Android Development DropboxUnlinkedException - java

I am writing an Android app with upload a file to Dropbox. However, I do not know
why I encounter DropboxUnlinkedException at runtime after reading some articles on StackOverflow. Can anyone tell me what problem it is?
Actually, I am new to JAVA and Android. Hope that you can explain the problem as well
as the solutions in details. Thanks a lot! :D
(Remarks: I have checked that I can call the uploadFile method. But there is no any response get. I am confused.)
public class ConnectToDropBox extends Activity {
final static private String APP_KEY = "16u74380lodkknv";
final static private String APP_SECRET = "westpz8i6mqn15g";
final static private AccessType ACCESS_TYPE = AccessType.DROPBOX;
// In the class declaration section:
private DropboxAPI<AndroidAuthSession> mDBApi;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// And later in some initialization function:
AppKeyPair appKeys = new AppKeyPair(APP_KEY, APP_SECRET);
AndroidAuthSession session = new AndroidAuthSession(appKeys,
ACCESS_TYPE);
mDBApi = new DropboxAPI<AndroidAuthSession>(session);
mDBApi.getSession().startOAuth2Authentication(ConnectToDropBox.this);
try {
uploadFile();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (DropboxException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
protected void onResume() {
super.onResume();
if (mDBApi.getSession().authenticationSuccessful()) {
try {
// Required to complete auth, sets the access token on the
// session
mDBApi.getSession().finishAuthentication();
String accessToken = mDBApi.getSession().getOAuth2AccessToken();
} catch (IllegalStateException e) {
Log.i("DbAuthLog", "Error authenticating", e);
}
}
}
public void uploadFile() throws DropboxException, FileNotFoundException {
File file = new File("/sdcard/letschat/data/backup.txt.part.1");
FileInputStream inputStream = new FileInputStream(file);
Entry response = mDBApi.putFile(
"/sdcard/letschat/data/backup.txt.part.1", inputStream,
file.length(), null, null);
Toast.makeText(ConnectToDropBox.this, "HIHI", Toast.LENGTH_SHORT)
.show();
}
}
The LogCat is as follows:
03-28 20:27:28.269: W/System.err(8283): com.dropbox.client2.exception.DropboxUnlinkedException
03-28 20:27:28.273: W/System.err(8283): at com.dropbox.client2.DropboxAPI.assertAuthenticated(DropboxAPI.java:2525)
03-28 20:27:28.273: W/System.err(8283): at com.dropbox.client2.DropboxAPI.putFileRequest(DropboxAPI.java:2177)
03-28 20:27:28.273: W/System.err(8283): at com.dropbox.client2.DropboxAPI.putFileRequest(DropboxAPI.java:1498)
03-28 20:27:28.273: W/System.err(8283): at com.dropbox.client2.DropboxAPI.putFile(DropboxAPI.java:1458)
03-28 20:27:28.277: W/System.err(8283): at com.tolmms.backup.ConnectToDropBox.uploadFile(ConnectToDropBox.java:74)
03-28 20:27:28.277: W/System.err(8283): at com.tolmms.backup.ConnectToDropBox.onCreate(ConnectToDropBox.java:45)
03-28 20:27:28.277: W/System.err(8283): at android.app.Activity.performCreate(Activity.java:5008)
03-28 20:27:28.277: W/System.err(8283): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1079)
03-28 20:27:28.277: W/System.err(8283): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2023)
03-28 20:27:28.277: W/System.err(8283): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
03-28 20:27:28.277: W/System.err(8283): at android.app.ActivityThread.access$600(ActivityThread.java:130)
03-28 20:27:28.277: W/System.err(8283): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
03-28 20:27:28.277: W/System.err(8283): at android.os.Handler.dispatchMessage(Handler.java:99)
03-28 20:27:28.277: W/System.err(8283): at android.os.Looper.loop(Looper.java:137)
03-28 20:27:28.277: W/System.err(8283): at android.app.ActivityThread.main(ActivityThread.java:4745)
03-28 20:27:28.281: W/System.err(8283): at java.lang.reflect.Method.invokeNative(Native Method)
03-28 20:27:28.281: W/System.err(8283): at java.lang.reflect.Method.invoke(Method.java:511)
03-28 20:27:28.281: W/System.err(8283): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
03-28 20:27:28.281: W/System.err(8283): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
03-28 20:27:28.281: W/System.err(8283): at dalvik.system.NativeStart.main(Native Method)

