Register a SA Forums Account here!
JOINING THE SA FORUMS WILL REMOVE THIS BIG AD, THE ANNOYING UNDERLINED ADS, AND STUPID INTERSTITIAL ADS!!!

You can: log in, read the tech support FAQ, or request your lost password. This dumb message (and those ads) will appear on every screen until you register! Get rid of this crap by registering your own SA Forums Account and joining roughly 150,000 Goons, for the one-time price of $9.95! We charge money because it costs us money per month for bills, and since we don't believe in showing ads to our users, we try to make the money back through forum registrations.
 
  • Post
  • Reply
Sereri
Sep 30, 2008

awwwrigami

Just came across this by chance:

stackoverflow posted:

I have a Preference activity which uses a List Preferences as defined by my XML file. How would I set the summary of the list activity to the value that is selected?

Thank you!

stackoverflow answer posted:

The simplest way to do this is just to have Android do it for you. Assuming you want the summary to match the selected value, you can simply set the summary of the ListPreference to "%s".

Android will replace %s with the current string value of the preference, as displayed by the ListPreference's picker.

I spent far too much time mucking about with SharedPreferences listeners before I discovered this. As a bonus, the list's summary will be set correctly when you enter the activity.

:aaaaa:

I'm currently at work and can't try this but it would probably cut down Awful's settings.java by like 80%.

Are there more magical tricks like this I don't know of?

Adbot
ADBOT LOVES YOU

Tunga
May 7, 2004

Grimey Drawer

Jabor posted:

The easy way to get data into a ListView:

- Create a custom subclass of BaseAdapter.
- Implement getCount() to return the total number of items in your data set.
- Implement getView(int position, View convertView, ViewGroup parent) to inflate a new view from whatever layout you want to use, populate it with the data from the appropriate position in your data set, and return it.
- Give the ListView your adapter.
This was helpful, thanks. But now I'm confused about how separators work.

I basically have three lists that I was to display one after another with a small "header" at the top of each one.

Would be easier to just add three ListViews to my layout?

zeekner
Jul 14, 2007

Tunga posted:

This was helpful, thanks. But now I'm confused about how separators work.

I basically have three lists that I was to display one after another with a small "header" at the top of each one.

Would be easier to just add three ListViews to my layout?

Three listviews wouldn't let you scroll between them.

I haven't worked with the new RecyclerView stuff, but the way I did what you are trying to do is with multiple item types in the same listview. Adapters are actually pretty flexible, but there are a ton of quirks you have to watch out for. I wrote a Adapter/Item library that let me mix multiple different row types and also group them at will. It's how I do section/page dividers in something.apk.



I need to write a few pages of documentation to explain everything it does, but hopefully a brief explanation will help for now:

I have a FastAdapter in FastLibrary, it handles multiple item types, onclick events, ViewHolders, and a bunch of workarounds for silly limitations in Android's ListView.
Basic FastAdapter implementation or the Sectioned Adapter that just allows me to group items together. (Ignore everything outside the list section of FastLibrary, it's all terrible util library bullshit.)

The list items are a subclass of BaseFastItem which implements a bunch of helper stuff and handles ViewHolder creation, view updating, ids, ect. A basic example in Something is the forum Divider which does nothing but show some text.

To use the FastAdapter, just create it and plug it into the listview:
code:
//maxTypeCount is the number of unique view types you will use,
//count the number of different R.layout.X types you will use, you can set it higher than you will actually use.
//this is required because of dumb limitations in ListView recycling management.
adapter = new FastAdapter(yourFragment, maxTypeCount);

listView = (ListView) frag.findViewById(R.id.listview);
listView.setAdapter(adapter);

//(optional) enables onClick callback in your BaseFastItem subclass
listView.setOnItemClickListener(adapter);
Then just create a bunch of list items, which implement BaseFastItem, then insert them into the adapter.

adapter.addItems(yourListItems);
or
sectionAdapter.addItems(groupNumber, yourListItems);

Now having written all of this, I have a big disclaimer: I'm not going to support this library nor do any future work on it, and it's not documented because I am terrible. It works great for what I needed to do, and digging through it should help you understand exactly what ListView is capable of. The new RecyclerView stuff would be a great starting point for a rewrite of this library, but I'm not doing Android development right now so that's probably not going to happen. Hopefully someone will take the new RecyclerView stuff and writes a nice wrapper library for it.

Tunga
May 7, 2004

Grimey Drawer
Cool, thanks for the quick write-up, that's basically the conclusion I came to after trying three lists and realising that you can't lay them out the way I wanted to because they scroll individually.

This was for a pre-interview exercise which I was supposed to be able to do in 2-3 hours. It seems like this is a lot more work than that so either I am nowhere near the level they want or the person who wrote the task knows jack poo poo about Android. I don't know which it is but the PDF describing the problem has screenshots of their iOS app as examples so...yeah.

I ended up downloading their current Android app to see if I was misunderstanding what they wanted. The first thing it did was demand my Facebook login, the second thing it did was ask for permission to make posts without my knowledge, and the third thing it did is get uninstalled because gently caress that poo poo.

I told the recruiter that their product "wasn't really me" :) .

