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.
Related
After my tablet update to 4.4.2 my app crashes.
My log says at com.example.androidhive.EditProductActivity$6.onClick(EditProductActivity.java:344)
and the line is
bitmap.compress(Bitmap.CompressFormat.PNG, 90, out);
This is a part off my code (the bitmap code)
#Override
public void onClick(View v) {
btn_shoot.setVisibility(View.INVISIBLE);
View view = findViewById(R.id.relativelayout);
view.setDrawingCacheEnabled(true);
Bitmap bitmap = view.getDrawingCache();
BitmapDrawable bitmapDrawable = new BitmapDrawable(bitmap);
ImageView iv = (ImageView) findViewById(R.id.imageView1);
iv.setBackgroundDrawable(bitmapDrawable);
if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
//we check if external storage is available, otherwise display an error message to the user
File sdCard = Environment.getExternalStorageDirectory();
// .getExternalStorageDirectory() + "/Indflyt/ "+ inputNr.getText().toString() + ".pdf";
File directory = new File (sdCard.getAbsolutePath() + "/Indflyt");
directory.mkdirs();
String filename = inputNr.getText().toString() + "-"+ txtetDate.getText().toString() +".jpg";
File yourFile = new File(directory, filename);
while (yourFile.exists()) {
i++;
filename = "screenshot" + i + ".jpg";
yourFile = new File(directory, filename);
}
if (!yourFile.exists()) {
if (directory.canWrite())
{
try {
FileOutputStream out = new FileOutputStream(yourFile, true);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
out.flush();
out.close();
Toast.makeText(EditProductActivity.this, "Billede gemt i /sdcard/Indflyt/" + inputNr.getText().toString() + "-" + txtetDate.getText().toString() + ".jpg", Toast.LENGTH_SHORT).show();
i++;
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
else
{
Toast.makeText(EditProductActivity.this, "SD Card not available!", Toast.LENGTH_SHORT).show();
}
}
});
and my log
11-26 11:43:33.413: E/AndroidRuntime(24275): FATAL EXCEPTION: main
11-26 11:43:33.413: E/AndroidRuntime(24275): Process: com.example.androidhive, PID: 24275
11-26 11:43:33.413: E/AndroidRuntime(24275): java.lang.NullPointerException
11-26 11:43:33.413: E/AndroidRuntime(24275): at com.example.androidhive.EditProductActivity$6.onClick(EditProductActivity.java:344)
11-26 11:43:33.413: E/AndroidRuntime(24275): at android.view.View.performClick(View.java:4630)
11-26 11:43:33.413: E/AndroidRuntime(24275): at android.view.View$PerformClick.run(View.java:19340)
11-26 11:43:33.413: E/AndroidRuntime(24275): at android.os.Handler.handleCallback(Handler.java:733)
11-26 11:43:33.413: E/AndroidRuntime(24275): at andrid.os.Handler.dispatchMessage(Handler.java:95)
11-26 11:43:33.413: E/AndroidRuntime(24275): at android.os.Looper.loop(Looper.java:157)
11-26 11:43:33.413: E/AndroidRuntime(24275): at android.app.ActivityThread.main(ActivityThread.java:5377)
11-26 11:43:33.413: E/AndroidRuntime(24275): at java.lang.reflect.Method.invokeNative(Native Method)
11-26 11:43:33.413: E/AndroidRuntime(24275): at java.lang.reflect.Method.invoke(Method.java:515)
11-26 11:43:33.413: E/AndroidRuntime(24275): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1265)
11-26 11:43:33.413: E/AndroidRuntime(24275): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1081)
11-26 11:43:33.413: E/AndroidRuntime(24275): at dalvik.system.NativeStart.main(Native Method)
Any help?
Update
View view = findViewById(R.id.relativelayout);
view.setDrawingCacheEnabled(true);
Bitmap bitmap = view.getDrawingCache();
ImageView iv = (ImageView) findViewById(R.id.imageView1);
Drawable bitmapDrawable = null;
iv.setBackground(bitmapDrawable);
So I'm making a soundboard app and I'm trying to implement saving sounds as notifications. The problem, however, is that the app crashes as soon as the user confirms saving as notification.
Heres what I have so far:
private OnItemLongClickListener longClickListener = new OnItemLongClickListener() {
public boolean onItemLongClick(AdapterView<?> parent, View v,
final int position, long id) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
CharSequence[] menu = new CharSequence[1];
menu[0] = "Notification";
// menu[1] = "Ringtone";
builder.setTitle("Save As...").setItems(menu,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// The 'which' argument contains the index position
// of the selected item
switch (which) {
case 0:
if (saveAsNotification(getSounds()
.get(position))) {
Toast.makeText(getActivity(),
"Saved as Notification",
Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getActivity(),
"Failed to Save Notification",
Toast.LENGTH_SHORT).show();
}
break;
default:
break;
}
}
});
builder.create().show();
return true;
}
};
public boolean saveAsNotification(Sound sound) {
byte[] buffer = null;
InputStream fIn = getActivity().getBaseContext().getResources()
.openRawResource(sound.getSoundResourceId());
int size = 0;
try {
size = fIn.available();
buffer = new byte[size];
fIn.read(buffer);
fIn.close();
} catch (IOException e) {
e.printStackTrace();
return false;
}
String path = Environment.getExternalStorageDirectory().getPath()
+ "/media/audio/notifications/";
String filename = sound.getDescription() + ".ogg";
boolean exists = (new File(path)).exists();
if (!exists) {
new File(path).mkdirs();
}
FileOutputStream save;
try {
save = new FileOutputStream(path + filename);
save.write(buffer);
save.flush();
save.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
return false;
} catch (IOException e) {
e.printStackTrace();
return false;
}
getActivity().sendBroadcast(
new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri
.parse("file://" + path + filename)));
File k = new File(path, filename);
ContentValues values = new ContentValues();
values.put(MediaStore.MediaColumns.DATA, k.getAbsolutePath());
values.put(MediaStore.MediaColumns.TITLE, sound.getDescription());
values.put(MediaStore.MediaColumns.MIME_TYPE, "audio/ogg");
values.put(MediaStore.Audio.Media.ARTIST, "soundboarder");
values.put(MediaStore.Audio.Media.IS_RINGTONE, true);
values.put(MediaStore.Audio.Media.IS_NOTIFICATION, true);
values.put(MediaStore.Audio.Media.IS_ALARM, true);
values.put(MediaStore.Audio.Media.IS_MUSIC, false);
// Insert it into the database
getActivity().getContentResolver()
.insert(MediaStore.Audio.Media.getContentUriForPath(k
.getAbsolutePath()), values);
return true;
}
Here's the logcat output when it crashes:
10-21 18:56:54.315: W/ResourceType(19905): No known package when getting value for resource number 0xffffffff
10-21 18:56:54.315: D/AndroidRuntime(19905): Shutting down VM
10-21 18:56:54.315: W/dalvikvm(19905): threadid=1: thread exiting with uncaught exception (group=0x41510ba8)
10-21 18:56:54.315: E/AndroidRuntime(19905): FATAL EXCEPTION: main
10-21 18:56:54.315: E/AndroidRuntime(19905): Process: com.metrico.trailerparkboyssoundboard, PID: 19905
10-21 18:56:54.315: E/AndroidRuntime(19905): android.content.res.Resources$NotFoundException: Resource ID #0xffffffff
10-21 18:56:54.315: E/AndroidRuntime(19905): at android.content.res.Resources.getValue(Resources.java:1123)
10-21 18:56:54.315: E/AndroidRuntime(19905): at android.content.res.Resources.openRawResource(Resources.java:1038)
10-21 18:56:54.315: E/AndroidRuntime(19905): at android.content.res.Resources.openRawResource(Resources.java:1015)
10-21 18:56:54.315: E/AndroidRuntime(19905): at com.metrico.trailerparkboyssoundboard.fragments.SoundboardFragment.saveAsNotification(SoundboardFragment.java:130)
10-21 18:56:54.315: E/AndroidRuntime(19905): at com.metrico.trailerparkboyssoundboard.fragments.SoundboardFragment$1$1.onClick(SoundboardFragment.java:106)
10-21 18:56:54.315: E/AndroidRuntime(19905): at com.android.internal.app.AlertController$AlertParams$3.onItemClick(AlertController.java:941)
10-21 18:56:54.315: E/AndroidRuntime(19905): at android.widget.AdapterView.performItemClick(AdapterView.java:299)
10-21 18:56:54.315: E/AndroidRuntime(19905): at android.widget.AbsListView.performItemClick(AbsListView.java:1113)
10-21 18:56:54.315: E/AndroidRuntime(19905): at android.widget.AbsListView$PerformClick.run(AbsListView.java:2904)
10-21 18:56:54.315: E/AndroidRuntime(19905): at android.widget.AbsListView$3.run(AbsListView.java:3638)
10-21 18:56:54.315: E/AndroidRuntime(19905): at android.os.Handler.handleCallback(Handler.java:733)
10-21 18:56:54.315: E/AndroidRuntime(19905): at android.os.Handler.dispatchMessage(Handler.java:95)
10-21 18:56:54.315: E/AndroidRuntime(19905): at android.os.Looper.loop(Looper.java:136)
10-21 18:56:54.315: E/AndroidRuntime(19905): at android.app.ActivityThread.main(ActivityThread.java:5017)
10-21 18:56:54.315: E/AndroidRuntime(19905): at java.lang.reflect.Method.invokeNative(Native Method)
10-21 18:56:54.315: E/AndroidRuntime(19905): at java.lang.reflect.Method.invoke(Method.java:515)
10-21 18:56:54.315: E/AndroidRuntime(19905): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
10-21 18:56:54.315: E/AndroidRuntime(19905): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
10-21 18:56:54.315: E/AndroidRuntime(19905): at dalvik.system.NativeStart.main(Native Method)
The dialogue box pops of fine, but as soon as I click on "save as notification", the app crashes.
I think that this part of the code causes the error
InputStream fIn = getActivity().getBaseContext().getResources().openRawResource(sound.getSoundResourceId());
The error message says you are trying to open the resource with the ID -1, make sure getSoundResourceId() returns the correct ID number.
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.
I'm new to Android programming. My application crashes while creating a socket. I added to the Manifest internet permission, and Wifi is on. I have a server on a PC waiting for the Android client; it works well with my other applications. I don't know where the problem with is this application. I'd appreciate any help.
Log errors
01-23 13:10:32.110: E/AndroidRuntime(4493): FATAL EXCEPTION: main
01-23 13:10:32.110: E/AndroidRuntime(4493): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.usapp/com.example.usapp.Settings}: android.os.NetworkOnMainThreadException
01-23 13:10:32.110: E/AndroidRuntime(4493): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1751)
01-23 13:10:32.110: E/AndroidRuntime(4493): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1767)
01-23 13:10:32.110: E/AndroidRuntime(4493): at android.app.ActivityThread.access$1500(ActivityThread.java:122)
01-23 13:10:32.110: E/AndroidRuntime(4493): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1005)
01-23 13:10:32.110: E/AndroidRuntime(4493): at android.os.Handler.dispatchMessage(Handler.java:99)
01-23 13:10:32.110: E/AndroidRuntime(4493): at android.os.Looper.loop(Looper.java:132)
01-23 13:10:32.110: E/AndroidRuntime(4493): at android.app.ActivityThread.main(ActivityThread.java:4028)
01-23 13:10:32.110: E/AndroidRuntime(4493): at java.lang.reflect.Method.invokeNative(Native Method)
01-23 13:10:32.110: E/AndroidRuntime(4493): at java.lang.reflect.Method.invoke(Method.java:491)
01-23 13:10:32.110: E/AndroidRuntime(4493): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:844)
01-23 13:10:32.110: E/AndroidRuntime(4493): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:602)
01-23 13:10:32.110: E/AndroidRuntime(4493): at dalvik.system.NativeStart.main(Native Method)
01-23 13:10:32.110: E/AndroidRuntime(4493): Caused by: android.os.NetworkOnMainThreadException
01-23 13:10:32.110: E/AndroidRuntime(4493): at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1077)
01-23 13:10:32.110: E/AndroidRuntime(4493): at dalvik.system.BlockGuard$WrappedNetworkSystem.connect(BlockGuard.java:368)
01-23 13:10:32.110: E/AndroidRuntime(4493): at org.apache.harmony.luni.net.PlainSocketImpl.connect(PlainSocketImpl.java:208)
01-23 13:10:32.110: E/AndroidRuntime(4493): at org.apache.harmony.luni.net.PlainSocketImpl.connect(PlainSocketImpl.java:431)
01-23 13:10:32.110: E/AndroidRuntime(4493): at java.net.Socket.connect(Socket.java:901)
01-23 13:10:32.110: E/AndroidRuntime(4493): at java.net.Socket.connect(Socket.java:844)
01-23 13:10:32.110: E/AndroidRuntime(4493): at com.example.usapp.Stream.doInBackground(Stream.java:46)
01-23 13:10:32.110: E/AndroidRuntime(4493): at com.example.usapp.Settings.onCreate(Settings.java:37)
01-23 13:10:32.110: E/AndroidRuntime(4493): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1048)
01-23 13:10:32.110: E/AndroidRuntime(4493): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1715)
01-23 13:10:32.110: E/AndroidRuntime(4493): ... 11 more
Java class
package com.example.usapp;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
import java.net.UnknownHostException;
import java.nio.ByteBuffer;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Handler;
import android.util.Log;
public class Stream extends AsyncTask<Void, Void, Void>{
Bitmap image;
int frameCounter=0;
int checkCounterFPS=0;
long lastFpsTime=0;
double FPS;
protected Handler handler_bitmap, handlerdata;
boolean firstSetOfFPS=false;
double availableFPS;
double toleranceValue;
boolean firstFalseFPS = false;
byte[] datainput = new byte[1024];
Socket socket;
#Override
protected Void doInBackground(Void... params) {
Log.i("DUPA","po String doInBackground(String... params) ");
try {
Log.i("DUPA","przed socket");
socket = new Socket();
InetSocketAddress adres = new InetSocketAddress("192.168.1.50", 4444);
//adres.
socket.connect(adres);
//socket = new Socket("192.168.1.50", 4444);
Log.i("DUPA","po socket");
BufferedInputStream in = new BufferedInputStream(socket.getInputStream());
Log.i("DUPA","po socketconnected ");
/*
do {
try {
ByteBuffer buffer = ByteBuffer.allocate(9);
in.read(buffer.array());
byte[] bBuffer = new byte[9];
buffer.get(bBuffer, 0, 9);
int len = Integer.parseInt(new String(bBuffer,"US-ASCII"));
int bytesRecieved = 0;
ByteBuffer completeBuf;
completeBuf = ByteBuffer.allocate(len);
while (len > bytesRecieved) {
int inSize = in.available();
if (inSize > len- bytesRecieved) {
buffer = ByteBuffer.allocate(len- bytesRecieved);
bytesRecieved += len- bytesRecieved;
in.read(buffer.array());
completeBuf.put(buffer);
} else {
bytesRecieved += inSize;
buffer = ByteBuffer.allocate(inSize);
in.read(buffer.array());
completeBuf.put(buffer);
}
}
frameCounter++;
long delay = (long) (System.currentTimeMillis() - lastFpsTime);
if (delay > 1000) {
checkCounterFPS++;
FPS = (((double) frameCounter) / delay) * 1000;
handler_bitmap.post(new Runnable() {
public void run() {
///usunieto fps set text
}
});
frameCounter = 0;
lastFpsTime = System.currentTimeMillis();
}
if (checkCounterFPS >= 3 && firstSetOfFPS == true) {
checkCounterFPS = 0;
if (FPS <= ((double) availableFPS - toleranceValue)
|| FPS >= ((double) availableFPS + toleranceValue)) {
firstFalseFPS = true;
}
} else if (firstFalseFPS == true) {
if (FPS <= ((double) availableFPS - toleranceValue)
|| FPS >= ((double) availableFPS + toleranceValue)) {
// setSendText("FPS",(int) FPS);
firstFalseFPS = false;
}
}
//publishProgress(completeBuf);
} catch (NumberFormatException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.i("DUPA","blad1");
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.i("DUPA","blad2");
}
} while (!socket.isInputShutdown() && !socket.isClosed()); //
// publishProgress("Status: Closed".getBytes());*/
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Log.i("DUPA","blad3");
}
Log.i("AsyncTask", "doInBackground: Finished");
return null;
}
protected Bitmap onProgressUpdate(ByteBuffer... values) {
Log.i("DUPA","blad4");
return image = BitmapFactory.decodeByteArray(values[0].array(), 0,values[0].array().length);
}
}
As correctly pointed out by others, android does not allow networking operations on the main UI thread since Honeycomb and higher versions. I can see that you have created a class extending AsyncTask, which is a special class provided by android for doing background operations. You need to create a separate activity and trigger your AsyncTask from it. That way the code within doInBackground() will execute in a separate thread and will not block your main activity.
eg., you can make your Stream class an inner class to another activity add the following code to the onCreate() method of the activity
Stream task = new Stream();
task.execute();
As #pingw33n mentioned in his comement, the Android network connection has to be done in an AsyncTask thread, not in the main thread. This worked in older versions of android but in the newest ones, your network connection can't be done in the main thread.
I'm working on some code which fills a GridView full of images that have been pulled from YouTube. Now its working apart from when it can't find an image, I'm not sure why it can't find the image as the image link works in a browser but this actually works to my advantage as it weeds out videos that have been removed due to copyright/account closure etc.
My code to get the image is as follows
Call
final Object item = allMatches.get(position);
if(item != null) {
Bitmap bitmap = loadBitmap("http://i2.ytimg.com/vi/"+ allMatches.get(position).toString() + "/default.jpg");
imageView.setImageBitmap(bitmap);
}
else { imageView.setImageDrawable(getResources().getDrawable(R.drawable.default1)); }
loadBitmap()
public static Bitmap loadBitmap(String url)
{
Bitmap bitmap = null;
InputStream in = null;
BufferedOutputStream out = null;
try {
in = new BufferedInputStream(new URL(url).openStream(), 4 * 1024);
final ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
out = new BufferedOutputStream(dataStream, 4 * 1024);
int byte_;
while ((byte_ = in.read()) != -1)
out.write(byte_);
out.flush();
final byte[] data = dataStream.toByteArray();
BitmapFactory.Options options = new BitmapFactory.Options();
//options.inSampleSize = 1;
bitmap = BitmapFactory.decodeByteArray(data, 0, data.length,options);
} catch (IOException e) {
Log.e("","Could not load Bitmap from: " + url);
} finally {
try{
in.close();
out.close();
}catch( IOException e )
{
System.out.println(e);
}
}
return bitmap;
So this will sometimes crash with the following Stacktrace
03-23 01:47:10.087: E/(9757): Could not load Bitmap from: http://i2.ytimg.com/vi/8s3lnGuyC9M/default.jpg
03-23 01:47:10.247: W/dalvikvm(9757): threadid=1: thread exiting with uncaught exception (group=0x40018560)
03-23 01:47:10.267: E/AndroidRuntime(9757): FATAL EXCEPTION: main
03-23 01:47:10.267: E/AndroidRuntime(9757): java.lang.NullPointerException
03-23 01:47:10.267: E/AndroidRuntime(9757): at com.myapp.Sample.loadBitmap(Sample.java:159)
03-23 01:47:10.267: E/AndroidRuntime(9757): at com.myapp..Sample$ImageAdapter.getView(Sample.java:207)
03-23 01:47:10.267: E/AndroidRuntime(9757): at android.widget.AbsListView.obtainView(AbsListView.java:1467)
03-23 01:47:10.267: E/AndroidRuntime(9757): at android.widget.GridView.onMeasure(GridView.java:935)
03-23 01:47:10.267: E/AndroidRuntime(9757): at android.view.View.measure(View.java:8330)
03-23 01:47:10.267: E/AndroidRuntime(9757): at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:3138)
03-23 01:47:10.267: E/AndroidRuntime(9757): at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1017)
03-23 01:47:10.267: E/AndroidRuntime(9757): at android.widget.LinearLayout.measureVertical(LinearLayout.java:386)
03-23 01:47:10.267: E/AndroidRuntime(9757): at android.widget.LinearLayout.onMeasure(LinearLayout.java:309)
03-23 01:47:10.267: E/AndroidRuntime(9757): at android.view.View.measure(View.java:8330)
03-23 01:47:10.267: E/AndroidRuntime(9757): at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:3138)
03-23 01:47:10.267: E/AndroidRuntime(9757): at android.widget.FrameLayout.onMeasure(FrameLayout.java:250)
03-23 01:47:10.267: E/AndroidRuntime(9757): at android.view.View.measure(View.java:8330)
03-23 01:47:10.267: E/AndroidRuntime(9757): at android.widget.LinearLayout.measureVertical(LinearLayout.java:531)
03-23 01:47:10.267: E/AndroidRuntime(9757): at android.widget.LinearLayout.onMeasure(LinearLayout.java:309)
03-23 01:47:10.267: E/AndroidRuntime(9757): at android.view.View.measure(View.java:8330)
03-23 01:47:10.267: E/AndroidRuntime(9757): at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:3138)
03-23 01:47:10.267: E/AndroidRuntime(9757): at android.widget.FrameLayout.onMeasure(FrameLayout.java:250)
03-23 01:47:10.267: E/AndroidRuntime(9757): at android.view.View.measure(View.java:8330)
03-23 01:47:10.267: E/AndroidRuntime(9757): at android.view.ViewRoot.performTraversals(ViewRoot.java:843)
03-23 01:47:10.267: E/AndroidRuntime(9757): at android.view.ViewRoot.handleMessage(ViewRoot.java:1865)
03-23 01:47:10.267: E/AndroidRuntime(9757): at android.os.Handler.dispatchMessage(Handler.java:99)
03-23 01:47:10.267: E/AndroidRuntime(9757): at android.os.Looper.loop(Looper.java:130)
03-23 01:47:10.267: E/AndroidRuntime(9757): at android.app.ActivityThread.main(ActivityThread.java:3835)
03-23 01:47:10.267: E/AndroidRuntime(9757): at java.lang.reflect.Method.invokeNative(Native Method)
03-23 01:47:10.267: E/AndroidRuntime(9757): at java.lang.reflect.Method.invoke(Method.java:507)
03-23 01:47:10.267: E/AndroidRuntime(9757): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:847)
03-23 01:47:10.267: E/AndroidRuntime(9757): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:605)
03-23 01:47:10.267: E/AndroidRuntime(9757): at dalvik.system.NativeStart.main(Native Method)
What I need to do is just be able to deal with it not being able to retrieve the image. My Java skills are limited but I want something like the below (but actually working)
Bitmap bitmap = loadBitmap("http://i2.ytimg.com/vi/"+ allMatches.get(position).toString() + "/default.jpg"); //
if (bitmap == null) {
imageView.setImageBitmap(defaultBitmap);
} else {
imageView.setImageBitmap(bitmap); }
or
//Doesn't work anyway due to 'Exception IOException is not compatible with throws clause in Adapter.getView'
try {
Bitmap bitmap = loadBitmap("http://i2.ytimg.com/vi/"+ allMatches.get(position).toString() + "/default.jpg");
imageView.setImageBitmap(bitmap);
}catch( IOException ) {
imageView.setImageBitmap(defaultBitmap);
}
My understanding of try catch blocks is that if you 'catch the error' the code should continue. In this case shouldn't it just be printing the error to the log and carrying on?
How can I do this for when 'loadBitmap' fails at retrieving the image?
EDIT: I have updated the code as per some user comments - it still provides the exact same error, it just removes some doubt around the point of failure. Also, to clarify
Line 159: in.close();
Line 207: Bitmap bitmap = loadBitmap("http://i2.ytimg.com/vi/"+ allMatches.get(position).toString() + "/default.jpg");
First:
try
{
Bitmap bitmap = loadBitmap("http://i2.ytimg.com/vi/"+ allMatches.get(position).toString() + "/default.jpg");
imageView.setImageBitmap(bitmap);
}
catch(IOException e)
{
System.err.println("Couldn't load image: "+e.getMessage());
imageView.setImageDrawable(getResources().getDrawable(R.drawable.default1));
}
Second:
public static Bitmap loadBitmap(String url) throws IOException
{
final InputStream in = new BufferedInputStream(new URL(url).openStream(), 4 * 1024);
try
{
final ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
final BufferedOutputStream out = new BufferedOutputStream(dataStream, 4 * 1024);
try
{
int byte_;
while ((byte_ = in.read()) != -1)
out.write(byte_);
out.flush();
final byte[] data = dataStream.toByteArray();
BitmapFactory.Options options = new BitmapFactory.Options();
//options.inSampleSize = 1;
return BitmapFactory.decodeByteArray(data, 0, data.length,options);
}
finally
{
out.close();
}
}
finally
{
in.close();
}
}
This is the error:
catch (IOException e)
{
Log.e("","Could not load Bitmap from: " + url);
// If IOExceotion occurs, the `bitmap` variable is null, right?
bitmap = bitmap.loadBitmap("http://i2.ytimg.com/vi/k4v9JWUhveY/default.jpg");
// ^^^^^^ NullPointerException will be thrown and IOException will be lost (overwritten by NullPointerException).
}
I was going to say the same as edthethird. You should avoid catching an Exception when possible. You say it is not working, so could you tell us which are the lines 159 and 207 of you Sample.java class, where the NullPointerException occured ? It would be of great help to understand the problem.
Where does this line point to ? It doesn't seem like you quote it in you question:
03-23 01:47:10.267: E/AndroidRuntime(9757): at com.myapp..Sample$ImageAdapter.getView(Sample.java:207)
And why don't you set the default image as a local drawable instead of pulling it from a website ?