The documentation kinda sucks, it does not tell you that if you dont use onResume, how to code this. I have called the upload in a service.
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d(God.TAG, "Initializing Dropbox");
AppKeyPair appKeys = new AppKeyPair(God.DROPBOX_APP_KEY,
God.DROPBOX_APP_SECRET);
AndroidAuthSession session = new AndroidAuthSession(appKeys);
mDBApi = new DropboxAPI<AndroidAuthSession>(session);
mDBApi.getSession().startOAuth2Authentication(this);
if (mDBApi != null && mDBApi.getSession().authenticationSuccessful()) {
try {
// Required to complete auth, sets the access token on the session
mDBApi.getSession().finishAuthentication();
UploadDB2DropBox upload2DropBox = new UploadDB2DropBox(this,
mDBApi);
upload2DropBox.execute();
//String accessToken = mDBApi.getSession().getOAuth2AccessToken();
} catch (IllegalStateException e) {
Log.i(God.TAG, "Error authenticating", e);
}
}
return super.onStartCommand(intent, flags, startId);
}

Related

How to remove Android ExceptionInitializeError?

I am getting the following error in my logcat:
03-28 15:07:12.758 27708-27708/in.aekansh.cortibae E/AndroidRuntime: FATAL EXCEPTION: main
03-28 15:07:12.758 27708-27708/in.aekansh.cortibae E/AndroidRuntime: Process: in.aekansh.cortibae, PID: 27708
03-28 15:07:12.758 27708-27708/in.aekansh.cortibae E/AndroidRuntime: java.lang.ExceptionInInitializerError
03-28 15:07:12.758 27708-27708/in.aekansh.cortibae E/AndroidRuntime: at in.aekansh.cortibae.MainActivity.onCreate(MainActivity.java:130)
03-28 15:07:12.758 27708-27708/in.aekansh.cortibae E/AndroidRuntime: at android.app.Activity.performCreate(Activity.java:5990)
03-28 15:07:12.758 27708-27708/in.aekansh.cortibae E/AndroidRuntime: at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
03-28 15:07:12.758 27708-27708/in.aekansh.cortibae E/AndroidRuntime: at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2310)
03-28 15:07:12.758 27708-27708/in.aekansh.cortibae E/AndroidRuntime: at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2419)
03-28 15:07:12.758 27708-27708/in.aekansh.cortibae E/AndroidRuntime: at android.app.ActivityThread.access$900(ActivityThread.java:154)
03-28 15:07:12.758 27708-27708/in.aekansh.cortibae E/AndroidRuntime: at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1321)
03-28 15:07:12.758 27708-27708/in.aekansh.cortibae E/AndroidRuntime: at android.os.Handler.dispatchMessage(Handler.java:102)
03-28 15:07:12.758 27708-27708/in.aekansh.cortibae E/AndroidRuntime: at android.os.Looper.loop(Looper.java:135)
03-28 15:07:12.758 27708-27708/in.aekansh.cortibae E/AndroidRuntime: at android.app.ActivityThread.main(ActivityThread.java:5293)
03-28 15:07:12.758 27708-27708/in.aekansh.cortibae E/AndroidRuntime: at java.lang.reflect.Method.invoke(Native Method)
03-28 15:07:12.758 27708-27708/in.aekansh.cortibae E/AndroidRuntime: at java.lang.reflect.Method.invoke(Method.java:372)
03-28 15:07:12.758 27708-27708/in.aekansh.cortibae E/AndroidRuntime: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:904)
03-28 15:07:12.758 27708-27708/in.aekansh.cortibae E/AndroidRuntime: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:699)
03-28 15:07:12.758 27708-27708/in.aekansh.cortibae E/AndroidRuntime: Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.res.Resources in.aekansh.cortibae.App.getResources()' on a null object reference
03-28 15:07:12.758 27708-27708/in.aekansh.cortibae E/AndroidRuntime: at in.aekansh.cortibae.AndroidUtilities.<clinit>(AndroidUtilities.java:32)
03-28 15:07:12.758 27708-27708/in.aekansh.cortibae E/AndroidRuntime: at in.aekansh.cortibae.MainActivity.onCreate(MainActivity.java:130) 
03-28 15:07:12.758 27708-27708/in.aekansh.cortibae E/AndroidRuntime: at android.app.Activity.performCreate(Activity.java:5990) 
03-28 15:07:12.758 27708-27708/in.aekansh.cortibae E/AndroidRuntime: at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106) 
03-28 15:07:12.758 27708-27708/in.aekansh.cortibae E/AndroidRuntime: at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2310) 
03-28 15:07:12.758 27708-27708/in.aekansh.cortibae E/AndroidRuntime: at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2419) 
03-28 15:07:12.758 27708-27708/in.aekansh.cortibae E/AndroidRuntime: at android.app.ActivityThread.access$900(ActivityThread.java:154) 
03-28 15:07:12.758 27708-27708/in.aekansh.cortibae E/AndroidRuntime: at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1321) 
03-28 15:07:12.758 27708-27708/in.aekansh.cortibae E/AndroidRuntime: at android.os.Handler.dispatchMessage(Handler.java:102) 
03-28 15:07:12.758 27708-27708/in.aekansh.cortibae E/AndroidRuntime: at android.os.Looper.loop(Looper.java:135) 
03-28 15:07:12.758 27708-27708/in.aekansh.cortibae E/AndroidRuntime: at android.app.ActivityThread.main(ActivityThread.java:5293) 
03-28 15:07:12.758 27708-27708/in.aekansh.cortibae E/AndroidRuntime: at java.lang.reflect.Method.invoke(Native Method) 
03-28 15:07:12.758 27708-27708/in.aekansh.cortibae E/AndroidRuntime: at java.lang.reflect.Method.invoke(Method.java:372) 
03-28 15:07:12.758 27708-27708/in.aekansh.cortibae E/AndroidRuntime: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:904) 
03-28 15:07:12.758 27708-27708/in.aekansh.cortibae E/AndroidRuntime: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:699) 
03-28 15:07:14.863 27708-27708/in.aekansh.cortibae I/Process: Sending signal. PID: 27708 SIG: 9
I don't know how to remove the error.
This is my MainActivity.java:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
AndroidUtilities.statusBarHeight = getStatusBarHeight();
chatMessages = new ArrayList<>();
chatListView = (ListView) findViewById(R.id.chat_list_view);
chatEditText1 = (EditText) findViewById(R.id.chat_edit_text1);
enterChatView1 = (ImageView) findViewById(R.id.enter_chat1);
// Hide the emoji on click of edit text
chatEditText1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (showingEmoji)
hideEmojiPopup();
}
});
emojiButton = (ImageView)findViewById(R.id.emojiButton);
emojiButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showEmojiPopup(!showingEmoji);
}
});
listAdapter = new ChatListAdapter(chatMessages, this); //load the messages from the array.
chatListView.setAdapter(listAdapter);
chatEditText1.setOnKeyListener(keyListener);
enterChatView1.setOnClickListener(clickListener);
chatEditText1.addTextChangedListener(watcher1);
sizeNotifierRelativeLayout = (SizeNotifierRelativeLayout) findViewById(R.id.chat_layout);
sizeNotifierRelativeLayout.delegate = this;
NotificationCenter.getInstance().addObserver(this, NotificationCenter.emojiDidLoaded);
}
AndroidUtilities.java:
public class AndroidUtilities {
public static float density = 1;
public static int statusBarHeight = 0;
public static Point displaySize = new Point();
static {
density = App.getInstance().getResources().getDisplayMetrics().density;
checkDisplaySize();
}
public static int dp(float value) {
return (int)Math.ceil(density * value);
}
public static void runOnUIThread(Runnable runnable) {
runOnUIThread(runnable, 0);
}
public static void runOnUIThread(Runnable runnable, long delay) {
if (delay == 0) {
App.applicationHandler.post(runnable);
} else {
App.applicationHandler.postDelayed(runnable, delay);
}
}
public native static void loadBitmap(String path, Bitmap bitmap, int scale, int width, int height, int stride);
public static boolean copyFile(InputStream sourceFile, File destFile) throws IOException {
OutputStream out = new FileOutputStream(destFile);
byte[] buf = new byte[4096];
int len;
while ((len = sourceFile.read(buf)) > 0) {
Thread.yield();
out.write(buf, 0, len);
}
out.close();
return true;
}
public static boolean copyFile(File sourceFile, File destFile) throws IOException {
if(!destFile.exists()) {
destFile.createNewFile();
}
FileChannel source = null;
FileChannel destination = null;
try {
source = new FileInputStream(sourceFile).getChannel();
destination = new FileOutputStream(destFile).getChannel();
destination.transferFrom(source, 0, source.size());
} catch (Exception e) {
//FileLog.e("tmessages", e);
return false;
} finally {
if(source != null) {
source.close();
}
if(destination != null) {
destination.close();
}
}
return true;
}
public static void checkDisplaySize() {
try {
WindowManager manager = (WindowManager) App.getInstance().getSystemService(Context.WINDOW_SERVICE);
if (manager != null) {
Display display = manager.getDefaultDisplay();
if (display != null) {
if (android.os.Build.VERSION.SDK_INT < 13) {
displaySize.set(display.getWidth(), display.getHeight());
} else {
display.getSize(displaySize);
}
}
}
} catch (Exception e) {
}
}
public static int getViewInset(View view) {
if (view == null || Build.VERSION.SDK_INT < 21) {
return 0;
}
try {
Field mAttachInfoField = View.class.getDeclaredField("mAttachInfo");
mAttachInfoField.setAccessible(true);
Object mAttachInfo = mAttachInfoField.get(view);
if (mAttachInfo != null) {
Field mStableInsetsField = mAttachInfo.getClass().getDeclaredField("mStableInsets");
mStableInsetsField.setAccessible(true);
Rect insets = (Rect)mStableInsetsField.get(mAttachInfo);
return insets.bottom;
}
} catch (Exception e) {
// FileLog.e("tmessages", e);
}
return 0;
}
}
Please tell me where am I getting the NullPointerException. I think I have called all the necessary functions after super.onCreate(); so I don't think there should be any problem. Please help me out. Ask me for more information if you need it.
******* UPDATE *******
App.java:
public class App extends Application {
private static App Instance;
public static volatile Handler applicationHandler = null;
#Override
public void onCreate() {
super.onCreate();
Instance=this;
applicationHandler = new Handler(getInstance().getMainLooper());
NativeLoader.initNativeLibs(App.getInstance());
}
public static App getInstance()
{
return Instance;
}
}
Your App.getInstance() is returning null. The issue here is static block code at AndroidUtilities.java:
static {
density = App.getInstance().getResources().getDisplayMetrics().density;
checkDisplaySize();
}
Static initialization blocks are run when the JVM (class loader - to be specific) loads StaticClass (which occurs the first time it is referenced in code) and before your application started (before onCreate() method of App class was invoked), you can read more at here and here.
The solution is remove above static code block and create a static method at AndroidUtilities.java
public class AndroidUtilities {
public static float density = 1;
public static int statusBarHeight = 0;
public static Point displaySize = new Point();
public static void init() {
density = App.getInstance().getResources().getDisplayMetrics().density;
checkDisplaySize();
}
// your other code
}
App.java:
public class App extends Application {
public void onCreate() {
super.onCreate()
Instance = this;
AndroidUtilities.init();
// your other code
}
}
Android Manifests check application, add android:name=".App" and android:allowBackup="true" and permission
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"></uses-permission>
<application
android:name=".App"
android:allowBackup="true"
android:supportsRtl="true"
And activity add windowSoftInputMode attribute
<activity
android:name=".UserChatActivity"
android:windowSoftInputMode="adjustResize"></activity>
Grandle Control useLibrary and sourceSets.main
useLibrary 'org.apache.http.legacy'
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
sourceSets.main {
jniLibs.srcDir 'libs'
jni.srcDirs = [] //disable automatic ndk-build call
}
Rebuid.