Glimm
Jul 27, 2005

Time is only gonna pass you by

Uncomfortable Gaze posted:

Hopefully someone will take the new RecyclerView stuff and writes a nice wrapper library for it.

I haven't had a chance to play with it much but TwoWay-View aims to do just that.

kitten smoothie
Dec 29, 2001

Good News, from the people who bring you Google Play Services

quote:

As we’ve continued to add more APIs across the wide range of Google services, it can be hard to maintain a lean app, particularly if you're only using a portion of the available APIs. Now with Google Play services 6.5, you’ll be able to depend only on a minimal common library and the exact APIs your app needs. This makes it very lightweight to get started with Google Play services.

:toot:

baka kaba
Jul 19, 2003

PLEASE ASK ME, THE SELF-PROFESSED NO #1 PAUL CATTERMOLE FAN IN THE SOMETHING AWFUL S-CLUB 7 MEGATHREAD, TO NAME A SINGLE SONG BY HIS EXCELLENT NU-METAL SIDE PROJECT, SKUA, AND IF I CAN'T PLEASE TELL ME TO
EAT SHIT

Holy poo poo, why is it so hard to make a folder in the Android/data folder that actually shows up as a folder under MTP? No matter what I do it appears as a generic 'file' in Windows. It's definitely a folder, and there's another file inside it on the filesystem!

Debugging code shows they're both present and correct, it all shows up fine in the emulator's file explorer, I'm running MediaScannerConnection.scanFile() to make sure they appear (otherwise the folder I'm creating doesn't show up at all, so it is scanning them), they're set to fully readable and writeable, what the gently caress?

Anyone have any idea what the problem is here? I thought I'd just be calling mkdirs() and getting on with my life

Sereri
Sep 30, 2008

awwwrigami

What are people here using for crash reporting/analysis?

Awful has been using Bugsense for a couple of years now, but I've never been really happy with it and would love some input.

The Gay Bean
Apr 19, 2004
I have a large-sh C++ project I'm trying to get working on Android. The GUI is isolated from the meat of the program, and I've confirmed library support on Android.

