Activity closes when trying to asyncronously connect to twitter - java

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

Related

ASyncTask with progressdialog and button

I am beginner and I had a test. I did all tasks, but I have a problem -
public class HttpTask extends AsyncTask<Integer, String, String> {####
ProgressDialog dialog;
Context context;
public HttpTask(Activity activity) {
//init progress dialog
dialog = new ProgressDialog(context);****
dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
}
protected void onPreExecute() {
// show progress dialog
dialog.setMessage("Loading...");
dialog.setCancelable(false);
}
protected String doInBackground(Integer... params) {
//freeze system to 5 seconds
try {
int seconds = params[0]*5;####
TimeUnit.SECONDS.sleep(seconds);
} catch (InterruptedException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(final String success) {
// if there is progress dialog hide it
dialog.dismiss();
}
}
It crashes, when I try to compile it (I showed where are problems with * sign):
08-03 10:43:10.873 29441-29441/? E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.NullPointerException
at android.app.AlertDialog.resolveDialogTheme(AlertDialog.java:142)
at android.app.AlertDialog.<init>(AlertDialog.java:98)
at android.app.ProgressDialog.<init>(ProgressDialog.java:77)
at net.joerichard.androidtest.main.f.HttpTask.<init>(HttpTask.java:26)
at net.joerichard.androidtest.main.f.F_Networking_Activity$1.onClick(F_Networking_Activity.java:27)
at android.view.View.performClick(View.java:4107)
at android.view.View$PerformClick.run(View.java:17166)
at android.os.Handler.handleCallback(Handler.java:615)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:155)
at android.app.ActivityThread.main(ActivityThread.java:5559)
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:1074)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:841)
at dalvik.system.NativeStart.main(Native Method)
08-03 10:43:10.913 754-877/? E/EmbeddedLogger﹕ App crashed! Process: net.joerichard.androidtest
08-03 10:43:10.913 754-877/? E/EmbeddedLogger﹕ App crashed! Package: net.joerichard.androidtest v1 (1.0)
08-03 10:43:10.913 754-877/? E/EmbeddedLogger﹕ Application Label: AndroidTest
This is class of main activity.
public class F_Networking_Activity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_f__networking_);
// bDownload: start HttpTask
Button bDownload = (Button) findViewById(R.id.bDownload);
bDownload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
HttpTask task = new HttpTask(F_Networking_Activity.this);****
task.execute();
}
});
}
Thank you for your answers. Now I have another problem (I showed with # sign of second problems)
08-03 11:28:18.292 754-877/? E/EmbeddedLogger﹕ App crashed! Process: net.joerichard.androidtest'
08-03 11:28:18.292 754-877/? E/EmbeddedLogger﹕ App crashed! Package: net.joerichard.androidtest v1 (1.0)
08-03 11:28:18.292 754-877/? E/EmbeddedLogger﹕ Application Label: AndroidTest
08-03 11:28:18.292 30544-30726/? E/AndroidRuntime﹕ FATAL EXCEPTION: AsyncTask #1
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:299)
at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:273)
at java.util.concurrent.FutureTask.setException(FutureTask.java:124)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:307)
at java.util.concurrent.FutureTask.run(FutureTask.java:137)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
at java.lang.Thread.run(Thread.java:864)
Caused by: java.lang.ArrayIndexOutOfBoundsException: length=0; index=0
at net.joerichard.androidtest.main.f.HttpTask.doInBackground(HttpTask.java:40)
at net.joerichard.androidtest.main.f.HttpTask.doInBackground(HttpTask.java:20)
at android.os.AsyncTask$2.call(AsyncTask.java:287)
at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
at java.util.concurrent.FutureTask.run(FutureTask.java:137)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:230)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1076)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:569)
at java.lang.Thread.run(Thread.java:864)
Actually, your context is null because you didn't initialize it.
Add one extra line inside your HttpTask:
public HttpTask(Activity activity) {
this.context = activity;
dialog = new ProgressDialog(context);
dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
}
and change Context to Activity like this:
Activity context;
Now call this context anywhere in your class.
Yes you must get NullPointer. Because your context is null.
Change this like
public HttpTask(Context _context) {
context = _context;
//init progress dialog
dialog = new ProgressDialog(context);****
dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
}

Cant start a dialog activity from a button in another activity