Fatal Exception when viewing/ writing database SQLite?

I get an error when I run my emulator, and try to start reading or viewing the database..
Please see my logcat at the bottum of this page!
I have a Database activity, a SQLView activity, and an SQLite activity.
The database activity is to run the database, the SQLView activity to view the database, and the last one, my SQLite activity is to wrie to my database.
I use SQLiteAssetHelper, and my .rar file is in my assets/databases/Voedsel.rar .
This are my activities:
My database activity:
package com.jacob.eindproject;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import java.sql.*;
import com.readystatesoftware.sqliteasset.SQLiteAssetHelper;
public class Database extends SQLiteAssetHelper {
public static final String KEY_PRODUCT = "Product";
public static final String KEY_EENHEID = "Eenheid";
public static final String KEY_KCAL = "Kcal";
private static final String DATABASE_NAME = "Voedsel";
private static final String DATABASE_TABLE = "Voeding";
private static final int DATABASE_VERSION = 1;
private DbHelper ourHelper;
private Context Context;
private SQLiteDatabase ourDatabase;
private static class DbHelper extends SQLiteAssetHelper{
public DbHelper(Context context) {
super(context, DATABASE_NAME, context.getExternalFilesDir(null).getAbsolutePath(), null, DATABASE_VERSION);
// TODO Auto-generated constructor stub
}
}
#Override
public void onUpgrade(SQLiteDatabase Voedsel, int oldVersion, int newVersion) {
Voedsel.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
onCreate(Voedsel);
}
public Database(Context context){
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
public Database open() throws SQLException{
ourHelper = new DbHelper(Context);
ourDatabase = ourHelper.getWritableDatabase();
return this;
}
public void close() {
ourHelper.close();
}
public long createEntry(String product, String kcal, String eenheid) {
ContentValues cv = new ContentValues();
cv.put(KEY_PRODUCT, product);
cv.put(KEY_EENHEID, eenheid);
cv.put(KEY_KCAL, kcal);
return ourDatabase.insert(DATABASE_TABLE, null, cv);
}
public String getData() {
// TODO Auto-generated method stub
String[] columns = new String[]{ KEY_PRODUCT, KEY_EENHEID, KEY_KCAL};
Cursor c = ourDatabase.query(DATABASE_TABLE, columns, null, null, null, null, null);
String result = "";
int iProduct = c.getColumnIndex(KEY_PRODUCT);
int iEenheid = c.getColumnIndex(KEY_EENHEID);
int iKcal = c.getColumnIndex(KEY_KCAL);
for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()){
result = result + c.getString(iProduct) + " " + c.getString(iEenheid) + " " + c.getString(iKcal) + "\n";
}
return result;
}
public void close(Database database) {
// TODO Auto-generated method stub
}
}
My SQLite activity:
public class SQLite extends Activity implements View.OnClickListener {
Button sqlUpdate, sqlView;
EditText sqlVoeding, sqlKcal, sqlEenheid;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sqllite);
sqlUpdate = (Button) findViewById(R.id.bSQLUpdate);
sqlVoeding = (EditText) findViewById(R.id.etSQLVoeding);
sqlEenheid = (EditText) findViewById(R.id.etSQLEenheid);
sqlKcal = (EditText) findViewById(R.id.etSQLKcal);
sqlView = (Button) findViewById(R.id.bSQLopenView);
sqlView.setOnClickListener((android.view.View.OnClickListener) this);
sqlUpdate.setOnClickListener((android.view.View.OnClickListener) this);
}
public void onClick(View arg0) {
switch (arg0.getId()) {
case R.id.bSQLUpdate:
boolean didItWork = true;
try{
String voeding = sqlVoeding.getText().toString();
String Kcal = sqlKcal.getText().toString();
String eenheid = sqlEenheid.getText().toString();
Database entry = new Database(SQLite.this);
entry.open();
entry.createEntry(voeding, Kcal, eenheid);
entry.close();
}catch (Exception e ){
didItWork = false;
}finally{
if (didItWork){
Dialog d = new Dialog(this);
d.setTitle("Heak Yeay");
TextView tv = new TextView(this);
tv.setText("Succes");
d.setContentView(tv);
d.show();
}
}
break;
case R.id.bSQLopenView:
Intent i = new Intent(this, SQLView.class);
startActivity(i);
}
}
public void onClick(DialogInterface arg0, int arg1) {
// TODO Auto-generated method stub
}
}
And the SQLView activity:
public class SQLView extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sqlview);
TextView tv = (TextView) findViewById(R.id.tvSQLinfo);
Database info = new Database(this);
info.open();
String data = info.getData();
info.close();
tv.setText(data);
}
}
This is my logcat error when I click the SQLView activity:
12-16 14:28:26.883: E/AndroidRuntime(1170): FATAL EXCEPTION: main
12-16 14:28:26.883: E/AndroidRuntime(1170): java.lang.NoClassDefFoundError: com.jacob.eindproject.Database
12-16 14:28:26.883: E/AndroidRuntime(1170): at com.jacob.eindproject.SQLView.onCreate(SQLView.java:14)
12-16 14:28:26.883: E/AndroidRuntime(1170): at android.app.Activity.performCreate(Activity.java:5133)
12-16 14:28:26.883: E/AndroidRuntime(1170): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
12-16 14:28:26.883: E/AndroidRuntime(1170): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2175)
12-16 14:28:26.883: E/AndroidRuntime(1170): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
12-16 14:28:26.883: E/AndroidRuntime(1170): at android.app.ActivityThread.access$600(ActivityThread.java:141)
12-16 14:28:26.883: E/AndroidRuntime(1170): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
12-16 14:28:26.883: E/AndroidRuntime(1170): at android.os.Handler.dispatchMessage(Handler.java:99)
12-16 14:28:26.883: E/AndroidRuntime(1170): at android.os.Looper.loop(Looper.java:137)
12-16 14:28:26.883: E/AndroidRuntime(1170): at android.app.ActivityThread.main(ActivityThread.java:5103)
12-16 14:28:26.883: E/AndroidRuntime(1170): at java.lang.reflect.Method.invokeNative(Native Method)
12-16 14:28:26.883: E/AndroidRuntime(1170): at java.lang.reflect.Method.invoke(Method.java:525)
12-16 14:28:26.883: E/AndroidRuntime(1170): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
12-16 14:28:26.883: E/AndroidRuntime(1170): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
12-16 14:28:26.883: E/AndroidRuntime(1170): at dalvik.system.NativeStart.main(Native Method)
And this is my error when I click my 'write' activity:
12-16 14:27:35.913: E/AndroidRuntime(999): FATAL EXCEPTION: main
12-16 14:27:35.913: E/AndroidRuntime(999): java.lang.NoClassDefFoundError: com.jacob.eindproject.Database
12-16 14:27:35.913: E/AndroidRuntime(999): at com.jacob.eindproject.SQLite.onClick(SQLite.java:45)
12-16 14:27:35.913: E/AndroidRuntime(999): at android.view.View.performClick(View.java:4240)
12-16 14:27:35.913: E/AndroidRuntime(999): at android.view.View$PerformClick.run(View.java:17721)
12-16 14:27:35.913: E/AndroidRuntime(999): at android.os.Handler.handleCallback(Handler.java:730)
12-16 14:27:35.913: E/AndroidRuntime(999): at android.os.Handler.dispatchMessage(Handler.java:92)
12-16 14:27:35.913: E/AndroidRuntime(999): at android.os.Looper.loop(Looper.java:137)
12-16 14:27:35.913: E/AndroidRuntime(999): at android.app.ActivityThread.main(ActivityThread.java:5103)
12-16 14:27:35.913: E/AndroidRuntime(999): at java.lang.reflect.Method.invokeNative(Native Method)
12-16 14:27:35.913: E/AndroidRuntime(999): at java.lang.reflect.Method.invoke(Method.java:525)
12-16 14:27:35.913: E/AndroidRuntime(999): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
12-16 14:27:35.913: E/AndroidRuntime(999): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
12-16 14:27:35.913: E/AndroidRuntime(999): at dalvik.system.NativeStart.main(Native Method)
Hopefully someone can help me fix my error. Thank you all in advance for taking your time.
Jacob.
I don't think you've added the SQLiteAssetHelper library to your project correctly.
You must ensure that the build path for your project is correct, and all referenced libraries are selected.
Right click on your project and select 'Properties'
Click on 'Android'
Make sure your SQLiteAssetHelper library is selected