The problem is that I'm having a hell of a time with Eclipse. I'm not really asking for much: just editor support for C++ code. The Project Tango SDK and all of the examples ( https://developers.google.com/project-tango/downloads ) are all geared toward Eclipse, which is my main reason for not jumping ship to Android Studio. Yesterday I spent a ton of time getting everything checked into Git, deleting the repo, checking it out, and making sure it would build on different computers, but today, wit absolutely no change on my part, I opened up eclipse and am greeted with jagged red lines and failed builds. There's also a year-old bug in which changing the NDK toolchain doesn't update Eclipse, and there's fuckall you can do about it (the solution in that link does not work.) When it comes time to import my code into the project, which makes heavy use of std::threads and mutexes, I'm stuck either changing everything over to pthreads or boost or abandoning editor support anyway.

My question is: what is the accepted way of dealing with large NDK projects and keeping editor support? Android Studio + Gradle? Eclipse + a huge headache? Eclipse + ndk-build + an external tool? Every time I search for any solution I always come across a 1000 page tutorial from 2009 that has a ton of outdated information. At the moment, Android Studio seems like the way to go, but I want to make sure that the time investment of switching / learning Gradle is worth it before I begin.

MrZig
Aug 13, 2005
I exist onl because of Parias'
LEGENDARY GENEROSITY.
Do people like beta testing? I developed a new game for Android called "Hipster Dave" and I need some more testers. If you have a gmail account, go to this link

https://groups.google.com/forum/#!forum/hipster-dave-beta-test

And join the group, then follow the instructions:

https://play.google.com/apps/testing/com.neverlift.hipsterdave


The game is about a hipster falling through the sky collecting vinyl records. Each vinyl record plays a note in a song that is unique to each level. So far there are 3 levels, and two difficulties. Full Google Play leaderboards and achievements.

If anyone has a Galaxy S4, I would like to talk to you directly. I'm having issues only concerning that phone right now. Send me a message through the group.

MrZig fucked around with this message at 02:02 on Nov 30, 2014

fritz
Jul 26, 2003

The Gay Bean posted:

I have a large-sh C++ project I'm trying to get working on Android. The GUI is isolated from the meat of the program, and I've confirmed library support on Android.

The problem is that I'm having a hell of a time with Eclipse. I'm not really asking for much: just editor support for C++ code. The Project Tango SDK and all of the examples ( https://developers.google.com/project-tango/downloads ) are all geared toward Eclipse, which is my main reason for not jumping ship to Android Studio. Yesterday I spent a ton of time getting everything checked into Git, deleting the repo, checking it out, and making sure it would build on different computers, but today, wit absolutely no change on my part, I opened up eclipse and am greeted with jagged red lines and failed builds. There's also a year-old bug in which changing the NDK toolchain doesn't update Eclipse, and there's fuckall you can do about it (the solution in that link does not work.) When it comes time to import my code into the project, which makes heavy use of std::threads and mutexes, I'm stuck either changing everything over to pthreads or boost or abandoning editor support anyway.

My question is: what is the accepted way of dealing with large NDK projects and keeping editor support? Android Studio + Gradle? Eclipse + a huge headache? Eclipse + ndk-build + an external tool? Every time I search for any solution I always come across a 1000 page tutorial from 2009 that has a ton of outdated information. At the moment, Android Studio seems like the way to go, but I want to make sure that the time investment of switching / learning Gradle is worth it before I begin.

I'm in this situation as well, please report back with whatever you find.

fritz
Jul 26, 2003

Actually, here's a more basic NDK question. I have a C++ library that I need to wrap inside an android app. In my project, I have a jni/ directory (which is a symlink to the actual directory) and Android.mk and Application.mk files. I can successfully run ndk-build and get a libX.so. Then in the app, I have another jni/ directory:
code:
app/src/main/
                      java/
                      jni/
which has a .h file that I made from running javah, and a .cpp file that has the functions that wrap the library methods. The problem is when I try to build the project (in Android Studio), I get linker errors where it's unable to link against the methods in libX.so. I don't know if it's even finding the library to link against.

Is there some common mistake I'm making?

MrZig
Aug 13, 2005
I exist onl because of Parias'
LEGENDARY GENEROSITY.
Are there any good resources for good practices for performance coding? Stuff like how calling a public variable from another class is faster than calling a get method, how defining variables before a for() loop searching an array is faster etc. That sort of stuff. I know Google has one on their Dev website, but I was wondering if there were more?

OzyMandrill
Aug 12, 2013

Look upon my words
and despair

The Gay Bean posted:

My question is: what is the accepted way of dealing with large NDK projects and keeping editor support? Android Studio + Gradle? Eclipse + a huge headache? Eclipse + ndk-build + an external tool? Every time I search for any solution I always come across a 1000 page tutorial from 2009 that has a ton of outdated information. At the moment, Android Studio seems like the way to go, but I want to make sure that the time investment of switching / learning Gradle is worth it before I begin.

Just top throw a spanner in the works - I use Visual Studio + nVidia Tegra App Dev Pack (TADP) for large (million lines of code+) NDK stuff. It's not too bad, but has an entirely different set of quirks to Eclipse on top of the usual android build ones, and less people use it so not always easy to get answers. Never not take the opportunity to learn how to setup & use new toolchains!

tRIDAV
Jul 10, 2001

Oh, cruel fates, to be thusly boned. Ask not for whom the bone bones, it bones for thee.

I'm having an issue with a custom view and I am at a loss of how to go about solving it. I have a custom view which is a variant of a progress bar. I have a method that allows me to change the Paint color. The custom view is part of a compound view that gets used in my layout/activity.

The issue I'm getting is when I try setting the color in the onCreate() of the activity, the color isn't changed. If I change the color in places like an onClickListener event then it works. The only way I can get the color to be set in the onCreate is by setting a Handler to update the color.

Activity:
code:

    @Override
    protected void onCreate(Bundle savedInstanceState) {
	.
	.
	.
	//doesn't work
	 mObj.setColor(getResources().getColor(R.color.green)); 

	//this works fine
        final Handler handler = new Handler();
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                mObj.setColor(getResources().getColor(R.color.green));
            }
        }, 100);
	.
	.	
	.
	}
