[Q] Java/android not understanding oop - Android Q&A, Help & Troubleshooting

Hi guys,
Im really trying to learn java but think Im getting very confused. I have a class which holds names and information, In my android program I have the user enter a load of names which then are passed as an array to my next activity. Whenever I try to create objects from each name in the array it wont do it? Ialso understand that this may be a bad way of doing this as names will change so how would I reference them. Maybe using the array[pos] to create objects... so instead of name.printweight(); I could use 1.printweight();
I really hope above is readable or understandable as to what I am trying to learn
SUDO:
Take in names of competitors
Pass array of competitors to next activity
for loop to get each competitor name entered to a string
create an object using the competitors name (e.g name.birthday)
class competitor:
dob
weight
highest score
time
I think you cant use a string name or an int to create objects but how else would I create several competitors in my class?
Im reading some books I bought and I really am struggling to make sense of all this. Please be patient with me...
Kind regards
Phil

Think I got it.....
for (int i = 0; i < numcompetitors; i++)
{
String competitorName = (String) competitorsArray;
TextView txtOutput = (TextView) findViewById(R.id.edttxtOutput);
txtOutput.append(competitorName + " ");
//create an object of this competitor
competitorsArray = new Competitor();
((Competitor) competitorsArray).average();
}

I couldn't really understand what you are having a problem with. The code you posted might be working but it really doesn't seem like a good way of doing what you are trying to do.
I'd like to help you out but first can you please explain a bit more clearly? Maybe even post your code, so that its easier for me to understand.

So... if I understood you, you need something like this:
class competitor:
dob
weight
highest score
time
Names entered:
A,B,C
Result:
A.dob, A.weight, A.highestscore, A.time
B.dob, B.weight, B.highestscore, B.time
C.dob, C.weight, C.highestscore, C.time
Right? Well, it can't be achieved using Java, it doesn't allow you to assign programatically names to variables. However, you can use a little trick based on an array:
Code:
//Remember: you have a class named "competitor" containing several variables
String[] Names= {"Uno","Dos","Tres"}; //the array passed by the other activity
competitor[] playerData=new competitor[Names.length]; //an array, to store copies of the competitor class (a copy for each name entered)
for(byte i=0;i<Names.length;i++){
playerData[i]=new competitor(); //Initializing the copy...
playerData[i].dob= //Storing data for each name entered...
playerData[i].weight=
playerData[i].highestscore=
playerData[i].time=
}
And that's all... 1st player's data will be stored in the position 0 of the array, 2nd player's data in the position 1... and so on.
BTW, instead use 2 activities, is more easy to use only an activity, changing its layout when you need a GUI's change (yep, it's possible ).

Related

how to start programming android?