Activity closes when trying to asyncronously connect to twitter

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");

Error on changing button's text color to default?

I have a button with set color code:
buttonClicked.setTextColor(Color.GRAY);
Now when I finish my timer, the text of all buttons reset to something else, so I need that text to go back to default. I tried this but I get error (i placed a comment near the end of my code for that error):
final OnClickListener clickListener = new OnClickListener() {
private Button buttonClicked;
private int brojacKlikova = 0;
public void onClick(View v) {
brojacKlikova++;
if (brojacKlikova < 16) {
Button button = (Button) v;
button.getBackground().setColorFilter(new LightingColorFilter(0xFFFFFFFF, 0x003333));
if (buttonClicked == null) {
// first button is clicked
buttonClicked = button;
} else {
// second button is clicked
if (buttonClicked.getTag().equals(button.getTag())) {
button.getBackground().setColorFilter(new LightingColorFilter(0xFFFFFFFF, 0x66FF33));
buttonClicked.getBackground().setColorFilter(new LightingColorFilter(0xFFFFFFFF, 0x66FF33));
buttonClicked.setEnabled(false);
button.setEnabled(false);
counter = counter + 5;
score.setText("Poeni: " + counter);
} else {
buttonClicked.setEnabled(false);
buttonClicked.setTextColor(Color.GRAY);
buttonClicked.getBackground().setColorFilter(new LightingColorFilter(0xFFFFFFFF, 0xFFCC99));
button.getBackground().clearColorFilter();
}
buttonClicked = null;
}
}else{
buttonClicked = null;
buttonClicked.setTextColor(Color.WHITE); //<--- here I get error
brojacKlikova = 0;
brojacVremena.cancel();
mHandler.postDelayed(mLaunchTask,2200);
}
}
};
How to reset my button's text color to default?
Here's logcat:
03-28 23:59:29.357: W/dalvikvm(27918): threadid=1: thread exiting with uncaught exception (group=0x40018560)
03-28 23:59:29.467: E/AndroidRuntime(27918): FATAL EXCEPTION: main
03-28 23:59:29.467: E/AndroidRuntime(27918): java.lang.NullPointerException
03-28 23:59:29.467: E/AndroidRuntime(27918): at rs.androidaplikacije.spojnice.Spojnice$1.onClick(Spojnice.java:77)
03-28 23:59:29.467: E/AndroidRuntime(27918): at android.view.View.performClick(View.java:2506)
03-28 23:59:29.467: E/AndroidRuntime(27918): at android.view.View$PerformClick.run(View.java:9112)
03-28 23:59:29.467: E/AndroidRuntime(27918): at android.os.Handler.handleCallback(Handler.java:587)
03-28 23:59:29.467: E/AndroidRuntime(27918): at android.os.Handler.dispatchMessage(Handler.java:92)
03-28 23:59:29.467: E/AndroidRuntime(27918): at android.os.Looper.loop(Looper.java:130)
03-28 23:59:29.467: E/AndroidRuntime(27918): at android.app.ActivityThread.main(ActivityThread.java:3835)
03-28 23:59:29.467: E/AndroidRuntime(27918): at java.lang.reflect.Method.invokeNative(Native Method)
03-28 23:59:29.467: E/AndroidRuntime(27918): at java.lang.reflect.Method.invoke(Method.java:507)
03-28 23:59:29.467: E/AndroidRuntime(27918): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:864)
03-28 23:59:29.467: E/AndroidRuntime(27918): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:622)
03-28 23:59:29.467: E/AndroidRuntime(27918): at dalvik.system.NativeStart.main(Native Method)
03-28 23:59:31.167: I/Process(27918): Sending signal. PID: 27918 SIG: 9
buttonClicked = null;
buttonClicked.setTextColor(Color.WHITE);
Problem is here. You are assigned button to NULL and then you call property on it. This always throw NPE. Solution is to remove first line and it should work.