which calls

CompoundView:
code:
    public void setColor(int color){
        customView.setCustomColor(color);
    }

which calls

CustomView:
code:
    public void setCustomColor(int color){
        this.solidFillPaint.setColor(color);
        invalidate();
        requestLayout();
    }
If anyone has an idea of why this is an issue being placed in onCreate I'd love to read up more on this.

edit: Manage to find a work around. Instead of setting the Paint color directly, I store the color value and set it during the onDraw.

tRIDAV fucked around with this message at 23:38 on Dec 3, 2014

fritz
Jul 26, 2003

Some JNI trouble. I have a class with:
code:
    private long skpointer = 0;
and this is going to store a pointer to a c++ object that I allocate in a native method:

code:
JNIEXPORT void JNICALL Java_com_example_pkg_cls_load
  (JNIEnv * env, jobject jobj) {
    // ...
    A* a = new A(parameter);
    jlong saveme =  (jlong)a;
    jfieldID fid = env->GetFieldID(cls, "skpointer", "J");
    env->SetLongField(jobj, fid, saveme);
    // ... 
}
I can print out "saveme" in the c++ code, and in the java code, and they're the same. The problem is I'm not able to read this back out inside a subsequent call. That is:
code:

JNIEXPORT void JNICALL Java_com_example_pkg_class_checkptr
  (JNIEnv * env, jobject jobj) {

  
  jclass cls = env->GetObjectClass(jobj);
  jfieldID pid = env->GetFieldID(cls, "skpointer", "J");
  long ptr = (jlong)(env->GetObjectField(jobj, pid));
   std::stringstream summary;
   summary << "Pointer value is " << std::hex << ptr;
   std::string sumout = summary.str();
   __android_log_write(ANDROID_LOG_DEBUG, "pointer check", sumout.c_str());
  }
The value printed here is different than the original pointer value, and it changes every time it's called. So if the original pointer was at ffffffffae8b8c40, three calls to checkptr give e760001d, e770001d, e780001d.


Does anybody see anything obviously wrong?


EDIT: found it, I needed env->GetLongField instead of env->GetObjectField.

fritz fucked around with this message at 23:31 on Dec 3, 2014

genki
Nov 12, 2003

tRIDAV posted:

If anyone has an idea of why this is an issue being placed in onCreate I'd love to read up more on this.