Hello guys,
I've never programmed before and I wish to learn programming android apps. I really don't know how to start, what should I learn first. I need your help on how to start, your suggestions.
Thank you very much
smartuse said:
Hello guys,
I've never programmed before and I wish to learn programming android apps. I really don't know how to start, what should I learn first. I need your help on how to start, your suggestions.
Thank you very much
Click to expand...
Click to collapse
You may want to start with learning java; See here: http://mobile.tutsplus.com/tutorials/android/java-tutorial/. You may also want to learn C/C++. Take a browse around here: http://developer.android.com/guide/basics/what-is-android.html.
smartuse said:
Hello guys,
I've never programmed before and I wish to learn programming android apps. I really don't know how to start, what should I learn first. I need your help on how to start, your suggestions.
Thank you very much
Click to expand...
Click to collapse
You'll also need the android sdk and I believe eclipse is a good bit of software.
Sent from my HTC EVO 3D X515m using XDA App
Android Application Development -o'Reilly
Don't understand!
I looked at linkes you have advised, but really don't understand some things: why used paranthesys ant other signs. I mean I understand that there is a syntax but I don't understand for example why used this type of paranthesis "()" but not this type "{}".
For example, I dont clearly understand this code
public class Cat {
private String mCatName;
Cat(String name) {
mCatName=name;
}
public String getName() {
return mCatName;
};
public void setName(String strName) {
mCatName = strName;
};
}
I can't find the explanation. I need a course from the begining. What do you recommend for me, friends?
Thank you guys!
This is the Syntax: get used to it, you can't change it anyway...
PHP:
//Make a class called Cat
public class Cat {
//set up a variable, type:String, Name:mCatName
private String mCatName;
//Constructor (method which runs by default)
Cat(String name) {
mCatName=name;
}
//Public: it can be called from everwhere (even other classes or programs)
//Method name: getName.
//It simply returns the content of the variable mCatname;
public String getName() {
return mCatName;
};
//Public: it can be called from everwhere (even other classes or programs)
//Method name: setName
//It sets the variable mCatName to the value of the input variable strName
public void setName(String strName) {
mCatName = strName;
};
}
This code is a class called Cat.
It got a String which represents the Cat's name. It is set to "name" by default.
With the methods getName and setName you can either output or change the name of the Cat.
This is very basic Java. You won't learn Java in a day, just learn bit for bit.
Thanks
But tell me please, how did you started programming? What was or from which source you started first. What were your first steps?
May be it will help me, because I don't know anything in programming.
Thank you
I started with html (not a real programing language, but helpful though)
Then we did some basics in school (Pascal, basic, .net, java) and i learned PHP and more Java in my free time.
Once you learn one programing language its rather easy to switch.
Java is a good base to start with.
There are tons of tutorials on the Internet which are great for beginners. I cant recommend you a specific, i only know German ones.
I'm going to post the book that I was taught from. I can't vouch for other books, they may be better - however the person who wrote this book was a lecturer at my university and he handed out photocopies of this book as we went through the module, while the book was still being written.
It was ammended based on feedback from a number of years of students and the parts of the language and concepts they found difficult. When I went into Uni I had no programming background beyond dabbling very lightly into HTML/PHP.
The book has exercises in it, as will any other book or online guide you find, I highly recommend attempting all of them as you progress.
http://www.amazon.co.uk/Java-Just-Time-John-Latham/dp/1848900252/ref=tmm_pap_title_0
Yes, I know it costs actual money, but for a going from complete beginner -> understand Java and its concepts well enough to begin thinking about putting it on your CV, I don't think that's such a bad thing - and he's deliberately put it at a cheap price point aimed at students, it should be 3-4x that amount to bring it in line with other university textbooks that are much less helpful.
smartuse said:
But tell me please, how did you started programming? What was or from which source you started first. What were your first steps?
May be it will help me, because I don't know anything in programming.
Thank you
Click to expand...
Click to collapse
I used a book called Object First with Java, BlueJ...
BlueJ is the IDE (where you type the code in to make programs) and its free.
Java is the language, we could talk you through the code above, but its better you learn it yourself, and then you will be able to read the code above.
Look into what Object Oriented Languages are, but tbh, that Book can be found online, its not cheap but I found it rather good!
http://www.amazon.co.uk/Objects-Fir...5628/ref=sr_1_1?ie=UTF8&qid=1325806069&sr=8-1
An amazon link to the book, hope this helps!
Thanks
Thank you, guys!
I'll try to find more information about Java online. Thank you all very much!
Also, look on you tube for "the new Boston" he makes some good programming videos
Which is difference between SDK and Oracle ?
I want to know which is difference between SDK and Oracle ?
Please help me I am new here and want to start programming.

Programming question.

Hi I not sure if I'm posting this in the correct section.
Just have a quick question.
In my java android application code I have created and instance of MapView class like this:
MapView mapView = (MapView) findViewById(R.id.mapview);
What does the (MapView) do compared when you normally create an instance of a class like this:
MapView mapView = new MapView(parameters);
Thanks.
The second one is calling constructor with parameter.I am not sure ,but the first one seems like member function calling with casting .
HTC Sense 3.5, Android 2.3.5
Thanks for answering! I tried searching the web for an explanation but not easy to find.
Cheers!
Well... the first one won'k work unless you have a layout which contains a MapView called "mapview".
So first of all you should build your xml layout file.
You can use MapView mapView = new MapView(parameters) and do it all programmatically.. which is definitely harder.
Btw the "Android software development" section would be more appropriate for this question.
Just to elaborate a bit more...in Java, most of the data you work with are types of Objects. The blueprint for the type of Object is called a class. When developing a new Class, you could define this new type of Object from scratch or you could Extend an existing one.
For example, when they whipped up the MapView class, they probably decided that "you know what...MapView's are sort of like other Views (they have gravity, padding, an id, perhaps a position, a border, etc)" and decided to define a skeleton class called View which maps out the aspects that are common to all Views. They likely then made MapView extend View, overriding or adding any aspects that make MapView unique.
So, where am I going with this...back to your code snippet, there's a function called getViewById(id) that--if you look at its definition--is set to return a View. If you just tried to use the result of this function like a MapView, you would run into problems because the Java compiler would have no way of knowing under which circumstances (ie. with which ID) the returned view would actually be a MapView. In these situations where you want to tell the compiler that you want to treat an object like some other type of object, you need to cast the reference to the object. You do this by putting the type you want in parentheses and to the left of the reference you want to cast.
For example, if you made a variable of type View (View mv) and are using it to refer to something you known is a MapView ( View mv = new MapView() ), to treat it like a MapView you need to cast it ( (MapView mv).aMethodUniqueToMapView() ). Keep in mind that unless there's no way an reference to one type could contain an object of another, the compiler will allow the cast. This means that at run time there's a chance you'll get an Exception (a ClassCastException). In certain situations, this is something you'll need to handle but in this case, you're usually good to go as you know for certain the ids you assigned to your views.
Hope this didn't put you to sleep
- chris
Thank you both for answering! =)
Chris or ctttt. Your explanation did not but me to sleep, you explained just what I was asking about! I have done java for only 1 year, and just started programming for my phone, so when I saw the (MapView) casting when you created an instance of a class i just wanted to know how that worked since I haven't seen it being done before =).
Thanks so much for clearing that up =)
Cheers
Questions or Problems Should Not Be Posted in the Development Forum
Please Post in the Correct Forums
Moving to Q&A