Why does this FileOutputStream give a NullPointerException?

so I am running an app that creates a NullPointerException when I try to write a file.
My first activity (see below) calls the NewSet activity when the user presses the new set button. When I try to write the input in the NewSet activity, it throws a NullPointerException. Printing out fileOut displays me with it having a value of null, which it shouldn't. fileOut is declared globally, but initialized in onCreate. The Two classes are below. (... represents omitted code due to being irrelevant.)
public class MainActivity extends Activity {
static ArrayList sets;
FileOutputStream fileOut;
BufferedReader read;
String line;
ArrayAdapter<String> adapter;
ListView listView;
Intent newSetIntent;
#Override
protected void onCreate(Bundle savedInstanceState) {
setContentView(R.layout.activity_main);
newSetIntent=new Intent(this,NewSet.class);
listView=(ListView)findViewById(R.id.setList);
sets=new ArrayList();
try {
read=new BufferedReader(new BufferedReader(new InputStreamReader(openFileInput("SETS.txt"))));
fileOut=openFileOutput("SETS.txt",Context.MODE_APPEND);
} catch (FileNotFoundException e) {
System.out.println("File not found");
try {
fileOut.write("".getBytes());
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
System.out.println("IOE");
// TODO Auto-generated catch block
e.printStackTrace();
}
getSets();
toList();
super.onCreate(savedInstanceState);
}
...
public void newSet(String newSetName){
System.out.println(newSetName);
sets.add(newSetName);
try {
fileOut=openFileOutput("SETS.txt",Context.MODE_APPEND);
fileOut.write(newSetName.getBytes());
fileOut.write("\n".getBytes());
} catch (IOException e) {
e.printStackTrace();
}
catch (NullPointerException NPE){
System.out.println(fileOut);
NPE.printStackTrace();
}
}
}
public class NewSet extends Activity {
EditText input;
String setName;
MainActivity main;
...
public void submit(View view){
setName=input.getText().toString();
System.out.println("CREATING SET:"+setName);
main.newSet(setName);
finish();
}
}
The full stack trace
03-03 23:08:42.183: W/System.err(8435): java.lang.NullPointerException
03-03 23:08:42.183: W/System.err(8435): at android.content.ContextWrapper.openFileOutput(ContextWrapper.java:173)
03-03 23:08:42.183: W/System.err(8435): at com.ollien.flashcards.MainActivity.newSet(MainActivity.java:112)
03-03 23:08:42.183: W/System.err(8435): at com.ollien.flashcards.NewSet.submit(NewSet.java:35)
03-03 23:08:42.193: W/System.err(8435): at java.lang.reflect.Method.invokeNative(Native Method)
03-03 23:08:42.193: W/System.err(8435): at java.lang.reflect.Method.invoke(Method.java:511)
03-03 23:08:42.193: W/System.err(8435): at android.view.View$1.onClick(View.java:3594)
03-03 23:08:42.193: W/System.err(8435): at android.view.View.performClick(View.java:4204)
03-03 23:08:42.193: W/System.err(8435): at android.view.View$PerformClick.run(View.java:17355)
03-03 23:08:42.193: W/System.err(8435): at android.os.Handler.handleCallback(Handler.java:725)
03-03 23:08:42.203: W/System.err(8435): at android.os.Handler.dispatchMessage(Handler.java:92)
03-03 23:08:42.203: W/System.err(8435): at android.os.Looper.loop(Looper.java:137)
03-03 23:08:42.203: W/System.err(8435): at android.app.ActivityThread.main(ActivityThread.java:5226)
03-03 23:08:42.203: W/System.err(8435): at java.lang.reflect.Method.invokeNative(Native Method)
03-03 23:08:42.203: W/System.err(8435): at java.lang.reflect.Method.invoke(Method.java:511)
03-03 23:08:42.203: W/System.err(8435): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:795)
03-03 23:08:42.203: W/System.err(8435): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:562)
03-03 23:08:42.203: W/System.err(8435): at dalvik.system.NativeStart.main(Native Method)
Exception is getting thrown in android.content.ContextWrapper class. Method is:
public FileOutputStream openFileOutput(String name, int mode) throws FileNotFoundException
{
return mBase.openFileOutput(name, mode); // Line number 173
}
Here, the only possibility I see which could result in NullPointerException is data member mBase of type Context is NULL.
Can you check if Context data member is non-null.

Categories