edit: Manage to find a work around. Instead of setting the Paint color directly, I store the color value and set it during the onDraw.
Off the top of my head, I'd guess that the view isn't actually inflated in onCreate when you try to set the color (which is also why it works when you post to the main thread handler, because that's getting run after the inflation, I assume because the method will get posted after the activity and view lifecycle events. You could probably test this by trying to run the method at the front of the queue, which should fail. postAtFrontOfQueue is the method). Similar to your workaround, you could try setting the paint color in the activity onCreate on the custom view, then in the custom view's onFinishInflate, set the paint color. Not a huge difference at that point though.

ButtaKnife
Mar 12, 2007

"I WILL DEVOUR 100 GENERATIONS OF YOUR FAMILY!"

Sereri posted:

What are people here using for crash reporting/analysis?

Awful has been using Bugsense for a couple of years now, but I've never been really happy with it and would love some input.

A bit late with this, but Crashlytics is fantastic. I'm really liking it so far. What solution did you end up with?

Glimm
Jul 27, 2005

Time is only gonna pass you by

Woop woop, Android Studio 1.0:
https://developer.android.com/sdk/index.html

Eclipse/ADT look pretty dead in the water:

Android Developer Tools posted:

Caution: The ADT plugin for Eclipse is no longer in active development. If you're currently using it, you should migrate to Android Studio as soon as possible. For more details about Android Studio, see the Android Studio guide.

baka kaba
Jul 19, 2003

PLEASE ASK ME, THE SELF-PROFESSED NO #1 PAUL CATTERMOLE FAN IN THE SOMETHING AWFUL S-CLUB 7 MEGATHREAD, TO NAME A SINGLE SONG BY HIS EXCELLENT NU-METAL SIDE PROJECT, SKUA, AND IF I CAN'T PLEASE TELL ME TO
EAT SHIT

Haven't tried this for a long while, that live Memory Monitor gizmo is really slick :swoon:

Or should I say :pcgaming:

e- already managed to break everything horribly by daring to refactor my project's name to something other than 'app'

baka kaba fucked around with this message at 15:35 on Dec 9, 2014

Sereri
Sep 30, 2008

awwwrigami

ButtaKnife posted:

A bit late with this, but Crashlytics is fantastic. I'm really liking it so far. What solution did you end up with?

Well I'm late with the reply too so it all balances out :). I'm still using ACRA/Bugsense or whatever it's called now. I'm currently looking at Crashlytics and it looks decent, I might give it a shot soon.

speng31b
May 8, 2010

MrZig posted:

Are there any good resources for good practices for performance coding? Stuff like how calling a public variable from another class is faster than calling a get method, how defining variables before a for() loop searching an array is faster etc. That sort of stuff. I know Google has one on their Dev website, but I was wondering if there were more?

Avoiding Object creation in loops or other frequently called code (draw loops, hashcode methods, touch events, sensor callbacks, etc...) will be the single biggest practical performance gain by far. Keep in mind that you'll almost never be attacking a real bottleneck by doing stuff like declaring variables outside loops and preferring public fields over methods, and you might be making your code less readable and harder to extend and maintain.

On unrelated note, gently caress Fragments. I'm sort of on the tail end of developing an Android & iOS app for a Fortune 500 retail client. We released the app a few months ago, and we're just in maintenance cycles now. For the first time in Real Life, I got permission from a client to not support as far back as Gingerbread, so I decided to go down the screen-per-Fragment over screen-per-Activity approach since I didn't have to worry about supporting below ICS, and you know, Fragments are awesome! All I've got to say is, gently caress Fragments. gently caress their lovely finnicky lifecycle, their habit of re-adding themselves to containers in the wrong order across config changes, gently caress the inscrutable crash reports coming from inside the Fragment manager, gently caress the fact that even though I've executed all committed all Fragment operations immediately to avoid the ugly race conditions that pop up when you allow their default posted behavior to run wild, internal Fragment operations on Activity restoration will still cause impossible-to-reproduce race conditiony crashes. gently caress the fact that Google built what should be a simple screen and nav stack system that works on top of Views and turned it into the most over-architected piece of poo poo imaginable, not to mention Fragments' fragmented (heh...) behavior across Android versions. Oh, and if you decided to use the support library Fragment manager because you need nested Fragment support through the child Fragment manager on versions below API level 17? Well, enjoy even more crashes and known unpatched years-old bugs.

Here's an awesome article from Square on why Fragments are utter poo poo and what to do about it, and after my bitterness resides a little I'm going to seriously consider taking this approach in my next project. Even if you think I'm full of poo poo and Fragments are great, this article is really worth a read: http://corner.squareup.com/2014/10/advocating-against-android-fragments.html

speng31b fucked around with this message at 05:18 on Dec 17, 2014

Doctor w-rw-rw-
Jun 24, 2008

Yesssss...let the hate flow through you. I went through nearly the same thing a couple of years ago, though possibly worse since Android 7-9 was a total shitshow and video playback was the wild west on any Android version less than 4.0, and still woefully inconsistent and terrible on higher versions.

Thanks for the article.

speng31b
May 8, 2010

Doctor w-rw-rw- posted:

Yesssss...let the hate flow through you. I went through nearly the same thing a couple of years ago, though possibly worse since Android 7-9 was a total shitshow and video playback was the wild west on any Android version less than 4.0, and still woefully inconsistent and terrible on higher versions.

Thanks for the article.

At any given time video playback is always going to be one of the worst things about Android. I basically mentally filter out crash reports from the video player activity because it's too depressing to even consider how powerless I am to fix those.

My favorites are crash reports from embedded html5 video trying to play in a webview.

speng31b fucked around with this message at 07:38 on Dec 17, 2014

Doctor w-rw-rw-
Jun 24, 2008

speng31b posted:

My favorites are crash reports from embedded html5 video trying to play in a webview.
Definitely preferable over one or more video players inside a fragment each, inside an activity, though.

hooah
Feb 6, 2006
WTF?
I'm near the beginning of Udacity's Android App Development course, and I figure this might be a better place for my stupid Java/Android-newbie questions than the Java thread. The course talks you through making a weather app. So, I've got the MainActivity and the fragment. At this point, I'm supposed to push the app to my phone and hit the refresh button. An expected crash happens, and I'm to look in the logcat and choose the right error from a list of four. The problem is that the error I get (NetworkOnMainThreadException) apparently isn't the right one. I'm guessing I did something unexpected, having come from C++ with not a whole lot of Java experience. What did I do wrong?

Volmarias
Dec 31, 2002

EMAIL... THE INTERNET... SEARCH ENGINES...

hooah posted:

I'm near the beginning of Udacity's Android App Development course, and I figure this might be a better place for my stupid Java/Android-newbie questions than the Java thread. The course talks you through making a weather app. So, I've got the MainActivity and the fragment. At this point, I'm supposed to push the app to my phone and hit the refresh button. An expected crash happens, and I'm to look in the logcat and choose the right error from a list of four. The problem is that the error I get (NetworkOnMainThreadException) apparently isn't the right one. I'm guessing I did something unexpected, having come from C++ with not a whole lot of Java experience. What did I do wrong?

You did networking on the Ui thread, it sounds like. Strict Mode will crash you if you do that so as to make you aware that you did something really dumb. Use an async task and do something with the callback.

Welcome to event driven programming.

If you did not do that, a stack trace and relevant lines of code would help.

hooah
Feb 6, 2006
WTF?
There's a nested async task in the fragment that's supposed to be doing that in onOptionsItemSelected:

Java code:
@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_refresh) {
        FetchWeatherTask task = new FetchWeatherTask();
        task.doInBackground();
    }
    return super.onOptionsItemSelected(item);
}