I am trying to start a new activity as a Dialog Activity putting a Intent on a button from another activity. Whenever I try and press the button, the activity unfotunately closes.
Main Activity.java
public class MainActivity extends FragmentActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button ab = (Button) findViewById(R.id.button1);
ab.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent intent = new Intent(MainActivity.this, NewDialog.class);
startActivity(intent);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public void side(View view){
android.support.v4.app.FragmentManager fm1 = getSupportFragmentManager();
NewDialog newdialog = new NewDialog();
newdialog.show(fm1, "SideDialog");
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
}
NewDialog.java
public class NewDialog extends DialogFragment{
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState){
final View view = inflater.inflate(R.layout.activity_new_dialog, container);
getDialog().requestWindowFeature(Window.FEATURE_NO_TITLE);
return view;
}
}
Added Logcat:
05-29 22:37:36.472: D/dalvikvm(26806): Late-enabling CheckJNI
05-29 22:37:36.762: D/ActivityThread(26806): setTargetHeapUtilization:0.25
05-29 22:37:36.762: D/ActivityThread(26806): setTargetHeapIdealFree:8388608
05-29 22:37:36.762: D/ActivityThread(26806): setTargetHeapConcurrentStart:2097152
05-29 22:37:39.172: D/libEGL(26806): loaded /system/lib/egl/libEGL_adreno200.so
05-29 22:37:39.222: D/libEGL(26806): loaded /system/lib/egl/libGLESv1_CM_adreno200.so
05-29 22:37:39.322: D/libEGL(26806): loaded /system/lib/egl/libGLESv2_adreno200.so
05-29 22:37:39.362: I/Adreno200-EGL(26806): <qeglDrvAPI_eglInitialize:299>: EGL 1.4 QUALCOMM build: AU_LINUX_ANDROID_JB_REL_2.0.3.1_RB1.04.01.01.45.000_msm8625_JB_REL_2.0.3.1_Merge_release_AU (Merge)
05-29 22:37:39.362: I/Adreno200-EGL(26806): Build Date: 03/28/13 Thu
05-29 22:37:39.362: I/Adreno200-EGL(26806): Local Branch:
05-29 22:37:39.362: I/Adreno200-EGL(26806): Remote Branch: m/jb_rel_2.0.3.1
05-29 22:37:39.362: I/Adreno200-EGL(26806): Local Patches: NONE
05-29 22:37:39.362: I/Adreno200-EGL(26806): Reconstruct Branch: NOTHING
05-29 22:37:39.452: D/OpenGLRenderer(26806): Enabling debug mode 0
05-29 22:37:43.822: D/AndroidRuntime(26806): Shutting down VM
05-29 22:37:43.822: W/dalvikvm(26806): threadid=1: thread exiting with uncaught exception (group=0x40fd4438)
05-29 22:37:44.022: E/AndroidRuntime(26806): FATAL EXCEPTION: main
05-29 22:37:44.022: E/AndroidRuntime(26806): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.createdialog/com.example.createdialog.NewDialog}: java.lang.ClassCastException: com.example.createdialog.NewDialog cannot be cast to android.app.Activity
05-29 22:37:44.022: E/AndroidRuntime(26806): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2038)
05-29 22:37:44.022: E/AndroidRuntime(26806): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2139)
05-29 22:37:44.022: E/AndroidRuntime(26806): at android.app.ActivityThread.access$700(ActivityThread.java:143)
05-29 22:37:44.022: E/AndroidRuntime(26806): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1241)
05-29 22:37:44.022: E/AndroidRuntime(26806): at android.os.Handler.dispatchMessage(Handler.java:99)
05-29 22:37:44.022: E/AndroidRuntime(26806): at android.os.Looper.loop(Looper.java:137)
05-29 22:37:44.022: E/AndroidRuntime(26806): at android.app.ActivityThread.main(ActivityThread.java:4963)
05-29 22:37:44.022: E/AndroidRuntime(26806): at java.lang.reflect.Method.invokeNative(Native Method)
05-29 22:37:44.022: E/AndroidRuntime(26806): at java.lang.reflect.Method.invoke(Method.java:511)
05-29 22:37:44.022: E/AndroidRuntime(26806): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1038)
05-29 22:37:44.022: E/AndroidRuntime(26806): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:805)
05-29 22:37:44.022: E/AndroidRuntime(26806): at dalvik.system.NativeStart.main(Native Method)
05-29 22:37:44.022: E/AndroidRuntime(26806): Caused by: java.lang.ClassCastException: com.example.createdialog.NewDialog cannot be cast to android.app.Activity
05-29 22:37:44.022: E/AndroidRuntime(26806): at android.app.Instrumentation.newActivity(Instrumentation.java:1068)
05-29 22:37:44.022: E/AndroidRuntime(26806): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2029)
05-29 22:37:44.022: E/AndroidRuntime(26806): ... 11 more
I might be wrong here, but as far as I know, you can't start an Intent passing a DialogFragment, you should pass an Activity. Here's what's wrong:
Intent intent = new Intent(MainActivity.this, NewDialog.class);
startActivity(intent);
Since NewDialog is declared as a DialogFragment and not as an Activity subclass.
If what you are trying to do is show the dialog, then you should do:
NewDialog dialog = NewDialog();
// use getSupportFragmentManager() if using support fragments instead of native fragments, or
// use getChildFragmentManager() if this code is inside a fragment rather than an activity
dialog.show(getFragmentManager(), "pass-any-string-here");
Without a logcat stacktrace to look at, I am assuming that your issue has to do with variable scope (here is an example explanation on the topic).
What you need to do is declare your button as a class level variable because right now it is a method variable and as such ceases to exist once your onCreate method has finished executing.
public class MainActivity extends FragmentActivity {
private Button myButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myButton = (Button) findViewById(R.id.button1);
myButton.setOnClickListener(...);
...
}
}