ContentProvider actual data access

Hello all,
hope my question is not too strange - I need to know it for some security "research" i currently do
What I am looking for is the place in the source where the actual retrieving of information by the Contracts content provider is done. I know that this is deprecated but I think that it is a good start
I tried to trace the place in the source manually but I got stuck at this method:
Code:
public ContentProviderHolder getContentProvider(IApplicationThread caller,
String name) throws RemoteException
in the file
/android/frameworks/base/core/java/android/app/ActivityManagerNative.java
I started from the following code snippet:
Code:
Cursor c = getContentResolver().query(People.CONTENT_URI, null, null, null, null);
String test = People.CONTENT_URI.getPath();
txt.append(test);
I think that the ContentProvider is implemented in
/android/frameworks/base/core/java/android/provider/Contacts.java even though this class does not extends ContentProvider (I thought that each ContantProvider must extend this class).
Can someone maybe help me and tell me where to look ?
Oh jea and i have a second question. What I want to do is to redirect every Call to the contacts contentprovider to a fake content. So I thought i could implement my own contentprovider e.g. fakeContacts and redirect each call to my fake content provider (by altering the source). Is this a good idea or is their a "better" idea to perform this "lying" to the contact app ???
Thank you so much

Confused about how to evolve from (very) basic Android Development