zeekner
Jul 14, 2007

hooah posted:

There's a nested async task in the fragment that's supposed to be doing that in onOptionsItemSelected:

Java code:
        FetchWeatherTask task = new FetchWeatherTask();
        task.doInBackground();
}

There's a problem, calling doInBackground() will actually do the work in the UI thread. You need to call execute(), which will call the doInBackground method in a secondary thread.

Volmarias
Dec 31, 2002

EMAIL... THE INTERNET... SEARCH ENGINES...

Uncomfortable Gaze posted:

There's a problem, calling doInBackground() will actually do the work in the UI thread. You need to call execute(), which will call the doInBackground method in a secondary thread.

This, you're directly calling that method. When you call execute, the task starts another thread which is then given that task and runs the doInBackground etc methods.

hooah
Feb 6, 2006
WTF?
Well it would've been nice if they'd loving mentioned that anywhere :psyduck:
Why would telling an async task to do in the background not ...do it in the background??

zeekner
Jul 14, 2007

hooah posted:

Well it would've been nice if they'd loving mentioned that anywhere :psyduck:
Why would telling an async task to do in the background not ...do it in the background??

The doInBackground method is the thing that's being overloaded when you define the task. It's a real poor choice of name, and they probably would have been better off making that function protected/private to hide it. Google is bad at naming/designing/implementing things.

