mImageReader = ImageReader.newInstance(mWidth, mHeight, PixelFormat.RGBA_8888, 4);
mVirtualDisplay = mMediaProjection.createVirtualDisplay(TAG, mWidth, mHeight, mDPI,DisplayManager.VIRTUAL_DISPLAY_FLAG_AUTO_MIRROR, mImageReader.getSurface(), getimg(), null);
image = mImageReader.acquireLatestImage();
12-14 13:57:06.893: W/System.err(15177): java.lang.RuntimeException:
ImageReaderContext is not initialized 12-14 13:57:06.927:
W/System.err(15177): at
android.media.ImageReader.nativeImageSetup(Native Method) 12-14
13:57:06.961: W/System.err(15177): at
android.media.ImageReader.acquireNextSurfaceImage(ImageReader.java:298)
12-14 13:57:06.992: W/System.err(15177): at
android.media.ImageReader.acquireNextImage(ImageReader.java:344) 12-14
13:57:07.024: W/System.err(15177): at
com.zed1.luaservice.ScreenService.acquireLatestImage(ScreenService.java:109)
12-14 13:57:07.056: W/System.err(15177): at
com.top.colour.ColorUtil.snap(ColorUtil.java:89) 12-14 13:57:07.087:
W/System.err(15177): at
com.top.colour.FindImageFuzzy.execute(FindImageFuzzy.java:55) 12-14
13:57:07.111: W/System.err(15177): at
org.keplerproject.luajava.LuaState._call(Native Method) 12-14
13:57:07.138: W/System.err(15177): at
org.keplerproject.luajava.LuaState.call(LuaState.java:602) 12-14
13:57:07.165: W/System.err(15177): at
com.zed1.server.LuaService.call(LuaService.java:33) 12-14
13:57:07.193: W/System.err(15177): at
com.zed1.server.LuaThread.callLua(LuaThread.java:71) 12-14
13:57:07.220: W/System.err(15177): at
com.zed1.server.LuaThread.run(LuaThread.java:49)
I had the same issue, however not on my device but on one of my customers. I found someting on this site. They use the following code:
Image image;
try {
image = mImageReader.acquireLatestImage();
} catch (RuntimeException e) {
/* In API level 23 or below, it will throw "java.lang.RuntimeException:
ImageReaderContext is not initialized" when ImageReader is closed. To make the
behavior consistent as newer API levels, we make it return null Image instead.*/
if (isImageReaderContextNotInitializedException(e)) {
image = null;
} else {
throw e; // only catch RuntimeException:ImageReaderContext is not initialized
}
}
if (image == null) {
return null;
}
private boolean isImageReaderContextNotInitializedException(RuntimeException e) {
return "ImageReaderContext is not initialized".equals(e.getMessage());
}
I don't know yet, if it solves the issue, because the crash does not occur on my device. Let me know if it helps.
Related
When I do http request in the PoolData(), request returns with data, and in AccoutData is always null.
In debugger, if I wait 1-2 sec after PoolData(), next request - returns not null. Method oder doesn't metter. Why is that, and how can I wait for 2nd request?
public void onClick(View v) {
new PoolData().execute();
}
private class PoolData extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
dataPool.clear();
}
#Override
protected Void doInBackground(Void... arg0) {
PoolData();
AccoutData();
return null;
}
private void PoolData(){
HttpHandler sh = new HttpHandler();
String statsBrowser = "http://api.electroneum.space/v1/stats/nonBrowser";
String browserStr = sh.makeServiceCall(statsBrowser);
//parsing...
}
private void AccoutData(){
HttpHandler sh = new HttpHandler();
String statsAddress = "http://api.electroneum.space/v1/stats/address/" + settings.getString(lp, "n/a");
String addressStr = sh.makeServiceCall(statsAddress);
//parsing...
}
public class HttpHandler {
private static final String TAG = HttpHandler.class.getSimpleName();
public HttpHandler() {
}
public String makeServiceCall(String reqUrl) {
String response = null;
try {
URL url = new URL(reqUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
InputStream in = new BufferedInputStream(conn.getInputStream());
response = convertStreamToString(in);
Log.e(TAG, "Responce: " + response);
} catch (MalformedURLException e) {
Log.e(TAG, "MalformedURLException: " + e.toString());
} catch (ProtocolException e) {
Log.e(TAG, "ProtocolException: " + e.toString());
} catch (IOException e) {
Log.e(TAG, "IOException: " + e.toString());
} catch (Exception e) {
Log.e(TAG, "Exception: " + e.toString());
}
return response;
}
private String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line;
try {
while ((line = reader.readLine()) != null) {
sb.append(line).append('\n');
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
}
12-14 14:27:18.941 6624-6651/dev.flair.the.electroneumspacepool
I/OpenGLRenderer: Initialized EGL, version 1.4
12-14 14:27:18.956 6624-6651/dev.flair.the.electroneumspacepool I/OpenGLRenderer: Get enable program binary service property (1)
12-14 14:27:18.956 6624-6651/dev.flair.the.electroneumspacepool I/OpenGLRenderer: Initializing program atlas...
12-14 14:27:18.958 6624-6651/dev.flair.the.electroneumspacepool I/OpenGLRenderer: Program binary detail: Binary length is 169916, program map length is 152.
12-14 14:27:18.958 6624-6651/dev.flair.the.electroneumspacepool I/OpenGLRenderer: Succeeded to mmap program binaries. File descriptor is 54, and path is /dev/ashmem .
12-14 14:27:18.958 6624-6651/dev.flair.the.electroneumspacepool I/OpenGLRenderer: No need to use file discriptor anymore, close fd(54).
12-14 14:27:18.979 6624-6624/dev.flair.the.electroneumspacepool W/art: Before Android 4.1, method int android.support.v7.widget.ListViewCompat.lookForSelectablePosition(int, boolean) would have incorrectly overridden the package-private method in android.widget.ListView
12-14 14:27:19.035 6624-6651/dev.flair.the.electroneumspacepool W/MALI: glDrawArrays:714: [MALI] glDrawArrays takes more than 5ms here. Total elapse time(us): 10394
12-14 14:27:23.448 6624-6672/dev.flair.the.electroneumspacepool I/System.out: url:http://api.electroneum.space/v1/stats/address/hVDo4adTwWsPK1
12-14 14:27:23.452 6624-6672/dev.flair.the.electroneumspacepool I/System.out: open:http://api.electroneum.space/v1/stats/address/hVDo4adTwWsPK1
12-14 14:27:23.454 6624-6672/dev.flair.the.electroneumspacepool D/libc-netbsd: [getaddrinfo]: mtk hostname=api.electroneum.space; servname=(null); cache_mode=(null), netid=0; mark=0
12-14 14:27:23.454 6624-6672/dev.flair.the.electroneumspacepool D/libc-netbsd: getaddrinfo( app_uid:10085
12-14 14:27:23.454 6624-6672/dev.flair.the.electroneumspacepool D/libc-netbsd: getaddrinfo() uid prop:
12-14 14:27:23.454 6624-6672/dev.flair.the.electroneumspacepool D/libc-netbsd: getaddrinfo() getuid():10085
12-14 14:27:23.454 6624-6672/dev.flair.the.electroneumspacepool D/libc-netbsd: [getaddrinfo]: mtk ai_addrlen=0; ai_canonname=(null); ai_flags=4; ai_family=0
12-14 14:27:23.454 6624-6672/dev.flair.the.electroneumspacepool D/libc-netbsd: [getaddrinfo]: mtk hostname=api.electroneum.space; servname=(null); cache_mode=(null), netid=0; mark=0
12-14 14:27:23.454 6624-6672/dev.flair.the.electroneumspacepool D/libc-netbsd: getaddrinfo( app_uid:10085
12-14 14:27:23.454 6624-6672/dev.flair.the.electroneumspacepool D/libc-netbsd: getaddrinfo() uid prop:
12-14 14:27:23.454 6624-6672/dev.flair.the.electroneumspacepool D/libc-netbsd: getaddrinfo() getuid():10085
12-14 14:27:23.454 6624-6672/dev.flair.the.electroneumspacepool D/libc-netbsd: [getaddrinfo]: mtk ai_addrlen=0; ai_canonname=(null); ai_flags=1024; ai_family=0
12-14 14:27:23.457 6624-6672/dev.flair.the.electroneumspacepool D/libc-netbsd: getaddrinfo: api.electroneum.space get result from proxy >>
12-14 14:27:23.457 6624-6672/dev.flair.the.electroneumspacepool I/System.out: propertyValue:true
12-14 14:27:23.459 6624-6672/dev.flair.the.electroneumspacepool I/System.out: [CDS]connect[api.electroneum.space/104.27.156.123:80] tm:90
12-14 14:27:23.497 6624-6672/dev.flair.the.electroneumspacepool I/System.out: [OkHttp] sendRequest>>
12-14 14:27:23.497 6624-6672/dev.flair.the.electroneumspacepool I/System.out: [OkHttp] sendRequest<<
12-14 14:27:23.612 6624-6672/dev.flair.the.electroneumspacepool E/HttpHandler: MalformedURLException: java.io.BufferedInputStream#3d6a54f5
12-14 14:27:23.613 6624-6672/dev.flair.the.electroneumspacepool I/NetworkManagementSocketTagger: untagSocket(56)
12-14 17:08:49.897 19931-20613/dev.flair.the.electroneumspacepool E/HttpHandler: Responce:
{"stats":{"data...."}}
12-14 17:08:49.899 19931-20613/dev.flair.the.electroneumspacepool I/System.out: url:http://api.electroneum.space/v1/stats/nonBrowser
12-14 17:08:49.900 19931-20613/dev.flair.the.electroneumspacepool I/System.out: open:http://api.electroneum.space/v1/stats/nonBrowser
12-14 17:08:49.901 19931-20613/dev.flair.the.electroneumspacepool I/System.out: [OkHttp] sendRequest>>
12-14 17:08:49.901 19931-20613/dev.flair.the.electroneumspacepool I/System.out: [OkHttp] sendRequest<<
12-14 17:08:50.008 19931-20613/dev.flair.the.electroneumspacepool E/HttpHandler: IOException: java.io.FileNotFoundException: http://api.electroneum.space/v1/stats/nonBrowser
12-14 17:08:50.008 19931-20613/dev.flair.the.electroneumspacepool E/MainActivity: Response from browser: null
I'm trying to get a screenshot from a fragment, but seems that when I do
bitmap = view.getDrawingCache(); it returns null. Does anyone knows why is this happening and how can I fix this?
here is my code:
public void takeScreenshot(View view) {
OutputStream output;
view = view.getRootView();
view.setDrawingCacheEnabled(true);
view.buildDrawingCache(true);
File filepath = Environment.getExternalStorageDirectory();
File dir = new File(filepath + "/"
+ getString(R.string.app_name) + "/");
dir.mkdirs();
File file = new File(dir, getString(R.string.app_name) + ".jpg");
bitmap = view.getDrawingCache();
try {
output = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.PNG, 80, output);
output.flush();
output.close();
Log.d(TAG, "screenshot saved");
} catch (FileNotFoundException e1) {
e1.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
and calling the method
takeScreenshot(getActivity().findViewById(R.id.fragment_container));
and here is the logCat output:
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.contractfit/com.contractfit.activities.MainActivity}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2413)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2471)
at android.app.ActivityThread.access$900(ActivityThread.java:175)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1308)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:146)
at android.app.ActivityThread.main(ActivityThread.java:5602)
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:1283)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1099)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.contractfit.fragments.BaseFragment.takeScreenshot(BaseFragment.java:532)
at com.contractfit.fragments.MainFragment.init(MainFragment.java:211)
at com.contractfit.fragments.MainFragment.onCreateView(MainFragment.java:116)
at android.support.v4.app.Fragment.performCreateView(Fragment.java:1789)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:955)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1138)
at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:740)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1501)
at android.support.v4.app.FragmentActivity.onStart(FragmentActivity.java:551)
at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1177)
at android.app.Activity.performStart(Activity.java:5461)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2386)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2471)
at android.app.ActivityThread.access$900(ActivityThread.java:175)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1308)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:146)
at android.app.ActivityThread.main(ActivityThread.java:5602)
at java.lang.reflect.Method.invokeNative(Native Method)
Consider doing this like Instrumentation test cases do it, your code is close but differs a bit.
From https://android.googlesource.com/platform/external/droiddriver/+/367267b/src/io/appium/droiddriver/instrumentation/InstrumentationUiDevice.java
Get root view (if it's public):
context.getDriver().getRootElement().getRawElement()));
Take screenshot
public Bitmap call() {
Bitmap screenshot;
rootView.destroyDrawingCache();
rootView.buildDrawingCache(false);
Bitmap drawingCache = rootView.getDrawingCache();
int[] xy = new int[2];
rootView.getLocationOnScreen(xy);
if (xy[0] == 0 && xy[1] == 0) {
screenshot = Bitmap.createBitmap(drawingCache);
} else {
Canvas canvas = new Canvas();
Rect rect = new Rect(0, 0, drawingCache.getWidth(), drawingCache.getHeight());
rect.offset(xy[0], xy[1]);
screenshot =
Bitmap.createBitmap(rect.width() + xy[0], rect.height() + xy[1], Config.ARGB_8888);
canvas.setBitmap(screenshot);
canvas.drawBitmap(drawingCache, null, new RectF(rect), null);
canvas.setBitmap(null);
}
rootView.destroyDrawingCache();
return screenshot;
I got an exception while releasing camera object "java.lang.RuntimeException: Method called after release"
following is my code and exception stack trace.
if (camera != null) {
camera.stopPreview();
camera.release();
camera = null;
}
Exception stack trace -
java.lang.RuntimeException: Method called after release()
Thread[main,5,main] android.hardware.Camera._stopPreview(Native Method)
android.hardware.Camera.stopPreview(Camera.java:626)
com.s5.selfiemonkey1.activity.Preview.surfaceDestroyed(Preview.java:152)
android.view.SurfaceView.updateWindow(SurfaceView.java:601)
android.view.SurfaceView.access$000(SurfaceView.java:88)
android.view.SurfaceView$3.onPreDraw(SurfaceView.java:183)
android.view.ViewTreeObserver.dispatchOnPreDraw(ViewTreeObserver.java:680)
android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:2123)
android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1139)
android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:4872)
android.view.Choreographer$CallbackRecord.run(Choreographer.java:776)
android.view.Choreographer.doCallbacks(Choreographer.java:579)
android.view.Choreographer.doFrame(Choreographer.java:548)
android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:762)
android.os.Handler.handleCallback(Handler.java:800)
android.os.Handler.dispatchMessage(Handler.java:100)
android.os.Looper.loop(Looper.java:194)
android.app.ActivityThread.main(ActivityThread.java:5371)
java.lang.reflect.Method.invokeNative(Native Method)
java.lang.reflect.Method.invoke(Method.java:525)
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:833)
com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600)
it look like stopPreview() is called on released object.
I had made a method which would return me boolean depending of whether camera is in use or not. Below is a small snipet:
public static Camera checkForCamera(){
Camera camera = null;
try {
camera = Camera.open(); // this line will throw exception if camera is not in use.
}
catch (Exception e){
// if exception is thrown, return your boolean value here...
}
return camera; // if instance of camera, if it is not available it will return null.
}
I've looked around on SOF and haven't been able to find anything helpful.
First off, I'll say what is happening. When I run my widget, it all works fine until I hit a checkbox on a listView item and run this coding:
#Override
public void onClick(View v) {
if (addCheckbox.isChecked()) {
System.out.println("Checked");
PackageManager pm = mContext.getPackageManager();
final int DEST_IMAGE_WIDTH = 100;
final int DEST_IMAGE_HEIGHT = 100;
ApplicationInfo appInfo = mContext.getApplicationInfo();
Drawable appIcon = pm.getApplicationIcon(appInfo);
Bitmap appBmp = Bitmap.createBitmap(DEST_IMAGE_WIDTH, DEST_IMAGE_HEIGHT, Config.ARGB_8888);
// Creates a new canvas based on the image specification
// created just above.
Canvas canvas = new Canvas(appBmp);
// (optional) Fills the entire canvas
canvas.drawColor(Color.WHITE);
// You need to set bounds otherwise a 0,0 sized image would be drawn.
appIcon.setBounds(0, 0, DEST_IMAGE_WIDTH, DEST_IMAGE_HEIGHT);
appIcon.draw(canvas);
/// Let's save to a .jpg file ...
File file = new File(mContext.getFilesDir().getAbsolutePath() + "/test2.jpg");
FileOutputStream out;
try
{
file.createNewFile();
out = mContext.getApplicationContext().openFileOutput("BitmapImage", Context.MODE_PRIVATE);
appBmp.compress(Bitmap.CompressFormat.JPEG, 80, out);
Log.i("AppInfoAdapter", "the icon(s) have been saved");
out.close();
// Load back the image file to confirm it works
// Bitmap bitmap = BitmapFactory.decodeFile(file.getAbsolutePath() );
// ImageView imageV = (ImageView)findViewById(R.id.);
// imageV.setImageBitmap(bitmap);
}
catch (FileNotFoundException e1)
{
e1.printStackTrace();
}
catch (IOException e2)
{
e2.printStackTrace();
}
Intent intent = new Intent (v.getContext(), GridViewAdapter.class);
v.getContext().startActivity(intent);
Log.i("AppInfoAdapter", "New intent started to send icon bitmap");
} else {
System.out.println("Un-Checked");
}
Everything works great and I even get the Log message that "New intent started to send icon bitmap". However, as soon as this is done, I get this error:
12-14 13:47:54.413: E/AndroidRuntime(1785): FATAL EXCEPTION: main
12-14 13:47:54.413: E/AndroidRuntime(1785): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.awesomefilebuilderwidget/com.example.awesomefilebuilderwidget.GridViewAdapter}: java.lang.InstantiationException: com.example.awesomefilebuilderwidget.GridViewAdapter
12-14 13:47:54.413: E/AndroidRuntime(1785): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1746)
12-14 13:47:54.413: E/AndroidRuntime(1785): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1854)
12-14 13:47:54.413: E/AndroidRuntime(1785): at android.app.ActivityThread.access$1500(ActivityThread.java:135)
12-14 13:47:54.413: E/AndroidRuntime(1785): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1041)
12-14 13:47:54.413: E/AndroidRuntime(1785): at android.os.Handler.dispatchMessage(Handler.java:99)
12-14 13:47:54.413: E/AndroidRuntime(1785): at android.os.Looper.loop(Looper.java:150)
12-14 13:47:54.413: E/AndroidRuntime(1785): at android.app.ActivityThread.main(ActivityThread.java:4333)
12-14 13:47:54.413: E/AndroidRuntime(1785): at java.lang.reflect.Method.invokeNative(Native Method)
12-14 13:47:54.413: E/AndroidRuntime(1785): at java.lang.reflect.Method.invoke(Method.java:507)
12-14 13:47:54.413: E/AndroidRuntime(1785): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
12-14 13:47:54.413: E/AndroidRuntime(1785): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
12-14 13:47:54.413: E/AndroidRuntime(1785): at dalvik.system.NativeStart.main(Native Method)
12-14 13:47:54.413: E/AndroidRuntime(1785): Caused by: java.lang.InstantiationException: com.example.awesomefilebuilderwidget.GridViewAdapter
12-14 13:47:54.413: E/AndroidRuntime(1785): at java.lang.Class.newInstanceImpl(Native Method)
12-14 13:47:54.413: E/AndroidRuntime(1785): at java.lang.Class.newInstance(Class.java:1409)
12-14 13:47:54.413: E/AndroidRuntime(1785): at android.app.Instrumentation.newActivity(Instrumentation.java:1040)
12-14 13:47:54.413: E/AndroidRuntime(1785): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1738)
12-14 13:47:54.413: E/AndroidRuntime(1785): ... 11 more
This is the class in question:
package com.example.awesomefilebuilderwidget;
IMPORTS
public class GridViewAdapter extends BaseAdapter {
private Context Context;
// Keep all Images in array list
public ArrayList<Integer> drawables = new ArrayList<Integer>();
CheckBox mCheckBox=null;
// Constructor
public GridViewAdapter(Context c){
Context = c;
Log.d("GridViewAdapter", "Constructor is set");
drawables.add(R.drawable.pattern1);
Log.d("GridViewAdapter", "pattern1 added");
drawables.add(R.drawable.pattern2);
Log.d("GridViewAdapter", "pattern2 added");
drawables.add(R.drawable.trashcan);
Log.d("GridViewAdapter", "trashcan added");
drawables.add(R.drawable.ic_launcher);
Log.d("GridViewAdapter", "ic_launcher added");
}
public void setCheckBox(CheckBox checkbox){
mCheckBox=checkbox;
}
#Override
// How many items are in the data set represented by this Adapter
public int getCount() {
return drawables.size();
}
#Override
// Get the data item associated with the specified position in the
// data set
public Object getItem(int position) {
return drawables.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
public boolean isSdReadable() {
boolean mExternalStorageAvailable = false;
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
// We can read and write the media
mExternalStorageAvailable = true;
Log.i("isSdReadable", "External storage card is readable.");
} else if (Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
// We can only read the media
Log.i("isSdReadable", "External storage card is readable.");
mExternalStorageAvailable = true;
} else {
// Something else is wrong. It may be one of many other
// states, but all we need to know is we can neither read nor write
mExternalStorageAvailable = false;
}
return mExternalStorageAvailable;
}
public Bitmap getThumbnail() {
final String APP_PATH_SD_CARD = "/TEST/";
final String APP_THUMBNAIL_PATH_SD_CARD = "thumbnails";
String filename = "AFBWIcon.png";
String fullPath = Environment.getExternalStorageDirectory().getAbsolutePath() + APP_PATH_SD_CARD + APP_THUMBNAIL_PATH_SD_CARD;
Bitmap thumbnail = null;
// Look for the file on the external storage
try {
if (isSdReadable() == true) {
thumbnail = BitmapFactory.decodeFile(fullPath + "/" + filename);
}
} catch (Exception e) {
Log.e("getThumbnail() on external storage", e.getMessage());
}
// If no file on external storage, look in internal storage
if (thumbnail == null) {
try {
File filePath = Context.getFileStreamPath(filename);
FileInputStream fi = new FileInputStream(filePath);
thumbnail = BitmapFactory.decodeStream(fi);
} catch (Exception ex) {
Log.e("getThumbnail() on internal storage", ex.getMessage());
}
}
return thumbnail;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// Try to reuse the views
ImageView view = (ImageView) convertView;
boolean checked = (mCheckBox==null)?false:(((CheckBox) mCheckBox).isChecked());
// if convert view is null then create a new instance else reuse it
if (view == null) {
view = new ImageView(Context);
Log.d("GridViewAdapter", "new imageView added");
}
if(checked == true){
isSdReadable();
try {
Log.i("GridViewAdapter", "checkbox is checked");
FileInputStream in = Context.openFileInput("BitmapImage");
// Load back the image file to confirm it works
Bitmap bitmap = BitmapFactory.decodeStream(in);
view.setImageBitmap(bitmap);
in.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// getThumbnail();
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else {
Log.e("GridView", "Icons not for use/checkbox not checked");
}
view.setImageResource(drawables.get(position));
view.setScaleType(ImageView.ScaleType.CENTER_CROP);
view.setLayoutParams(new android.widget.GridView.LayoutParams(70, 70));
view.setTag(String.valueOf(position));
return view;
}
}
Also, this is my Manifest:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.awesomefilebuilderwidget"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="18" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<receiver android:name="com.example.awesomefilebuilderwidget.AFBWidget" android:label="#string/app_name">
<intent-filter>
<action android:name="android.appwidget.action.APPWIDGET_UPDATE"/>
</intent-filter>
<meta-data android:name="android.appwidget.provider"
android:resource="#xml/widget_stuff"/>
</receiver>
<activity android:name="com.example.awesomefilebuilderwidget.WidgetConfig" android:label="#string/app_name">
<intent-filter>
<action android:name="android.appwidget.action.APPWIDGET_CONFIGURE"/>
</intent-filter>
</activity>
<activity android:name="com.example.awesomefilebuilderwidget.Drag_and_Drop_App" android:label="#string/app_name" android:windowSoftInputMode="stateHidden" android:screenOrientation="portrait"></activity>
<activity android:name="com.example.awesomefilebuilderwidget.AppInfoAdapter" android:label="#string/app_name" ></activity>
<activity android:name="com.example.awesomefilebuilderwidget.Feedback" android:label="#string/app_name" ></activity>
<activity android:name="com.example.awesomefilebuilderwidget.GridView" android:label="#string/app_name" ></activity>
<activity android:name="com.example.awesomefilebuilderwidget.SendMessageActivity" android:label="#string/app_name" ></activity>
<activity android:name="com.example.awesomefilebuilderwidget.Utilities" android:label="#string/app_name" ></activity>
<activity android:name="com.example.awesomefilebuilderwidget.Personalize" android:label="#string/app_name" ></activity>
<activity android:name="com.example.awesomefilebuilderwidget.SwipeDetector" android:label="#string/app_name"></activity>
<activity android:name="com.example.awesomefilebuilderwidget.GridViewAdapter" android:label="#string/app_name"></activity>/
</application>
</manifest>
I was told that since it is an adapter, not an activity, I should remove it from my Manifest. But, when I do this, I get this error:
12-14 12:57:04.047: E/AndroidRuntime(708): android.content.ActivityNotFoundException: Unable to find explicit activity class {com.example.awesomefilebuilderwidget/com.example.awesomefilebuilderwidget.GridViewAdapter}; have you declared this activity in your AndroidManifest.xml?
It seems as though I am stuck between the choice of having the class or not.
I haven't had this issue up until now and I have tried cleaning my project.
Please help!
I was told that since it is an adapter, not an activity, I should remove it from my Manifest.
Correct.
But, when I do this, I get this error:
That would be because in your code shown above, you are calling startActivity() incorrectly, trying to start GridViewAdapter as an activity. GridViewAdapter is not an activity. If you want to start an activity, write an activity, add it to the manifest, and then call startActivity() for your newly-written activity.
You can learn more about activities in the documentation.
else if (v.getId() == R.id.update) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
try {
URL url = new URL("http://darkliteempire.gaming.multiplay.co.uk/testdownload.txt");
//create the new connection
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
//set up some things on the connection
urlConnection.setRequestMethod("GET");
urlConnection.setDoOutput(true);
//and connect!
urlConnection.connect();
//set the path where we want to save the file
//in this case, going to save it on the root directory of the
//sd card.
File SDCardRoot = new File("/sdcard/"+"download/");
//create a new file, specifying the path, and the filename
//which we want to save the file as.
File file = new File(SDCardRoot,"test.txt");
//this will be used to write the downloaded data into the file we created
FileOutputStream fileOutput = new FileOutputStream(file);
//this will be used in reading the data from the internet
InputStream inputStream = urlConnection.getInputStream();
//this is the total size of the file
int totalSize = urlConnection.getContentLength();
//variable to store total downloaded bytes
int downloadedSize = 0;
//create a buffer...
byte[] buffer = new byte[1024];
int bufferLength = 0; //used to store a temporary size of the buffer
//now, read through the input buffer and write the contents to the file
while ( (bufferLength = inputStream.read(buffer)) > 0 )
{
//add the data in the buffer to the file in the file output stream (the file on the sd card
fileOutput.write(buffer, 0, bufferLength);
//add up the size so we know how much is downloaded
downloadedSize += bufferLength;
int progress=(int)(downloadedSize*100/totalSize);
//this is where you would do something to report the prgress, like this maybe
//updateProgress(downloadedSize, totalSize);
}
//close the output stream when done
fileOutput.close();
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (ProtocolException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
this code keeps coming out with the FileNotFoundException, but the file is there, if you follow the url you can see it.
does it have to be hosted in a specific way? or is it something wrong with the way im getting it
EDIT: this is the logcat message
12-14 22:29:19.890: W/System.err(24557): java.io.FileNotFoundException: http://darkliteempire.gaming.multiplay.co.uk/testdownload.txt
12-14 22:29:19.890: W/System.err(24557): at libcore.net.http.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:177)
12-14 22:29:19.890: W/System.err(24557): at com.MasterZangetsu.kentrocksoc.MainActivity.onClick(MainActivity.java:99)
12-14 22:29:19.890: W/System.err(24557): at android.view.View.performClick(View.java:3591)
12-14 22:29:19.890: W/System.err(24557): at android.view.View$PerformClick.run(View.java:14263)
12-14 22:29:19.895: W/System.err(24557): at android.os.Handler.handleCallback(Handler.java:605)
12-14 22:29:19.895: W/System.err(24557): at android.os.Handler.dispatchMessage(Handler.java:92)
12-14 22:29:19.895: W/System.err(24557): at android.os.Looper.loop(Looper.java:137)
12-14 22:29:19.895: W/System.err(24557): at android.app.ActivityThread.main(ActivityThread.java:4507)
12-14 22:29:19.895: W/System.err(24557): at java.lang.reflect.Method.invokeNative(Native Method)
12-14 22:29:19.895: W/System.err(24557): at java.lang.reflect.Method.invoke(Method.java:511)
12-14 22:29:19.895: W/System.err(24557): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:790)
12-14 22:29:19.895: W/System.err(24557): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:557)
12-14 22:29:19.895: W/System.err(24557): at dalvik.system.NativeStart.main(Native Method)
12-14 22:29:20.170: W/WifiStateTracker(2010): getNetworkInfo : NetworkInfo: type: WIFI[], state: DISCONNECTED/DISCONNECTED, reason: (unspecified), extra: (none), roaming: false, failover: false, isAvailable: false
comment the below piece of line in your code.
urlConnection.setDoOutput(true);