Android Development DropboxUnlinkedException

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

Create Dialog Box For Checking Internet Connection in Android

I'm implementing to show dialog box when Internet is offline, when i run my app i got "FATAL Exception main" and ClassCastException when when i click on button and application is crash . Can someone tell me what i am doing wrong ? Thanks to you in Advanced.
here is code how i check is internet enabled or not:
public class AndroidDetectInternetConnectionActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button btnStatus = (Button) findViewById(R.id.btn_check);
btnStatus.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!isOnline())
{
showNoConnectionDialog(this);
}
}
});
}
public static void showNoConnectionDialog(OnClickListener onClickListener)
{
final Context ctx = (Context) onClickListener;
AlertDialog.Builder builder = new AlertDialog.Builder(ctx);
builder.setCancelable(true);
builder.setMessage(R.string.no_connection);
builder.setTitle(R.string.no_connection_title);
builder.setPositiveButton(R.string.settings_button_text, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which)
{
ctx.startActivity(new Intent(Settings.ACTION_WIRELESS_SETTINGS));
}
});
builder.setNegativeButton(R.string.cancel_button_text, new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which)
{
return;
}
});
builder.setOnCancelListener(new DialogInterface.OnCancelListener()
{
public void onCancel(DialogInterface dialog) {
return;
}
});
builder.show();
}
public boolean isOnline()
{
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnectedOrConnecting())
{
return true;
}
return false;
}
}
// This is my Log Cat stack trace
11-15 11:57:19.115: D/AndroidRuntime(453): Shutting down VM
11-15 11:57:19.115: W/dalvikvm(453): threadid=1: thread exiting with uncaught exception (group=0x40015560)
11-15 11:57:19.122: E/AndroidRuntime(453): FATAL EXCEPTION: main
11-15 11:57:19.122: E/AndroidRuntime(453): java.lang.ClassCastException: com.example.detectinternetconnection.AndroidDetectInternetConnectionActivity$1
11-15 11:57:19.122: E/AndroidRuntime(453): at com.example.detectinternetconnection.AndroidDetectInternetConnectionActivity.showNoConnectionDialog(AndroidDetectInternetConnectionActivity.java:99)
11-15 11:57:19.122: E/AndroidRuntime(453): at com.example.detectinternetconnection.AndroidDetectInternetConnectionActivity$1.onClick(AndroidDetectInternetConnectionActivity.java:64)
11-15 11:57:19.122: E/AndroidRuntime(453): at android.view.View.performClick(View.java:2485)
11-15 11:57:19.122: E/AndroidRuntime(453): at android.view.View$PerformClick.run(View.java:9080)
11-15 11:57:19.122: E/AndroidRuntime(453): at android.os.Handler.handleCallback(Handler.java:587)
11-15 11:57:19.122: E/AndroidRuntime(453): at android.os.Handler.dispatchMessage(Handler.java:92)
11-15 11:57:19.122: E/AndroidRuntime(453): at android.os.Looper.loop(Looper.java:123)
11-15 11:57:19.122: E/AndroidRuntime(453): at android.app.ActivityThread.main(ActivityThread.java:3683)
11-15 11:57:19.122: E/AndroidRuntime(453): at java.lang.reflect.Method.invokeNative(Native Method)
11-15 11:57:19.122: E/AndroidRuntime(453): at java.lang.reflect.Method.invoke(Method.java:507)
11-15 11:57:19.122: E/AndroidRuntime(453): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
11-15 11:57:19.122: E/AndroidRuntime(453): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
11-15 11:57:19.122: E/AndroidRuntime(453): at dalvik.system.NativeStart.main(Native Method)
11-15 11:57:24.892: I/Process(453): Sending signal. PID: 453 SIG: 9
change this line
final Context ctx = (Context) onClickListener;
to below one
final Context ctx = AndroidDetectInternetConnectionActivity.this;
basically you are trying to conver onClickListener to Contex which is incorrect and can not be casted.
Either you directly use ActivityName.this wherever you need context instance, or define static Context ctx as a class variable and intialize it in onCreate()by just adding this line ctx =this also remember to intialize it before using it.
Enjoy
There are two ways to solve this problem.
1) showNoConnectionDialog(this); and later on:
public static void showNoConnectionDialog(Context ctx) ...
2) showNoConnectionDialog(); and later on: public void showNoConnectionDialog() { Context ctx = AndroidDetectInternetConnectionActivity.this
You basic problem is generated by the line:
final Context ctx = (Context) onClickListener;
This is simply not a context so trying to force it to be one doesn't work.
I believe that you wanted to do was pass a context (or activity) to this function (as opposed to the local unnamed OnClickListener class that you are now passing)
The easiest solution would be to simple not pass anything to the constructor and use AndroidDetectInternetConnectionActivity.this to access your valid context.

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.

Categories