Volmarias
Dec 31, 2002

EMAIL... THE INTERNET... SEARCH ENGINES...

hooah posted:

Well it would've been nice if they'd loving mentioned that anywhere :psyduck:
Why would telling an async task to do in the background not ...do it in the background??

Because you're directly calling that method. It's meant as a callback. The documentation will both tell you this, and tell you exactly what to write to use this class.

Stop, think about what you're doing, and ask yourself why you believe that would, or could, work any differently. I understand that you're new to java AND android, but this would do the same thing in C++.

hooah
Feb 6, 2006
WTF?
I probably should have learned what a callback is before doing this, I guess. Any good references for that? The Wikipedia page wasn't terribly helpful.

I did miss the bit that said "Once created, a task is executed very simply:" though.

speng31b
May 8, 2010

hooah posted:

I probably should have learned what a callback is before doing this, I guess. Any good references for that? The Wikipedia page wasn't terribly helpful.

I did miss the bit that said "Once created, a task is executed very simply:" though.

A callback is a mechanism by which the observer pattern is implemented (http://en.wikipedia.org/wiki/Observer_pattern). In Android, callbacks are sometimes used a lot to simplify logic for doing stuff that takes a long time and shouldn't have to halt the user interface thread while it's happening. Callbacks do exactly what they sound like - you tell something that you want it to "call you back" when it's ready to accomplish something.

Android is driven by callbacks - you can't really get anything done without at least responding to Views getting clicked with setOnClickListener. If you've seen that, it's basically the same thing AsyncTask is doing. The whole Activity lifecycle is made up of callbacks. The only big thing to watch out for in AsyncTask is that whatever code you write in your implementation of doInBackground had better not directly access anything external to the method - only access the data you are provided directly through the parameters, and only return data through the return type. If you feel compelled to break this rule, glance at the following book first and then decide not to: http://www.amazon.com/Java-Concurrency-Practice-Brian-Goetz/dp/0321349601

speng31b fucked around with this message at 23:56 on Dec 17, 2014

hooah
Feb 6, 2006
WTF?
Hmm. I learned about the observer pattern in my software design class, but we didn't deal with callbacks, I think because we weren't dealing with multiple threads. Now that you've mentioned the connection, that much makes sense, at least.

Also, I just finished my first OS course, the second half of which dealt entirely with concurrency, so yeah, not really wanting to touch that just yet. Thank you!

hooah
Feb 6, 2006
WTF?
I'm a little further on, and now being confounded by JSONObject and JSONArray. I have a JSON string that's the weather data from openweathermap.org. I'm trying to parse the thing to get the max temperature from a given day (day is an int). I read the class overview for both of these classes, and then skimmed through the methods. Here's my code attempt so far:
Java code:
public static double getMaxTemperatureForDay(String weatherJsonStr, int dayIndex)
		throws JSONException {
		JSONObject forecast = new JSONObject(weatherJsonStr);
        JSONArray days = forecast.getJSONArray("list");
        JSONObject day = days.get(dayIndex);
        JSONObject temps = day.get("temp");
        return temps.get("max");
	}
I'm using the Udacity IDE because I'm lazy, and it's giving me a few errors about incompatible types. The first is on the open paren in JSONObject day = days.get(dayIndex);. The message says that a JSONObject is required, but it found an Object. I don't understand why it's looking for a JSONObject, when the documentation says that the .get method of JSONArray takes an int.

zeekner
Jul 14, 2007

hooah posted:

I'm a little further on, and now being confounded by JSONObject and JSONArray. I have a JSON string that's the weather data from openweathermap.org. I'm trying to parse the thing to get the max temperature from a given day (day is an int). I read the class overview for both of these classes, and then skimmed through the methods. Here's my code attempt so far:
Java code:
public static double getMaxTemperatureForDay(String weatherJsonStr, int dayIndex)
		throws JSONException {
		JSONObject forecast = new JSONObject(weatherJsonStr);
        JSONArray days = forecast.getJSONArray("list");
        JSONObject day = days.get(dayIndex);
        JSONObject temps = day.get("temp");
        return temps.get("max");
	}
I'm using the Udacity IDE because I'm lazy, and it's giving me a few errors about incompatible types. The first is on the open paren in JSONObject day = days.get(dayIndex);. The message says that a JSONObject is required, but it found an Object. I don't understand why it's looking for a JSONObject, when the documentation says that the .get method of JSONArray takes an int.

The JSONObject/JSONArray get() methods return the item you want, but since Java is type-erasing it's a generic Object and you'll have to cast it. The way better thing to do is call days.getJSONObject() since that will do the cast internally. This applies to every type in the JSONObject/Array, you have getInt/getFloat/getString/ect.

Also, give Android Studio a shot when you have a chance, it's based on the really nice IntelliJ IDE and is pretty well integrated now.

zeekner fucked around with this message at 03:32 on Dec 18, 2014

speng31b
May 8, 2010

hooah posted:

I'm a little further on, and now being confounded by JSONObject and JSONArray. I have a JSON string that's the weather data from openweathermap.org. I'm trying to parse the thing to get the max temperature from a given day (day is an int). I read the class overview for both of these classes, and then skimmed through the methods. Here's my code attempt so far:
Java code:
public static double getMaxTemperatureForDay(String weatherJsonStr, int dayIndex)
		throws JSONException {
		JSONObject forecast = new JSONObject(weatherJsonStr);
        JSONArray days = forecast.getJSONArray("list");
        JSONObject day = days.get(dayIndex);
        JSONObject temps = day.get("temp");
        return temps.get("max");
	}
I'm using the Udacity IDE because I'm lazy, and it's giving me a few errors about incompatible types. The first is on the open paren in JSONObject day = days.get(dayIndex);. The message says that a JSONObject is required, but it found an Object. I don't understand why it's looking for a JSONObject, when the documentation says that the .get method of JSONArray takes an int.

It's not complaining about the parameter it's complaining about the return type. Use the documentation to check what the things you're calling return. You have to cast day to a JSONObject, it doesn't get returned as one.

Adbot
ADBOT LOVES YOU

hooah
Feb 6, 2006
WTF?

Uncomfortable Gaze posted:

The JSONObject/JSONArray get() methods return the item you want, but since Java is type-erasing it's a generic Object and you'll have to cast it. The way better thing to do is call days.getJSONObject() since that will do the cast internally. This applies to every type in the JSONObject/Array, you have getInt/getFloat/getString/ect.

Also, give Android Studio a shot when you have a chance, it's based on the really nice IntelliJ IDE and is pretty well integrated now.

Ok, I guess I kinda glossed over the Object thing and assumed that meant JSONObject.

I'm using Android Studio for the app, this is just an exercise, so by "I'm lazy" I meant "I don't feel like figuring out right now how to set up a dummy class", since they just provide that in the online IDE.

  • 1
  • 2
  • 3
  • 4
  • 5
  • Post
  • Reply