I am trying to show SD Card image into ImageView and getting OutOfMemory error.
Please let me know How can i show SDCard's images into ImageView (no matter how big they are.)
I know we can use, these properties to control on it, but i am looking for the best solution :
android:hardwareAccelerated="false"
android:largeHeap="true"
Logcat:
08-05 11:27:34.530: E/AndroidRuntime(8158): FATAL EXCEPTION: main
08-05 11:27:34.530: E/AndroidRuntime(8158): java.lang.OutOfMemoryError
08-05 11:27:34.530: E/AndroidRuntime(8158): at android.graphics.BitmapFactory.nativeDecodeStream(Native Method)
08-05 11:27:34.530: E/AndroidRuntime(8158): at android.graphics.BitmapFactory.decodeStream(BitmapFactory.java:650)
08-05 11:27:34.530: E/AndroidRuntime(8158): at android.graphics.BitmapFactory.decodeFile(BitmapFactory.java:389)
08-05 11:27:34.530: E/AndroidRuntime(8158): at android.graphics.BitmapFactory.decodeFile(BitmapFactory.java:449)
08-05 11:27:34.530: E/AndroidRuntime(8158): at com.physic.UploadActivity.previewMedia(UploadActivity.java:171)
08-05 11:27:34.530: E/AndroidRuntime(8158): at com.physic.UploadActivity.onCreate(UploadActivity.java:109)
08-05 11:27:34.530: E/AndroidRuntime(8158): at android.app.Activity.performCreate(Activity.java:5191)
08-05 11:27:34.530: E/AndroidRuntime(8158): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1094)
08-05 11:27:34.530: E/AndroidRuntime(8158): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2074)
08-05 11:27:34.530: E/AndroidRuntime(8158): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2135)
08-05 11:27:34.530: E/AndroidRuntime(8158): at android.app.ActivityThread.access$700(ActivityThread.java:140)
08-05 11:27:34.530: E/AndroidRuntime(8158): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1237)
08-05 11:27:34.530: E/AndroidRuntime(8158): at android.os.Handler.dispatchMessage(Handler.java:99)
08-05 11:27:34.530: E/AndroidRuntime(8158): at android.os.Looper.loop(Looper.java:137)
08-05 11:27:34.530: E/AndroidRuntime(8158): at android.app.ActivityThread.main(ActivityThread.java:4921)
08-05 11:27:34.530: E/AndroidRuntime(8158): at java.lang.reflect.Method.invokeNative(Native Method)
08-05 11:27:34.530: E/AndroidRuntime(8158): at java.lang.reflect.Method.invoke(Method.java:511)
08-05 11:27:34.530: E/AndroidRuntime(8158): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1036)
08-05 11:27:34.530: E/AndroidRuntime(8158): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:803)
08-05 11:27:34.530: E/AndroidRuntime(8158): at dalvik.system.NativeStart.main(Native Method)
Code:
/**
* Displaying captured image/video on the screen
* */
private void previewMedia(boolean isImage) {
// Checking whether captured media is image or video
if (isImage) {
imgPreview.setVisibility(View.VISIBLE);
final Bitmap bitmap = BitmapFactory.decodeFile(filePath);
ExifInterface exif = null;
try {
exif = new ExifInterface(filePath);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
int orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION,
ExifInterface.ORIENTATION_UNDEFINED);
Bitmap bmRotated = rotateBitmap(bitmap, orientation);
imgPreview.setImageBitmap(bmRotated);
} else {
imgPreview.setVisibility(View.GONE);
}
}
Using Picasso Lib:
Picasso.with(UploadActivity.this)
.load(new File(filePath)).rotate(90)
.fit().centerInside()
.error(R.drawable.ic_launcher)
.placeholder(R.drawable.ic_launcher)
.into(imgPreview);
And even tried with this:
.transform(transformation)
Log:
Log.d("file:", filePath);
D/file:(6201): /storage/sdcard0/Pictures/Testing/LICPolicy20150805120029.jpg
Tried with Picasso lib but not showing image preview ..
OutOfMemoryException occur when your image is too large and your device is not able to render it so what you can do is to down scale the image according to your need below is the code for downscaling
public static Bitmap compressed_Bitmap(Bitmap bitmap) {
final int maxSize = 700;
int outWidth;
int outHeight;
int inWidth = bitmap.getWidth();
int inHeight = bitmap.getHeight();
if (inWidth > inHeight) {
outWidth = maxSize;
outHeight = (inHeight * maxSize) / inWidth;
} else {
outHeight = maxSize;
outWidth = (inWidth * maxSize) / inHeight;
}
Bitmap resizedBitmap = Bitmap.createScaledBitmap(bitmap, outWidth, outHeight, false);
return resizedBitmap;
}
Related
Hello guys I am making an Android app that convert from binary to decimal and I have made a class called Binary and a class called Decimal and a function in the Binary class that convert from decimal to binary
public Binary DtoB(Decimal decimal)
{
String temp = null;
do
{
if(decimal.decimal%2!=0)
temp+='1';
else
temp+='0';
decimal.decimal/=2;
}while(decimal.decimal>0);
while(temp.length()%4!=0)
temp+='0';
for(int i=temp.length()-1;i>=0;i--)
{
this.bn+=temp.charAt(i);
}
return this;
}
and in the activity there's a button that converts, but when I test and press on the button the app breaks
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
d1.decimal=Integer.parseInt(e1.getText().toString());
b.DtoB(d1);
t1.setText(b.bn);
}
});
can any one help me please ???
Here is the logcat:
10-26 09:16:15.831: E/AndroidRuntime(280): FATAL EXCEPTION: main
10-26 09:16:15.831: E/AndroidRuntime(280): java.lang.NullPointerException
10-26 09:16:15.831: E/AndroidRuntime(280): at com.example.converter.MainActivity$1.onClick(MainActivity.java:34)
10-26 09:16:15.831: E/AndroidRuntime(280): at android.view.View.performClick(View.java:2408)
10-26 09:16:15.831: E/AndroidRuntime(280): at android.view.View$PerformClick.run(View.java:8816)
10-26 09:16:15.831: E/AndroidRuntime(280): at android.os.Handler.handleCallback(Handler.java:587)
10-26 09:16:15.831: E/AndroidRuntime(280): at android.os.Handler.dispatchMessage(Handler.java:92)
10-26 09:16:15.831: E/AndroidRuntime(280): at android.os.Looper.loop(Looper.java:123) 10-26 09:16:15.831: E/AndroidRuntime(280): at android.app.ActivityThread.main(ActivityThread.java:4627)
10-26 09:16:15.831: E/AndroidRuntime(280): at java.lang.reflect.Method.invokeNative(Native Method) 10-26 09:16:15.831: E/AndroidRuntime(280): at java.lang.reflect.Method.invoke(Method.java:521)
Try this...!
public class BinaryToDecimal {
public int getDecimalFromBinary(int binary){
int decimal = 0;
int power = 0;
while(true){
if(binary == 0){
break;
} else {
int tmp = binary%10;
decimal += tmp*Math.pow(2, power);
binary = binary/10;
power++;
}
}
return decimal;
}
public static void main(String a[]){
BinaryToDecimal bd = new BinaryToDecimal();
System.out.println("11 ===> "+bd.getDecimalFromBinary(11));
System.out.println("110 ===> "+bd.getDecimalFromBinary(110));
System.out.println("100110 ===> "+bd.getDecimalFromBinary(100110));
}
}
check variable all are initialize perfectly . because some time objectc are created but it is null so can't work and throw java.lang.NullPointerException .....
b1 , d1 , b ,t1
I'm new in android programming. I'm writing simple application that should execute sql file, in first run. But it seems that this process take couple of seconds so I figure that application should show progressDialog while it will be executing sql file. But when I try to run application, dialog is showing with message "app has stopped ...". Please help me.
#Override
public void onCreate(SQLiteDatabase database)
{
String CREATE_BIBLE_TABLE = "CREATE TABLE bible (" +
"id INTEGER PRIMARY KEY AUTOINCREMENT, " +
"book INTEGER, " +
"chapter INTEGER NOT NULL, " +
"verse INTEGER NOT NULL, " +
"content TEXT" +
")";
database.execSQL(CREATE_BIBLE_TABLE);
new FirstLoadAsyncTask(database).execute();
}
public class FirstLoadAsyncTask extends AsyncTask<Void, Void, Void>
{
private SQLiteDatabase database;
private ProgressDialog progressDialog;
public FirstLoadAsyncTask(SQLiteDatabase database)
{
this.database = database;
}
#Override
protected void onPreExecute()
{
((Activity) context).runOnUiThread(new Runnable()
{
#Override
public void run()
{
progressDialog = ProgressDialog.show(context, "Loading...", "");
}
});
}
#Override
protected Void doInBackground(Void... params)
{
try
{
InputStream inputStream = context.getAssets().open("bible.sql");
execSqlFile(database, inputStream);
} catch(IOException e)
{
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result)
{
progressDialog.dismiss();
}
}
Class extends SQLiteOpenHelper.
Edit:
Logcat:
01-06 18:27:53.221 14118-14118/pl.several27.Biblia_Warszawska E/Trace﹕ error opening trace file: No such file or directory (2)
01-06 18:27:53.891 14118-14118/pl.several27.Biblia_Warszawska I/Adreno200-EGL﹕ <qeglDrvAPI_eglInitialize:299>: EGL 1.4 QUALCOMM build: AU_LINUX_ANDROID_JB_REL_2.0.3.04.01.02.21.081_msm7627a_JB_REL_2.0.3_CL2820657_release_AU (CL2820657)
Build Date: 01/22/13 Tue
Local Branch:
Remote Branch: quic/jb_rel_2.0.3
Local Patches: NONE
Reconstruct Branch: AU_LINUX_ANDROID_JB_REL_2.0.3.04.01.02.21.081 + NOTHING
01-06 18:27:54.001 14118-14118/pl.several27.Biblia_Warszawska E/copybit﹕ Error opening frame buffer errno=13 (Permission denied)
01-06 18:27:54.001 14118-14118/pl.several27.Biblia_Warszawska W/Adreno200-EGLSUB﹕ <updater_create_surface_state:342>: updater_create_surface_state failed to open copybit, error: -13
01-06 18:27:54.011 14118-14118/pl.several27.Biblia_Warszawska D/memalloc﹕ ion: Mapped buffer base:0x53be8000 size:1536000 offset:0 fd:61
01-06 18:27:54.021 14118-14118/pl.several27.Biblia_Warszawska D/memalloc﹕ ion: Mapped buffer base:0x5083a000 size:4096 offset:0 fd:63
01-06 18:27:54.381 14118-14118/pl.several27.Biblia_Warszawska D/memalloc﹕ ion: Mapped buffer base:0x541fb000 size:1536000 offset:0 fd:66
01-06 18:27:54.381 14118-14118/pl.several27.Biblia_Warszawska D/memalloc﹕ ion: Mapped buffer base:0x50a50000 size:4096 offset:0 fd:68
01-06 18:27:54.501 14118-14118/pl.several27.Biblia_Warszawska D/memalloc﹕ ion: Mapped buffer base:0x54472000 size:1536000 offset:0 fd:70
01-06 18:27:54.501 14118-14118/pl.several27.Biblia_Warszawska D/memalloc﹕ ion: Mapped buffer base:0x50c75000 size:4096 offset:0 fd:72
01-06 18:27:55.001 14118-14118/pl.several27.Biblia_Warszawska D/memalloc﹕ ion: Mapped buffer base:0x545e9000 size:1536000 offset:0 fd:74
01-06 18:27:55.001 14118-14118/pl.several27.Biblia_Warszawska D/memalloc﹕ ion: Mapped buffer base:0x50d4c000 size:4096 offset:0 fd:76
01-06 18:27:57.231 14118-14118/pl.several27.Biblia_Warszawska D/book choosen﹕ 1
01-06 18:27:57.581 14118-14118/pl.several27.Biblia_Warszawska W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0x40ca4540)
01-06 18:27:57.601 14118-14118/pl.several27.Biblia_Warszawska E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo{pl.several27.Biblia_Warszawska/pl.several27.Biblia_Warszawska.ChapterActivity}: java.lang.ClassCastException: android.app.Application cannot be cast to android.app.Activity
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2355)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2391)
at android.app.ActivityThread.access$600(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1335)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:155)
at android.app.ActivityThread.main(ActivityThread.java:5520)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1029)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:796)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.ClassCastException: android.app.Application cannot be cast to android.app.Activity
at pl.several27.Biblia_Warszawska.Database$FirstLoadAsyncTask.onPreExecute(Database.java:58)
at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:586)
at android.os.AsyncTask.execute(AsyncTask.java:534)
at pl.several27.Biblia_Warszawska.Database.onCreate(Database.java:42)
at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:252)
at android.database.sqlite.SQLiteOpenHelper.getReadableDatabase(SQLiteOpenHelper.java:188)
at pl.several27.Biblia_Warszawska.Database.countChapters(Database.java:148)
at pl.several27.Biblia_Warszawska.ChapterActivity.onCreate(ChapterActivity.java:32)
at android.app.Activity.performCreate(Activity.java:5066)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1101)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2311)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2391)
at android.app.ActivityThread.access$600(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1335)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:155)
at android.app.ActivityThread.main(ActivityThread.java:5520)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1029)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:796)
at dalvik.system.NativeStart.main(Native Method)
01-06 18:27:59.511 14118-14118/pl.several27.Biblia_Warszawska D/Process﹕ killProcess, pid=14118
01-06 18:27:59.521 14118-14118/pl.several27.Biblia_Warszawska D/Process﹕ dalvik.system.VMStack.getThreadStackTrace(Native Method)
01-06 18:27:59.521 14118-14118/pl.several27.Biblia_Warszawska D/Process﹕ java.lang.Thread.getStackTrace(Thread.java:599)
01-06 18:27:59.521 14118-14118/pl.several27.Biblia_Warszawska D/Process﹕ android.os.Process.killProcess(Process.java:956)
01-06 18:27:59.521 14118-14118/pl.several27.Biblia_Warszawska D/Process﹕ com.android.internal.os.RuntimeInit$UncaughtHandler.uncaughtException(RuntimeInit.java:108)
01-06 18:27:59.531 14118-14118/pl.several27.Biblia_Warszawska D/Process﹕ java.lang.ThreadGroup.uncaughtException(ThreadGroup.java:693)
01-06 18:27:59.531 14118-14118/pl.several27.Biblia_Warszawska D/Process﹕ java.lang.ThreadGroup.uncaughtException(ThreadGroup.java:690)
01-06 18:27:59.531 14118-14118/pl.several27.Biblia_Warszawska D/Process﹕ dalvik.system.NativeStart.main(Native Method)
Also I tried this way display progressdialog in non-activity class but it won't work too.
And here is whole application source code but without dialog: https://github.com/several27/BibliaWarszawska_Android
Please can anyone help me?
I do something like that on my application but I prefer to do that on background, so the user just don't have access to the screens that depend on my database...
You can try something like that:
public class BackgroundSyncService extends IntentService {
public static final String NOTIFICATION = "com.example.sync.service";
public static final String RESULT = "result";
public BackgroundSyncService() {
super("BackgroundSyncService");
}
#Override
protected void onHandleIntent(Intent intent) {
//Do here what you want with your database
//After all process you just notify your activitys
Intent intent = new Intent(NOTIFICATION);
intent.putExtra(RESULT, result);
sendBroadcast(intent);
}
}
Create a receiver (I use a inner class on my project)
private BroadcastReceiver receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
Bundle bundle = intent.getExtras();
if (bundle != null) {
//Do what you want here , like enable a section of your app
}
}
};
Then you need to register the service to your activity adding :
registerReceiver(receiver, new IntentFilter(BackgroundSyncService.NOTIFICATION));
Don't forget to unregister the receiver:
#Override
protected void onPause() {
super.onPause();
unregisterReceiver(receiver);
}
Also don't forget to register your IntentService on the AndroidManifest.xml
<service android:name="com.example.service.BackgroundSyncService" />
EDIT
Also you need to include the call to start your service where you want, I start mine on App instance:
Intent intent = new Intent(this, BackgroundSyncService.class);
startService(intent);
EXPLANATION
First you are creating a service to do what you want, the service can do whatever you want, in your case you will fill a database...
After you have created this service, you will set when you want to start this service (the edit part)...
After that you will register your activity to listen the service thats why we have created the BroadcastReceiver, the BroadcastReceiver will be called when your Service execute the line:
//After all process you just notify your activitys
Intent intent = new Intent(NOTIFICATION);
intent.putExtra(RESULT, result);
sendBroadcast(intent);
I guess the better way when the app starts you present the user with a message/ an activity that is not database related or just use the splash screen at the time that it is loading and estimate the time it normally finish loading to be the timer of the splash screen
I'm working on my first android app and I'm having trouble creating an object of a class I have programmed in java using the onCreate function of an activity. The activity starts great when I do not instantiate the object, but when I attempt to create the object the app crashes when switching to the activity. The onCreate function looks like this...
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_entry);
// Show the Up button in the action bar.
setupActionBar();
ForceTable testTable = new ForceTable();
Double factor = testTable.returnValue(forceTypes.newtons, forceTypes.newtons);
}
ForceTable is the class I have programmed, its code looks this...
public class ForceTable {
private double[][] forceTable;
protected enum forceTypes {newtons(0), pounds(1), kilopond(2);
public int num;
private forceTypes(int num)
{
this.num = num;
}
};
protected final class values{
private final static double zeroZero = 1.00;
private final static double zeroOne = 4.44872162;
private final static double zeroTwo = 9.80665;
private final static double oneZero = .224808943;
private final static double oneOne = 1.00;
private final static double oneTwo = 2.20462262;
private final static double twoZero = .10197164;
private final static double twoOne = .45359237;
private final static double twoTwo = 1.00;
}
public ForceTable()
{
this.makeTable();
}
private void makeTable()
{
forceTable[0][0] = values.zeroZero;
forceTable[0][1] = values.zeroOne;
forceTable[0][2] = values.zeroTwo;
forceTable[1][0] = values.oneZero;
forceTable[1][1] = values.oneOne;
forceTable[1][2] = values.oneTwo;
forceTable[2][0] = values.twoZero;
forceTable[2][1] = values.twoOne;
forceTable[2][2] = values.twoTwo;
}
public double returnValue(forceTypes ifYouHave, forceTypes thenYouHave){
double factor = forceTable[thenYouHave.num][ifYouHave.num];
return factor;
}
}
It's been a very long time since I have programmed in Java, and since the activity starts fine without instantiating it must be my Java code for ForceTable. Anybody notice something wrong? There's a good chance it's something easy that I'm not brushed up on...
Here is the logcat
08-08 18:08:13.206: E/(9801): : Can't open file for reading
08-08 18:08:13.206: E/(9801): : Can't open file for reading
08-08 18:10:34.045: W/dalvikvm(9801): threadid=1: thread exiting with uncaught exception (group=0x4136b438)
08-08 18:10:34.045: E/AndroidRuntime(9801): FATAL EXCEPTION: main
08-08 18:10:34.045: E/AndroidRuntime(9801): java.lang.RuntimeException: Unable to start activity ComponentInfo{khandy.application.convertible/khandy.application.convertible.EntryActivity}: java.lang.NullPointerException
08-08 18:10:34.045: E/AndroidRuntime(9801): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2110)
08-08 18:10:34.045: E/AndroidRuntime(9801): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2135)
08-08 18:10:34.045: E/AndroidRuntime(9801): at android.app.ActivityThread.access$700(ActivityThread.java:143)
08-08 18:10:34.045: E/AndroidRuntime(9801): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1241)
08-08 18:10:34.045: E/AndroidRuntime(9801): at android.os.Handler.dispatchMessage(Handler.java:99)
08-08 18:10:34.045: E/AndroidRuntime(9801): at android.os.Looper.loop(Looper.java:137)
08-08 18:10:34.045: E/AndroidRuntime(9801): at android.app.ActivityThread.main(ActivityThread.java:4950)
08-08 18:10:34.045: E/AndroidRuntime(9801): at java.lang.reflect.Method.invokeNative(Native Method)
08-08 18:10:34.045: E/AndroidRuntime(9801): at java.lang.reflect.Method.invoke(Method.java:511)
08-08 18:10:34.045: E/AndroidRuntime(9801): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1004)
08-08 18:10:34.045: E/AndroidRuntime(9801): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:771)
08-08 18:10:34.045: E/AndroidRuntime(9801): at dalvik.system.NativeStart.main(Native Method)
08-08 18:10:34.045: E/AndroidRuntime(9801): Caused by: java.lang.NullPointerException
08-08 18:10:34.045: E/AndroidRuntime(9801): at khandy.application.convertible.ForceTable.makeTable(ForceTable.java:34)
08-08 18:10:34.045: E/AndroidRuntime(9801): at khandy.application.convertible.ForceTable.(ForceTable.java:29)
08-08 18:10:34.045: E/AndroidRuntime(9801): at khandy.application.convertible.EntryActivity.onCreate(EntryActivity.java:21)
08-08 18:10:34.045: E/AndroidRuntime(9801): at android.app.Activity.performCreate(Activity.java:5179)
08-08 18:10:34.045: E/AndroidRuntime(9801): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1094)
08-08 18:10:34.045: E/AndroidRuntime(9801): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2074)
08-08 18:10:34.045: E/AndroidRuntime(9801): ... 11 more
You probably get a NullPointerException at this line
forceTable[0][0] = values.zeroZero;
because you try to access the array without creating it first. Before accessing it, create it like that
forceTable = new double[][];
forceTable[0][0] = values.zeroZero;
And please ALWAYS post the logcat output! It just makes it so much easier to find the problem.
I think the problem is when your makeTable function is called. can you allocate space for your forceTable array.. I mean do a new for double[][] forceTable;
You are missing
privatetable = new double[n] [m] ;
You can put it in the constructor of the second class!
I have been trying to program a twitter client for Android (using twitter4j). So far the idea is to have a simple GUI, and if there is not a file with the OAuth token in the SD Card, connect to the Twitter API using AsyncTask, get the URL for the authorization and open the default browser. However, the browser never runs. Depending on the different modifications I have made trying to fix this, either the Activity starts normally but the browser never starts or the Activity crashes. I have come to a point of a a little of frustation and confussion. Can someone point out what's wrong with my code?
public class StatusActivity extends Activity {
private static final String TAG = "StatusActivity";
EditText editText;
Button updateButton;
File oauthfile = null;
public Context context = getApplicationContext();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_status);
Log.d(TAG, "started");
// Find views
editText = (EditText) findViewById(R.id.editText); //
updateButton = (Button) findViewById(R.id.buttonUpdate);
oauthfile = new File("sdcard/auth_file.txt");
//Check if the file with the keys exist
if (oauthfile.exists()==false){
Log.d(TAG, "file not created");
Context context = getApplicationContext();
Toast toast = Toast.makeText(context, "file not created.", Toast.LENGTH_SHORT);
toast.show();
new Authorization(context).execute();
}
}
public void openBrowser (View v){
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.google.com"));
startActivity(browserIntent);
Log.d(TAG, "onclick");
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.status, menu);
return true;
}
}
class Authorization extends AsyncTask <String, Integer, String>{
String url = null;
private Context context;
Authorization(Context context) {
this.context = context.getApplicationContext();
}
public void onPreExecute() {
super.onPreExecute();
Toast.makeText(context, "Invoke onPreExecute()", Toast.LENGTH_SHORT).show();
}
#Override
public String doInBackground(String... params) {
ConfigurationBuilder configBuilder = new ConfigurationBuilder();
configBuilder.setDebugEnabled(true)
//I have eliminated the keys from the question :)
.setOAuthConsumerKey("XXXXXXXXXXXXXX")
.setOAuthConsumerSecret("XXXXXXXXXXXXXXX");
Twitter OAuthTwitter = new TwitterFactory(configBuilder.build()).getInstance();
RequestToken requestToken = null;
AccessToken accessToken = null;
do{
try {
requestToken = OAuthTwitter.getOAuthRequestToken();
url = requestToken.getAuthorizationURL();
}
catch (TwitterException ex) {
ex.printStackTrace();
}
}
while (accessToken==null);
return url;
}
protected void onPostExecute(String result) {
super.onPostExecute(result);
Toast.makeText(context, "Opening browser.", Toast.LENGTH_SHORT).show();
Intent browserIntent = new Intent(Intent.ACTION_ALL_APPS, Uri.parse(url));
context.startActivity(browserIntent);
}
}
I know that at least checks if the file for the tokens exists because the toast "file not created" appears, and that the activity is able to run the browser if I press the button. The app has permissions to write in the SD card and use the Internet. Thanks in advance.
Logcat Trace:
03-28 19:02:32.816: E/AndroidRuntime(278): FATAL EXCEPTION: main
03-28 19:02:32.816: E/AndroidRuntime(278): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.versec.pardinus/com.versec.pardinus.StatusActivity}: java.lang.NullPointerException
03-28 19:02:32.816: E/AndroidRuntime(278): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2585)
03-28 19:02:32.816: E/AndroidRuntime(278): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
03-28 19:02:32.816: E/AndroidRuntime(278): at android.app.ActivityThread.access$2300(ActivityThread.java:125)
03-28 19:02:32.816: E/AndroidRuntime(278): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
03-28 19:02:32.816: E/AndroidRuntime(278): at android.os.Handler.dispatchMessage(Handler.java:99)
03-28 19:02:32.816: E/AndroidRuntime(278): at android.os.Looper.loop(Looper.java:123)
03-28 19:02:32.816: E/AndroidRuntime(278): at android.app.ActivityThread.main(ActivityThread.java:4627)
03-28 19:02:32.816: E/AndroidRuntime(278): at java.lang.reflect.Method.invokeNative(Native Method)
03-28 19:02:32.816: E/AndroidRuntime(278): at java.lang.reflect.Method.invoke(Method.java:521)
03-28 19:02:32.816: E/AndroidRuntime(278): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
03-28 19:02:32.816: E/AndroidRuntime(278): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
03-28 19:02:32.816: E/AndroidRuntime(278): at dalvik.system.NativeStart.main(Native Method)
03-28 19:02:32.816: E/AndroidRuntime(278): Caused by: java.lang.NullPointerException
03-28 19:02:32.816: E/AndroidRuntime(278): at android.content.ContextWrapper.getApplicationContext(ContextWrapper.java:100)
03-28 19:02:32.816: E/AndroidRuntime(278): at com.versec.pardinus.StatusActivity.<init>(StatusActivity.java:30)
03-28 19:02:32.816: E/AndroidRuntime(278): at java.lang.Class.newInstanceImpl(Native Method)
03-28 19:02:32.816: E/AndroidRuntime(278): at java.lang.Class.newInstance(Class.java:1429)
03-28 19:02:32.816: E/AndroidRuntime(278): at android.app.Instrumentation.newActivity(Instrumentation.java:1021)
03-28 19:02:32.816: E/AndroidRuntime(278): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2577)
03-28 19:02:32.816: E/AndroidRuntime(278): ... 11 more
This is what is causing your crash.
public Context context = getApplicationContext();
You're not even using it when you need it, so you can just get rid of this line.
Btw, something else I noticed while looking at your code is this:
oauthfile = new File("sdcard/auth_file.txt");
Don't take the "sdcard/" path for granted. Use this instead:
File dir = Environment.getExternalStorageDirectory();
File oauthfile = new File(dir, "auth_file.txt");
I am using the JavaCV library with pre-built OpenCV libraries for Android. I think I have setup Eclipse the right way, because I have included the jars both javacv.jar and javacpp.jar. In addition, the java-cv-android-arm.jar, in my project. Everything compiles fine, no errors, warning, anything that should be suspicious of something that will go wrong at runtime. But I get NoClassDefFOundError exception that is thrown in this method body below:
#Override
public void draw(Canvas canvas)
{
try
{
canvas.drawColor(Color.BLUE);
if (current != null)
{
int width = current.getWidth();
int height = current.getHeight();
IplImage i = IplImage.create(width, height, IPL_DEPTH_8U, 1); // I assume here is where the exception gets thrown
ByteBuffer buffer = i.getByteBuffer();
current.copyPixelsToBuffer(buffer);
// We need a grayscale image in order to do the recognition, so
// we
// create a new image of the same size as the original one.
IplImage grayImage = IplImage.create(i.width(), i.height(),
IPL_DEPTH_8U, 1);
// We convert the original image to grayscale.
cvCvtColor(i, grayImage, CV_BGR2GRAY);
CvMemStorage storage = CvMemStorage.create();
// We instantiate a classifier cascade to be used for detection,
// using the cascade definition.
CvHaarClassifierCascade cascade = new CvHaarClassifierCascade(
cvLoad("haarcascade_frontalface_alt.xml"));
// We detect the faces.
CvSeq faces = cvHaarDetectObjects(grayImage, cascade, storage,
1.1, 1, 0);
// We iterate over the discovered faces and draw yellow
// rectangles around them.
for (int index = 0; index < faces.total(); index++)
{
CvRect r = new CvRect(cvGetSeqElem(faces, index));
cvRectangle(i, cvPoint(r.x(), r.y()),
cvPoint(r.x() + r.width(), r.y() + r.height()),
opencv_core.CvScalar.YELLOW, 1, CV_AA, 0);
}
Bitmap b = BitmapFactory.decodeByteArray(i.getByteBuffer()
.array(), 0, i.getByteBuffer().array().length);
canvas.drawBitmap(b, x, y, paint);
canvas.drawText(new Date().toLocaleString(), canvas.getWidth() - 100,
canvas.getHeight() - 50, paint);
paint.setColor(Color.GREEN);
}
} catch (Exception e)
{
canvas.drawColor(Color.RED);
canvas.drawText(
"Handled exception occurred in panel:\n" + e.getMessage(),
250, 250, paint);
paint.setColor(Color.GREEN);
}
super.draw(canvas);
}
And of course, right after the exception is thrown, my Android crashes, and I force close the application. Did I include the jars, and required libraries correctly? Is there anything that I should be aware of? Any help would be greatly appreciated.
Here is the LogCat for those who love Cats (insert emoticon here):
05-03 19:07:53.217: E/AndroidRuntime(741): FATAL EXCEPTION: main
05-03 19:07:53.217: E/AndroidRuntime(741): java.lang.NoClassDefFoundError: com.googlecode.javacv.cpp.opencv_core$IplImage
05-03 19:07:53.217: E/AndroidRuntime(741): at home.security.DrawingPanel.draw(DrawingPanel.java:81)
05-03 19:07:53.217: E/AndroidRuntime(741): at home.security.Main$2.run(Main.java:105)
05-03 19:07:53.217: E/AndroidRuntime(741): at android.os.Handler.handleCallback(Handler.java:587)
05-03 19:07:53.217: E/AndroidRuntime(741): at android.os.Handler.dispatchMessage(Handler.java:92)
05-03 19:07:53.217: E/AndroidRuntime(741): at android.os.Looper.loop(Looper.java:123)
05-03 19:07:53.217: E/AndroidRuntime(741): at android.app.ActivityThread.main(ActivityThread.java:3683)
05-03 19:07:53.217: E/AndroidRuntime(741): at java.lang.reflect.Method.invokeNative(Native Method)
05-03 19:07:53.217: E/AndroidRuntime(741): at java.lang.reflect.Method.invoke(Method.java:507)
05-03 19:07:53.217: E/AndroidRuntime(741): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
05-03 19:07:53.217: E/AndroidRuntime(741): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
05-03 19:07:53.217: E/AndroidRuntime(741): at dalvik.system.NativeStart.main(Native Method)
Folder Structure Of 'libs Folder
The jars need to be in the project-root/libs folder or to mark them as exported in the build path of the project...
now it should work...