Hello.
I followed all the New Boston Android videos, did everything, understood everything.
I tried to create a basic RSS feed reader, in order to better incorporate some concepts I learned in the New Boston videos (http processing, xml processing, adapting the content to lists, custom lists, etc). When I got to pass the information from the http processed data to xml parser and the list, that's when I got too much confused and knew I didn't have enough knowledge.
Then I tried to do some "Shopping List Manager" (just like OI Shopping, a bit adapted more to my taste), in order to learn.
However, again, when I neededto pass information to other objects in other classes or something like that, I get confused and don't know what to do.
So I bought CommonsWare book, "The Busy Coder's Guide to Android", which I have the latest version (5.1) and I'm reading, but I don't like to advance when I don't fully understand something. This time I'm stuck on the Action Bar part, more precisely this one:
Code:
private void configureActionItem(Menu menu) {
EditText add=
(EditText)menu.findItem(R.id.add).getActionView()
.findViewById(R.id.title);
add.setOnEditorActionListener(this);
}
I know this will seem very basic to many of you, but I get really confused on all this calls, returning results and more calls.
I don't have a background on OOP, except when I worked with PHP frameworks like Symfony, I work usually with direct task programming (scripting, automation, etc), as I am a Linux System Administrator, so my code is mainly scripting and web interface building (Python, Shell Script, PHP, Javascript, etc).
Can anybody explain what can I do to better understand this? It's just lack of practice and in time I'll understand better? Is it OOP lack of knowledge/practice? Or is it Java lack of knowledge/practice?
Thanks a lot for all your help.
Maybe the best approach is to get some face time with a person who is more experienced and have him explain to you the concept you have trouble with while focusing on the parts you don't grasp. A real human has this flexibility to do a "targeted strike" unlike a tutorial or a book that has no idea where in particular the student may get confused.
For this particular issue, the issue can be summarized as follows. Let's say you have an object call a function:
Code:
orange.peel();
This should be relatively straightforward. The next level of complexity is the fact that obj is just a variable representing an object, and in fact we can substitute anything else that evaluates to an object (i.e.: after it runs, you end up with an object). For example these all are legal ways to call the method as long as types match:
Code:
(new Orange()).peel();
(shouldEatSmallerOrange ? smallerOrange : largerOrange).peel();
retrieveOrangeFromBox().peel();
The last line illustrates calling some other function that returns the object, which is then used to call a second function. The final step from here is to recognize that instead of a single retrieveOrangeFromBox() we can have a chain of functions, each of which returns an object that is used to call the next function in line. For example:
Code:
findCar().accessCarTrunk().unloadBoxFromTrunk().retrieveOrangeFromBox().peel();
The names are unnecessarily verbose to illustrate how functions and their results relate to each other.
OOP + Android system
You're not that clear as to exactly what you are having a problem with, but in general, it sounds like you need to get a java book and learn the basic concepts of classes and interfaces. Since you say you have a background in PHP you could probably go pretty far just by following the Java tutorials on the Sun website. I say java because that's the target language here, any book on OOP in any language would be adequate but learning java would give you the added ability to read other people's android code examples more easily.
After that, you can learn the Android framework. You develop in the Java language but you work within the android framework. What that means is that here, for example, the action bar is provided to you by the android system, and this callback is called by the system, so it is all set up for you. But to understand what is happening, you need to understand when the system calls this method and what it does. That is the framework.
So more specifically, how can you understand this code? This method is called from another method, onCreateOptionsMenu(). OnCreateOptionsMenu() is a method in the Activity class that is called automatically by the system at a specific time. You need to read about the Activity class and the Activity lifecycle on the android developers site. If you want your activity to provide an options menu, you create it in OnCreateOptionsMenu and return it, the system will handle it from there. So back to configureActionItem(Menu menu), here you are passing in the menu object, which contains MenuItem objects, which the system uses to populate the menu (either on the action bar, or when you hit the menu button, depending on the android version). Each MenuItem object has a view that is associated with it (usually created in an XML file).
One thing that may be hard to understand is that all these calls are chained, so if you don't know what they are returning you don't know where to look for help. It's easier if you separate the calls out. Here, the documentation is your friend. If you look at the Menu class on the android dev site, you see that findItem() returns a MenuItem. So then you look up MenuItem, and you see that getActionView() returns a View. Look at the View class, and you can see findViewById() returns another view (a sub-view that is contained within this view). so when you look at it all together, unchained:
Code:
private void configureActionItem(Menu menu) {
MenuItem mi = menu.findItem(R.id.add);
View parentView = mi.getActionView();
EditText add = (EditText)parentView.findViewById(R.id.title);
}
findViewById returns a View, but you know that the view known by the id R.id.title is an EditText view, and you want to use it as an EditText, so you have to cast the View to an EditText (which is a subclass of View) so that the compiler knows that it is an EditText type of view. That's what the (EditText) is doing in front of the findViewById call. To understand that you need to read about subclassing and strongly-typed programming languages. PHP is weakly-typed, so that might be new to you.
finally, you call setOnEditActionListener on the EditText. OnEditActionListener is an interface that you have implemented in this class. An interface defines a common set of methods that are guaranteed to be present in whichever class has implemented it. So when you set the OnEditActionListener to this, (this means the current instance of this class), the EditText will hold on to the "this" object and it knows that it can call a certain set of methods on it. What are those methods? look up the OnEditActionListener interface in the docs:
it only has one method,
Code:
public abstract boolean onEditorAction (TextView v, int actionId, KeyEvent event);
so somewhere in this class, you will have this method defined and this is where you put code that you want to run when the EditText triggers this action. I assume this get called when the user touches the EditText.
It's really not going to be easy to work with android if you don't have a basic knowledge of OOP, specifically classes, inheritance, and interfaces. Also, knowing how java implements these concepts will help a lot. Then you can use your book to learn the Android framework.
GreenTuxer said:
Hello.
I followed all the New Boston Android videos, did everything, understood everything.
I tried to create a basic RSS feed reader, in order to better incorporate some concepts I learned in the New Boston videos (http processing, xml processing, adapting the content to lists, custom lists, etc). When I got to pass the information from the http processed data to xml parser and the list, that's when I got too much confused and knew I didn't have enough knowledge.
Then I tried to do some "Shopping List Manager" (just like OI Shopping, a bit adapted more to my taste), in order to learn.
However, again, when I neededto pass information to other objects in other classes or something like that, I get confused and don't know what to do.
So I bought CommonsWare book, "The Busy Coder's Guide to Android", which I have the latest version (5.1) and I'm reading, but I don't like to advance when I don't fully understand something. This time I'm stuck on the Action Bar part, more precisely this one:
Code:
private void configureActionItem(Menu menu) {
EditText add=
(EditText)menu.findItem(R.id.add).getActionView()
.findViewById(R.id.title);
add.setOnEditorActionListener(this);
}
I know this will seem very basic to many of you, but I get really confused on all this calls, returning results and more calls.
I don't have a background on OOP, except when I worked with PHP frameworks like Symfony, I work usually with direct task programming (scripting, automation, etc), as I am a Linux System Administrator, so my code is mainly scripting and web interface building (Python, Shell Script, PHP, Javascript, etc).
Can anybody explain what can I do to better understand this? It's just lack of practice and in time I'll understand better? Is it OOP lack of knowledge/practice? Or is it Java lack of knowledge/practice?
Thanks a lot for all your help.
Click to expand...
Click to collapse
Thanks a lot for your help. I also think my issue is with OOP, but I needed the opinion of people with more knowledge.
I understand very well what you said about onCreateOptionsMenu(), why and when is called, Activity class, lifecycle, etc.
Those things I understand without any problem. I also understand the basics of OOP, but I don't know almost nothing about Interfaces and I don't have almost any experience with inheritance, although I understand it.
I think I'm just confused because I haven't worked very long with OOP. I just don't know if I should invest in something like reading and testing something like Thinking in Java, or just practice more and more Android Development.

[Q] AndroidAppHelper - No context. Alternatives?

Hey all,
I was attempting to get the hooked application's context with the following code:
Context moduleContext = AndroidAppHelper.currentApplication();
if(moduleContext == null)
Log.v("App", "BOOO");
else
Log.v("App", "WE GOT APP!");
I realised that when I place this snipper in handleloadpackage, moduleContext is null, however if I place it in the beforeHookedMethod for testing, it gets an application context. Are there any other suggestions for getting application context?
You cannot retrieve the application's context if the application is not in memory. handleLoadPackage is run when the package is loaded not the application. You are able to retrieve a context in beforeHookedMethod since the application is active and in memory (and therefore has a context) by that point. If you want to load an application's context as soon as it becomes available try hooking the Application.onCreate method.
If you need a context that is not dependent on an application's lifecycle then you can attempt to retrieve a system context. I have not found any particular issues with this method but if my understanding of the Android internals is correct it could potentially open you up to a memory leak. For what it's worth I've been using this method for quite some time when I need to and have yet to notice any issues. This will not work in initZygote.
Code:
Object activityThread = XposedHelpers.callStaticMethod(XposedHelpers.findClass("android.app.ActivityThread", null), "currentActivityThread");
Context systemCtx = (Context) XposedHelpers.callMethod(activityThread, "getSystemContext");
Hi Kevin M,
Thanks, I eventually ended up using the method that you described, hooking onCreate. Managed to get the context there, thanks though! Hopefully someone will find this post and this may help them too.
Regards,
han
Kevin M said:
You cannot retrieve the application's context if the application is not in memory. handleLoadPackage is run when the package is loaded not the application. You are able to retrieve a context in beforeHookedMethod since the application is active and in memory (and therefore has a context) by that point. If you want to load an application's context as soon as it becomes available try hooking the Application.onCreate method.
If you need a context that is not dependent on an application's lifecycle then you can attempt to retrieve a system context. I have not found any particular issues with this method but if my understanding of the Android internals is correct it could potentially open you up to a memory leak. For what it's worth I've been using this method for quite some time when I need to and have yet to notice any issues. This will not work in initZygote.
Code:
Object activityThread = XposedHelpers.callStaticMethod(XposedHelpers.findClass("android.app.ActivityThread", null), "currentActivityThread");
Context systemCtx = (Context) XposedHelpers.callMethod(activityThread, "getSystemContext");
Click to expand...
Click to collapse
bahbahboom said:
Hi Kevin M,
Thanks, I eventually ended up using the method that you described, hooking onCreate. Managed to get the context there, thanks though! Hopefully someone will find this post and this may help them too.
Regards,
Han
Click to expand...
Click to collapse
I recently found it out while working with dialogs, I thought it would fit here:
If you are making use of the context from onCreate multiple times, you might receive a BadTokenException error at displaying dialogs, etc if the hooked application was launched from the background. To counter this, place a hook in onResume and get the context again.
Sent from my iPhone 6 Plus using Tapatalk

Categories

Resources