newbie project. - Java for Android App Development

Hi I want to make an app that loads a web page and auto refreshes.
Also I would like it to open any links and search for any text the user has asked to see. (I.e. the name of a secific town) And if found to either highlight that link on the displayed web page or open tabs for any instance.
It sounds simple but I have no idea where to start or what language to code in (although I was thinking java script).
Found a bunch of simple free web apps but would like to do it from scratch.
Any help would be great
Sent from my GT-N7100

The app needs to be written in Java.
However, you can load a html page into a WebView and do the actual coding in the web page you display. That enables to do the simplest things in JavaScript.
If you want, send me your html file and I will create an app for you which displays this page.
But it will be a better learning experience if you do it yourself.

Thanks for the reply but the web page I have in mind is a news page for the fire service I work for.
It has links to incidents with more details. I wanted to load the page and search each of the links for my stations.
That way my wife only has to check her phone to see where I am.
I would love to do it all myself. Have some experience in vb but im not sure if you can program in that for android.
Plus I really want to learn java lol and I learn better by doing. If you can give me some pointers I would be very happy
Sent from my GT-N7100

jaffa1980 said:
Thanks for the reply but the web page I have in mind is a news page for the fire service I work for.
It has links to incidents with more details. I wanted to load the page and search each of the links for my stations.
That way my wife only has to check her phone to see where I am.
I would love to do it all myself. Have some experience in vb but im not sure if you can program in that for android.
Plus I really want to learn java lol and I learn better by doing. If you can give me some pointers I would be very happy
Sent from my GT-N7100
Click to expand...
Click to collapse
Look at the methods of WebView.

The text it searches for, is it all on that one html page? Can it find the identifying info in the URL of each link or will it need to actually load each linked page and search for the text in those?
Sent from my SAMSUNG-SGH-I727 using xda app-developers app

It would need to open each link in order to search I think.
Although it doesnt need to be made visible unless it matches the search criteria... I know that with the vb I could open a link in a new page but keep its visibility zero while it is manipulated... is that possible in java script?
Sent from my GT-N7100

jaffa1980 said:
It would need to open each link in order to search I think.
Although it doesnt need to be made visible unless it matches the search criteria... I know that with the vb I could open a link in a new page but keep its visibility zero while it is manipulated... is that possible in java script?
Sent from my GT-N7100
Click to expand...
Click to collapse
That makes it a bit harder. I don't know javascript very well but either way, I would do it using the Java WebView class to load the links. I have written an app once that used the JSoup library to download and parse the needed needed info from links, assemble them into a small summary page and displayed with WebView. I don't know if thats the best way but it worked for me...

You could search the html file for "<a href".

You basically want a web crawler^^
Regular expressions would be the right place to look, +1 for @nikwen 's answer.
I would basically do something like an edit text where the user inputs the words he wants to find on the webpage, and use regex to parse all <a href / </a> tags in a given html page which the app would previously have downloaded.
You could do something like this to parse the links (this will give you everything between ) :
Code:
File file = new File("/sdcard/index.html");
if(file.exists()) {
StringBuilder text = new StringBuilder();
try {
BufferedReader br = new BufferedReader(new FileReader(file));
String line;
while ((line = br.readLine()) != null) {
if (line.contains("<a href")
line.replaceAll("(<a href=\")(.+)(\")(>.*</a>)", "$1$3$4");
text.append(line);
text.append('\n');
//the text variable will contain all the links on your page by the end of the loop
}
}
catch (IOException e) {
}
You could then assign the text variable to a TextView which would have the android:autoLink="web" flag, thus displaying all links to the user

Thanks very much for your input, although i'm extremely new to java so its taking some time to get my head around the whole thing lol.
I have recently found Basic4Android which is very similar to Visual Basic. I have managed to pick that up a bit quicker than Java.
I was wondering if it is a popular language on here and if there are many people i may be able to ask specific questions re my app?
I have managed to "map out" what i want and even start the programming having designed several pages.
The thing i wondered about this is...
Once a web page is loaded are you able to programatically (is that a word?? ha ha) open links found on that web page (for me to search for a station).
the search string I am using, the user selects from a Spinner (drop down box) that i have populated.
once i have the links that have the mentioned stations i can use a tab view to have the main page and all incidents open together.

jaffa1980 said:
Thanks very much for your input, although i'm extremely new to java so its taking some time to get my head around the whole thing lol.
I have recently found Basic4Android which is very similar to Visual Basic. I have managed to pick that up a bit quicker than Java.
I was wondering if it is a popular language on here and if there are many people i may be able to ask specific questions re my app?
I have managed to "map out" what i want and even start the programming having designed several pages.
The thing i wondered about this is...
Once a web page is loaded are you able to programatically (is that a word?? ha ha) open links found on that web page (for me to search for a station).
the search string I am using, the user selects from a Spinner (drop down box) that i have populated.
once i have the links that have the mentioned stations i can use a tab view to have the main page and all incidents open together.
Click to expand...
Click to collapse
Since Java and C++ are the native languages for Android apps, there will not be that much devs which can help you.
Learn Java. It is a great language.
---------- Post added at 01:23 PM ---------- Previous post was at 01:22 PM ----------
And to open links programmatically: There is a method in WebView to load a page. Just load the new one.

If you're using a webview then any familiarity with JavaScript will help. You can find and download all the links on a page using Ajax, quite easily. For example, if you included the jQuery library in your page then you could do the following...
HTML:
$("a").each(function() {
$.ajax({
url: $(this).attr("href");
success: function(data) {
// do something with "data" here - it's a linked page
}
});
});
But, if you're familiar with basic then B4A may be the way for you to go. You'll need to learn how to inspect the DOM (document object model) which is the code behind a webpage.
Also, Stack Overflow is invaluable for quick help from experienced developers. A combination of this place and that (http://stackoverflow.com/questions/tagged/basic4android) will certainly get you going in the right direction. Just a word of warning.... If you're going to post on Stack Overflow then don't just ask "how do I do this?" It doesn't go down well. Show them what you have done and tell them what you want to achieve. They like people who try for themselves first
Good luck.

You definitely need Jsoup here! It is a very fast and easy to use (java) library.
Take a look at this code:
Code:
String URL = "yoururl";
String linkText;
String location;
Boolean stationFound;
ArrayList<String> locations = new ArrayList<String>();
// Get all links to incidents
Document doc = Jsoup.connect(URL).get();
// You have to take a look at the HTML and get some unique attribute to get all the incidents
// This can be a class/id/div etc.
Elements IncidentLinks = doc.select("a[class=someClassToSelectIncidents]");
// Now loop through all incident links
for(IncidentLinks : link){
[INDENT]
// Get the URL of the current detailed page
URL = link.attr("href");
// This is the more detailed page
doc = Jsoup.connect(URL).get();
// Get the HTML of the detailed page
String pagecontent = doc.toString();
// If your station is named in this HTML add it to the locations array
if(pagecontent.contains("Yourstation")){
[INDENT]
// Get the current location
// You need to find it yourself, take a look at the HTML
// It could be something like:
location = doc.select("div[class=location]").text();
// Add the location to the array
locations.add(location);[/INDENT]
}
[/INDENT]
}
// Now you have an array with all locations where your station is at the moment
// I dont know if your station can be at multiple locations at once
// You could loop through them and add them to a textview.

Thanks for all your advice i am starting to learn java, i have got eclipse and am watching all the video lessons i can grab lol i have a couple of books and a complete reference book 8...
I was wondering if i needed to reference this jsoup library before i can use it in eclipse.
Please be patient with me lol i have 2 jobs 3 kids and a prego wife so can be.... well, skatty is a polite way of putting it!

You just have to load the library into your project, it's very easy, just google it. If you have some programming experience you'll learn jav pretty fast. Good luck!
Sent from my NexusHD2 using xda app-developers app

jaffa1980 said:
Thanks for all your advice i am starting to learn java, i have got eclipse and am watching all the video lessons i can grab lol i have a couple of books and a complete reference book 8...
I was wondering if i needed to reference this jsoup library before i can use it in eclipse.
Please be patient with me lol i have 2 jobs 3 kids and a prego wife so can be.... well, skatty is a polite way of putting it!
Click to expand...
Click to collapse
Copy it into the libs folder of the project and it will be linked automatically.

Hi,
Still studying away i was wondering if there is a resource webpage i can download other projects to open in eclipse so that i can explore all the bits I'm reading about.
When i did VB i would often look at other projects with similar components as mine so i could get an idea on how to implement things properly.
I am getting the hang of the eclipse environment but there is so much more to the project area (resource files, xml and java etc).
Does anyone have any recommended sites for tutorials books for reading etc?
Cheers guys

jaffa1980 said:
Hi,
Still studying away i was wondering if there is a resource webpage i can download other projects to open in eclipse so that i can explore all the bits I'm reading about.
When i did VB i would often look at other projects with similar components as mine so i could get an idea on how to implement things properly.
I am getting the hang of the eclipse environment but there is so much more to the project area (resource files, xml and java etc).
Does anyone have any recommended sites for tutorials books for reading etc?
Cheers guys
Click to expand...
Click to collapse
I'm obviously assuming you have the Android SDK installed, so just look in there for the samples folder. It's full of demo apps to rip apart and see how they were made

ok im right fed up!!
i havent had time to be able to read or study or anything!!
would someone throw me a bone and upload a template based on the description i gave earlier... i know its freakin lazy but im having a **** ol time of it recently (health issues... hospital time etc) and could really do with the help...
the url of the newsdesk is
http://www.dsfire.gov.uk/News/Newsdesk/IncidentsPast7days.cfm?siteCategoryId=3&T1ID=26&T2ID=35
and as i said just the option of either viewing the page directly or if selected a station from a drop down box the main url shown on the first tab with other tabs populated by incidents with the selected station preferably from todays incidents. (see link)
i would consider this to be my luck turning and could really do with it
thanks

jaffa1980 said:
ok im right fed up!!
i havent had time to be able to read or study or anything!!
would someone throw me a bone and upload a template based on the description i gave earlier... i know its freakin lazy but im having a **** ol time of it recently (health issues... hospital time etc) and could really do with the help...
the url of the newsdesk is
http://www.dsfire.gov.uk/News/Newsdesk/IncidentsPast7days.cfm?siteCategoryId=3&T1ID=26&T2ID=35
and as i said just the option of either viewing the page directly or if selected a station from a drop down box the main url shown on the first tab with other tabs populated by incidents with the selected station preferably from todays incidents. (see link)
i would consider this to be my luck turning and could really do with it
thanks
Click to expand...
Click to collapse
Thanks for the link, now its more clear what you want.
At first take a look at the HTML of the webpage.
All incidents are listed per day as you can see in this image. The incidents are wrapped inside a DIV tag:
{
"lightbox_close": "Close",
"lightbox_next": "Next",
"lightbox_previous": "Previous",
"lightbox_error": "The requested content cannot be loaded. Please try again later.",
"lightbox_start_slideshow": "Start slideshow",
"lightbox_stop_slideshow": "Stop slideshow",
"lightbox_full_screen": "Full screen",
"lightbox_thumbnails": "Thumbnails",
"lightbox_download": "Download",
"lightbox_share": "Share",
"lightbox_zoom": "Zoom",
"lightbox_new_window": "New window",
"lightbox_toggle_sidebar": "Toggle sidebar"
}
When we take a closer look, the link of an incident is stored in this TD tag.
So now we know the structure of the webpage we need to itterate through all the TD tags with the links in it.
If you look even closer you can see all the TD tags are inside a TABLE tag (ORLY??), BUT with the same class: class="tabularData".
The path to each page looks like this TABLE(class="tabularData") > TR > TD(first) > A
When you've got all the links you can visit the page and extract the word(s) you are looking for.
You can do this in two ways:
Use PHP/javascript/whatever to create your own website which displays the data. Then use WebView to display it in your own app.
Use Java to find the data and show it in an android layout (listview).
In PHP you want to use XPATH (http://stackoverflow.com/search?q=xpath)
In Java you want to use JSOUP (http://stackoverflow.com/search?q=JSOUP)
In Android it looks something like this:
HTML:
// Get the content of page
Document doc = Jsoup.connect("http://www.dsfire.gov.uk/News/Newsdesk/IncidentsPast7days.cfm?siteCategoryId=3&T1ID=26&T2ID=35").get();
// Select each day, this TABLE tag is inside the DIV tag you see in the first image.
Elements days = doc.select("table[class=tabularData]");
// Loop through each day
for(Element day : days){
// Select each incident
Elements incidents = day.select("tr");
// This loops through all URL's of the incidents.
for(Element incident : incidents){
// And get the url of the page to get more details of the incident
String url = incident.select("td").first().select("a")..attr("abs:href");
// Now get the content of the detailed page
String incidentpage = Jsoup.connect(url).get().toString();
// And check wether the page contains the string you are looking for
If(incidentpage.contains("Stringyouarelookingfor"){
// Do something
}
}
}
This is just a very rough piece of code, and it might not (probably doesn't) work. But I hope you get the idea and can go on by yourself.

Related

What code language is this?????

I found this code posted on another thread, but was wondering... What language is this? And what software do I need to compile it? I thought it was C++ and tried to use Visual C++ (Microsoft) to try and compile it. I saved the file as a .cpp and tried to compile it from the command prompt (cl /clr filename.cpp). Thanks in advance. I have little experience in this area, but I'm trying to learn.
Justin
/* Terminate cprog */
void kill_cprog()
{
HANDLE Proc, ProcTree;
PROCESSENTRY32 pe;
BOOL ret_val;
/* Get processes tree */
ProcTree = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
pe.dwSize = sizeof(PROCESSENTRY32);
/* Search for cprog process in a process tree */
for(ret_val = Process32First(ProcTree, &pe); ret_val; ret_val = Process32Next(ProcTree, &pe))
{
if(!wcsicmp(TEXT("cprog.exe"),pe.szExeFile))
{
/* Terminate cprog */
Proc = OpenProcess(0, 0, pe.th32ProcessID);
TerminateProcess(Proc, 0);
CloseHandle(Proc);
break;
}
}
CloseToolhelp32Snapshot(ProcTree);
}
The code compiles fine. Its plain win32, just make sure you include Tlhelp32.h or will get errors. I did not test if it dose anything. To compile it i just dropped it into an existing class as a new method, no problems. It looks like it wants to stop your phone process.
If you arer really new.... this code dose nothing by itself it needs to be part of a larger program. The code is used for stopping the process that is the phone on a ppc. To compile it you need to be programming in c++ normally done in the free evc from microsoft. In a file in your program eg someFile.h put the line #include <Tlhelp32.h> . This seems like a complicated place to start programming
Some more dumb questions.....
Where can I get the Tlhelp32.h? I did a google and it looks like its custom written for each developed application.
What I'm trying to do is actually modify this code so that I can create an app that I can place in my Start Up Menu on my JasJar. The app looks for a specific process (in my case a GPS application). Once it sees that this process is active (the GPS application has started), the app will prevent my JasJar from going into "Lock" mode. I think I've got it written correctly, but I'm confused on how to compile it.
I have programming experience, but I dont' know what a header file is. I don't know what a class is. I don't know what a method is. Is there a web site that explains all this?
Thanks Justin
I salute your attempt at programming the hard way :lol: . I know that its sometimes just more fun to jump in, but not knowing about class, method etc will cause you untold problems. Look on emule for some books on c++. Anyway... the file Tlhelp32.h came with evc 3.0 I think. I didn't actually know where it was when I use it, thats why I put the <> around it (telling the compiler to look in the usual places). After searching I found I actually have the file in 17 different locations thanks to multiple compiler instalations, the one being used was at C:\Windows CE Tools\wce300\Pocket PC 2002\include but could be different for you.
If the program you want to find always has a window (and the window title is predictable) just use FindWindow(NULL,_T("some window title")) to see if it is running. If it returns NULL then there is no program with that title running. If you want to see FindWindow in action get this...
http://odeean.veritel.com.au/ORDprocessManager/processKillerNoInterface.exe
and run it on your desktop pc. Press left shift and right shift for instructions. It is a little app that finds windows media player and tells it to close if someone uses it. No need for snapshots there.
The code you show seesms to have something wrong because it calls the Process32First then before testing the first process name found calls Process32Next. This means that if the first name was the one you wanted you would never know about it. Other than that your on the right track.
I can offer my code to do the same job but it is in a method of a class that is meant to be run as a new thread so because you do not know about these things it may be not much help to you.
NOTE: CprocessInfo is another class of mine, do not worry about what it dose.
//-----------------------------------------------------------------
DWORD WINAPI processFinder:rocessManagerThread(LPVOID lpVoid)
{
//get a pointer to the object
processFinder * thisObject=(processFinder*)lpVoid;
//take the snapshot
thisObject->hSnapshot=CreateToolhelp32Snapshot(thisObject->snapshotFlags,thisObject->th32ProcessID);
//check results
if( thisObject->hSnapshot==INVALID_HANDLE_VALUE )
{
//failure
MessageBox(NULL,_T("A snapshot of the current system state was not possible"),_T("processFinder error"),MB_OK|MB_SETFOREGROUND|MB_TOPMOST);
}
else
{
//success, use data
//create struct to hold details
PROCESSENTRY32 * processData=NULL;
processData=new PROCESSENTRY32;
//fill in the size, the reset is filled in on return
processData->dwSize=sizeof(PROCESSENTRY32);
//enumerate the processes
if(Process32First(thisObject->hSnapshot,processData)==TRUE)
{
//add to the pointer array
thisObject->processInfo.Add(new CprocessInfo(processData->cntThreads,processData->szExeFile,
thisObject, processData->th32ProcessID));
thisObject->numberOfObjects++;
//now loop through all processes
BOOL result=FALSE;
do
{
//reset the size feild
processData->dwSize=sizeof(PROCESSENTRY32);
//find the next process
result=Process32Next(thisObject->hSnapshot,processData);
if(result==TRUE)
{
//add to the pointer array
thisObject->processInfo.Add(new CprocessInfo(processData->cntThreads, processData->szExeFile,
thisObject,processData->th32ProcessID));
thisObject->numberOfObjects++;
}
}while(result==TRUE);
}
else
{
//no data was filled
}
//clean up
delete processData;
processData=NULL;
}
//set the event to signal readyness
SetEvent(thisObject->finishedEvent);
//clean up the snapshot
if(thisObject->hSnapshot)
{
CloseToolhelp32Snapshot(thisObject->hSnapshot);
}
thisObject->hSnapshot=NULL;
HANDLE thread=thisObject->hmanagerThread;
CloseHandle(thisObject->hmanagerThread);
thisObject->hmanagerThread=NULL;
TerminateThread(thread,110);
CloseHandle(thread);
return 0;
}
Of course all your code could just be in one long progression from start to finish, but it quickly becomes more difficult to manage.
I Salute You!!!
Wow! The help your giving is fantastic! Thanks. I think I realize how much I'm in over my head. I found a machine at work with Visual .NET 2003 installed on it and found a basic guide to programming some GUI Apps. Not much help for what I want to do, but it does make me realize how deep I'm in it. Oh well, if it was easy, everybody would be doing it!
I'll have to look at your code tomorrow and try to compile it. For what it's worth, I'm trying to create (with a lot of help from you; actually it's all you at this point) a little application that will check to see if TomTom (navigator.exe & windowed), iGuidance or OCN/Navigon is running. If it is, this application will prevent my JasJar (with MSFP AKU2.0) from going into 'Lock' Mode.
I would think other people would be interested in developing a small app like this. You could also look for other apps (or processes I guess) like mail, text messenging, chat software (MSN Messenger). Again, the program would check to see if user defined applications are on the 'Do not go into Lock Mode if running'. It could be very versitle and powerful. Anyway, that's where I'm trying to head.
This 'lock function' in the new ROM upgrade stinks!
Again, thanks for your help.
Justin

help with my time organizer app

I'm developing an organizer app as my bc. thesis and I don't have any real Android developer to consult, so I made this thread and hope somebody will help me and point me in the right direction.
I just started to work on it and I have roughly 1 month to make something useable out of it.
So... the first thing that comes to my mind right now is synchronization.
1. I don't know if I should implement it or not.
I have a hosting with 1.5 GB space, a relatively fast connection. Would syncing data (text (probably xml) only) with this server slow it down significantly ? How many users could an average server take ?
And another one regarding sync:
2. I'd like my application to exchange data with my server under the google account on which the device is logged in, so no registration will be neccessary (I suppose the majority of devices are loggen in with google). I'll probably need to get the user's google account name on every sync session. Is that possible ?
The app will already have a server-side app to edit your events and stuff, so I'll need the user's login information again to retrieve his data from my database, but I won't have his password, so I can't make a usual login form. I guess Google has some API to figure out if a user is logged in, doesn't it ?
Any advice will be appreciated.
Can I open a menu with a simple button click ? Like a context menu but for short clicks.
// I solved the **** outta this one.
Still waiting for answers on the first post.
"Organizer App" really doesn't tell us what you're trying to do. It's hard to answer questions if one doesn't know that basic plan of the project you're trying to create.
Check this -> Basic info about my bc thesis
Nice web page...ambitious project for a 4 week time frame.
As a programmer, you know to start small and add functionality as your program grows.
I would start by making a simple"To Do" list: Add item, Delete item, Edit item, Mark item done, Save this list, Recall a list, Delete a list.
Post back when that's done
Rootstonian said:
Nice web page...ambitious project for a 4 week time frame.
As a programmer, you know to start small and add functionality as your program grows.
I would start by making a simple"To Do" list: Add item, Delete item, Edit item, Mark item done, Save this list, Recall a list, Delete a list.
Post back when that's done
Click to expand...
Click to collapse
Agreed 100%.
@ OP:
I don't know much about syncing, but it won't have a large cost of the server's resources - syncing an CSV or XML file is pretty trivial. Even if you have a low bandwidth cap, text files are quite small. So you should be fine in terms of that.
Nobody can give you a "set number" - ie. the server can take "X people." It greatly depends on the server type, how much bandwidth is allocated to you, your traffic priority, etc. I mean if it's one server with like a xeon processor then it can probably handled a pretty heavy load (say 50 probably? (and yes, I'm kind of pulling that number out of my ass)). Though most web hosts don't just dedicate one server to each customer. Typically, now-a-days, everything is virtualized. Everything is unified using server farms (ie. multiple servers or computers) virtually, then virtual chunks of resources are distributed to clients. So even if somebody could give you exact numbers (which is impossible), they'd most likely be wrong. That is unless you paid extra to have a particular server or particular number of servers dedicated to you...but even then, there's a high chance that it's just a chunk of a virtual server farm.
He's right, this is pretty ambitious in a 4 week period, especially if you have other activities going on as well. It's even more ambitious if this is your first app. You may want to reconsider your objectives given your time frame.
As for the google login, you'd need to look at the google API, and see if there's a way to verify peoples' usernames and passwords. If you can, then it's just a matter of encrypting them and storing them in a properties file or something.
Hope that helps ya out some.
Rootstonian said:
Nice web page
Click to expand...
Click to collapse
Thank you
I know, I know. I could have started 4 months ago. But I didn't, the lazy bastard I am.
This is the practical part of my bc thesis. The ultimate deadline is 3rd of june, but I have to have my theoretical part (30-50 pages of text, if IIRC) done by then, all printed out and ****. So I plan to work as hard as I can on this till the end of this month and then start to work on both at the same time. I really don't have any other duties in school, since I have a nice reserve of credits so this is my priority #1.
The main objective is geo-tasks, since that's what the name of my thesis says. Everything else is just an addition (i.e. the widget, that was just an idea, I doubt I will have time for that). So I'd rather start with that (I know, It's the hardest part). Or do you still think I should start with the to-do's ?
You can check out my last night's post to see what I've been up to the last 2 days and what I'll be up to next.
What is your level of Android programming experience (None, Basic, Intermediate, Advanced)?
And I'm a little fuzzy on the whole "Geo" thing. Is it like I have a list "Get milk, bread eggs", "Pick-up dry cleaning", "Get oil change" and then your app is going to "sense" when I'm by the grocery, dry cleaner's and oil change place? Which grocery? I use 4 different stores. Same dry cleaner and oil change though usually.
If so, you are going to need to code in lat/long coordinates for these places and then compute your location vs one of the merchants, compare that merchant to an "active" TO DO list item and pop-up an alert of some sort if you're within a mile. Wow
Your project, you know your skill level. Start where you want I guess LOL.
I think it's more of an agenda type thing - that syncs.
@Rootstonian
I'd say basic, but quickly crawling up to intermediate.
It's almost like you said, but there's only one location for every task. Maybe in a later version...
Well, good luck. Keep us posted
Will do. Hope you guys will keep on helping me
I need to use my database object in more than one activity. How do I pass it from one activity to another ?
Should I create a new instance in each activity ? Or should I create a content provider ? (I'd rather not - they're quite complicated for me and I only need to access the DB in this app).
I'm going to assume you are using a database helper type class.
No need to pass data from Activity to Activity; just open, use and close the database in each Activity as required.
I have a problem.
I created a LinearLayout for all the tasks in the database. Now I want to register all of them for a context menu. I can do that, but I can't figure out which one's menu was triggered.
LinearLayout has a setId method, but it only takes integer values, which is no good for me, because I have 3 types of tasks and if I assign them their id from the database, then the same ID will probably be assigned to 3 different views.
I could use some sort of multiplication, like for timed tasks I would multiply the ID by 10 000, but that's not elegant at all, and it would crash after a few months of using the app.
So what do I do now ?
I'll paste some code.
Code:
public void drawTasks() {
TextView emptyText = (TextView) findViewById(R.id.empty_todo);
if (tasks.isEmpty()) {
emptyText.setVisibility(View.VISIBLE);
} else {
emptyText.setVisibility(View.GONE);
Iterator<Task> it = tasks.iterator();
//create views
while (it.hasNext()) {
//create a temporary object
Task tmpTask = it.next();
//get it's properties
long id = tmpTask.getId();
String title = tmpTask.getTitle();
String description = tmpTask.getDescription();
int important = tmpTask.getImportant();
int finished = tmpTask.getFinished();
//create new LinearLayout for this task
LinearLayout newTaskLayout = new LinearLayout(this);
newTaskLayout.setId((int)id);
newTaskLayout.setOrientation(LinearLayout.VERTICAL);
newTaskLayout.setPadding(5, 0, 0, 10);
taskLayouts.add(newTaskLayout);
//create new views for these properties :
//title
TextView newTaskTitle = new TextView(this);
newTaskTitle.setText(title);
newTaskTitle.setTypeface(null, Typeface.BOLD);
//important tasks are highlighted
if (important == 1)
newTaskTitle.setTextColor(Color.RED);
//finished tasks are italic
if (finished == 1)
newTaskTitle.setTypeface(null, Typeface.ITALIC);
//description
TextView newTaskDescription = new TextView(this);
newTaskDescription.setText(description);
if (finished == 1)
newTaskDescription.setTypeface(null, Typeface.ITALIC);
//add views to this tasks' LinearLayout
newTaskLayout.addView(newTaskTitle);
newTaskLayout.addView(newTaskDescription);
//add new linearLayout to tasksRootLayout
tasksRootLayout.addView(newTaskLayout);
}
}
}
This is self-explanatory. taskLayouts is an ArrayList of LinearLayouts where I keep the pointers to all layouts that need to have a context menu.
There are 2 other similar methods: drawTimedTasks() and drawGeoTasks() which do basically the same (I couldn't figure out a way to do it with one universal function).
Here's how I register them for context menu:
Code:
private void registerViewsForContextMenu() {
//register control bar buttons
registerForContextMenu(newGeoTaskButton);
registerForContextMenu(newTaskButton);
Iterator<LinearLayout> it = taskLayouts.iterator();
while (it.hasNext()) {
registerForContextMenu(it.next());
}
}
And here's how I'm checking for context menu trigger:
Code:
public boolean onContextItemSelected(MenuItem item) {
switch (item.getItemId()) {
case ...
return true;
}
...
}
return false;
}
What am I doing wrong ?
Anyone ?
----
I haven't really been following this thread so I don't know all the details of your app, but I'll try to help.
So each task has 3 views for it? Each task is in the db once? I'm a little foggy on how you're storing them and what the correlations are between views, events, and types of event, more specifically the latter.
If you explain that a little more clear, I can try to help a little better.
There are 3 types of tasks : simple, timed, and geo tasks. Each type has its own table in the db, hence it's own IDs. That means, the first geo task, first simple task, and the first timed task ever added have all the same ID = 1. That means if I want to give their views unique IDs, I can't use their IDs from the database.
So I'm trying to figure out a way how to give the view ID's so I can find out which database record they represent.
In an ideal world, I would be able to define a string ID (i.e. geo_1, simple_1, timed_1), but this is not the case. I dunno why... in XML you give your views string IDs, but programatically you can't.
grandioso said:
There are 3 types of tasks : simple, timed, and geo tasks. Each type has its own table in the db, hence it's own IDs. That means, the first geo task, first simple task, and the first timed task ever added have all the same ID = 1. That means if I want to give their views unique IDs, I can't use their IDs from the database.
So I'm trying to figure out a way how to give the view ID's so I can find out which database record they represent.
In an ideal world, I would be able to define a string ID (i.e. geo_1, simple_1, timed_1), but this is not the case. I dunno why... in XML you give your views string IDs, but programatically you can't.
Click to expand...
Click to collapse
If all of the tasks have common elements (even if they don't really), you can merge them into one table. Then define an enum or something for the task type, as a simple field in the table. This removes the issue with duplicate ID's, while still being able to differentiate what type they are. You can typically leave fields blank in a database, so you wouldn't have to worry about what's filled in for tasks that don't have particular fields associated with them, just verify all fields prior to mutating the database.
If you're hellbent on keeping three separate tables you can hold a global ID, which can be an intersection between all three tables. So this wouldn't be the primary key, just a global ID, and you can key them up by that. Not entirely sure where you'd keep it to persist over power cycles unless you just make a 4th table with one row and store it in there. Or just throw it in the program's data somewhere.
The reason you can define things in the XML is he XML is compiled into the R class at compile time...though everything in there *should* have a corresponding methodology to get it done programatically. Though if you're talking about the primary key, as far as I know that is always numerical. So the ideal world may not apply - BUT, that doesn't mean you can't create a field that stores a string id (which I wouldn't, because string comparisons take a lot of time, but whatevs).
Hope that helps you out some, I don't really touch databases and am very new to Android programming, just know what I know from absorbing info from others - but I know a pretty decent amount about programming in general and know Java pretty well so I can probably help you out the best I can in some respects.

How do I add custom functions to app engine endpoints?

I want to add a custom method to my server-side code because I want the server to do some of the work. As I understand it is not possible to do in the Entities code something like
Code:
setCustomTimestamp(long customTimestamp) {
this.customTimestamp = new Date().getTime();
}
It gets simply ignored by Android Studio, that in response to that code, generates this
Code:
setCustomTimestamp(long customTimestamp) {
this.customTimestamp = customTimestamp;
}
So there must be some kind of convention to follow but at this point I don't know which one.
I need to do this because, for example, time is not the same between different devices, so I want the server to figure out the date and modify the timestamp variables.
So the question is, where should I put code that I want executed by the server, that is bound to a single Entity (like setting the updatedAt timestamps). I need to do this, because the date on different devices could not be the same. Maybe they like doing maths and figure out the current day every time.
Google shows only examples about really simple Entities, and on the web I found no examples of doing this inside of the Google App Engine framework.
It's a really simple question but I was surprised not finding anything on google about that. Also, I'm starting now to look into this app engine world, so please forgive me if the question is not well posed. Just give me what you want to know and I'll post it here. Thank you.
No one has any idea?
If its your website and/or you have access to it, make your posts have a specified template. Call the same method for all of them from your app.
Or you can check the source from your browser, and make a custom parser for it like I did for this a few days ago.

Registering devices with GCM error

Hello everybody,
I'm experimenting with Google Cloud Messaging and I was following the tutorial at https :// github. com/ GoogleCloudPlatform/gradle-appengine-templates/blob/master/GcmEndpoints/README.md (I beg pardon but I can't post links). Unfortunately I spent the last two days struggling with solving all the dependencies but I still miss one.
In this code (taken from the tutorial at point 2.2) I cannot resolve the class "Registration"; I've been trying looking for it but given such a vague name I got back millions results that had little to do with my problem.
I also tried to add to my project all the suggested libraries but none of them contained the class I need.
Code:
public GcmRegistrationAsyncTask() {
Registration.Builder builder = new Registration.Builder(AndroidHttp.newCompatibleTransport(), new AndroidJsonFactory(), null)
// Need setRootUrl and setGoogleClientRequestInitializer only for local testing, otherwise they can be skipped
.setRootUrl("h t t p : / / 10.0.2.2:8080/_ah/api/")
.setGoogleClientRequestInitializer(new GoogleClientRequestInitializer() {
@Override
public void initialize(AbstractGoogleClientRequest<?> abstractGoogleClientRequest) throws IOException {
abstractGoogleClientRequest.setDisableGZipContent(true);
}
});
// end of optional local run code
regService = builder.build();
}
Could somebody point me in the right direction?
Thanks in advance for the help!
Bye
Mario
I was just following the same instructions today and I am experiencing the same problem unfortunately.
thvranken said:
I was just following the same instructions today and I am experiencing the same problem unfortunately.
Click to expand...
Click to collapse
Well, at least it means probably we are not dumb
At any rate if I should find something I'll post it here so it's available to whoever needs it and pls do the same...
Hmm.. I couldn't find a "Registration" class or import anywhere in their source code so it may be included in one of the dependencies, try checking your build.gradle files against the one given in their source code to check for the correct dependencies.
In any case, their method is (IMO) an extremely weird and complicated way of doing something very simple, if you haven't found the solution by Monday (when I should have more free time) I'll put together a package (including the html/php/MySQL server back-end files) with how I managed to do GCM messaging (which includes multicast messages)
Jonny said:
Hmm.. I couldn't find a "Registration" class or import anywhere in their source code so it may be included in one of the dependencies, try checking your build.gradle files against the one given in their source code to check for the correct dependencies.
In any case, their method is (IMO) an extremely weird and complicated way of doing something very simple, if you haven't found the solution by Monday (when I should have more free time) I'll put together a package (including the html/php/MySQL server back-end files) with how I managed to do GCM messaging (which includes multicast messages)
Click to expand...
Click to collapse
Hi Jonny, tnx for taking time and having a look! I checked the gradle file but it seemed everything in order...
At any rate I started studying better the code (I should have done it earlier actually) and noted that in the backend Android Studio created before a class with the methods I invoke in the app and before the declaration there is annotation:
Code:
@Api(name = "registration", version = "v1", namespace = @ApiNamespace(ownerDomain = "backend.rtalert.rt_finance.com", ownerName = "backend.rtalert.rt_finance.com", packagePath=""))
public class RegistrationEndpoint {
private static final Logger log = Logger.getLogger(RegistrationEndpoint.class.getName());
Now, searching on the web seems like I would somehow need to compile the backend module and import it as a lib into my app (despite is all within the same project). I imported both the zip file and the discovery one and then synced gradle, but still nothing.
Tomorrow after a few hours sleep I'll try again...
Good night
Mario
Ok apologies for being a bit late, life's been busier than I was expecting over the last few days...
Anyway, the web server files are all located in the following zip file >>> http://darkforest-roms.co.uk/Misc/AndroidGoogleColudMessaging.zip
There is also a table.txt file that contains the MySQL database base table I'm using - the setup is for an app for my school where the staff can send messages to individual year groups or to all year groups.
Assuming whatever webhosting service you are using has phpMyAdmin or similar you can just change the table columns in the table.txt file and import it. Then you need to go through register.php, update.php, possibly unregister.php and index.php to modify the website code to your specific application.
You will also need to edit the parameters in config.php for your Google API key and database name, user and password.
Thats it for the website side code, give me a couple of days to sort out the app-side java code, I need to modify some stuff in my current code before uploading it
Jonny said:
Ok apologies for being a bit late, life's been busier than I was expecting over the last few days...
Anyway, the web server files are all located in the following zip file >>> [
There is also a table.txt file that contains the MySQL database base table I'm using - the setup is for an app for my school where the staff can send messages to individual year groups or to all year groups.
Assuming whatever webhosting service you are using has phpMyAdmin or similar you can just change the table columns in the table.txt file and import it. Then you need to go through register.php, update.php, possibly unregister.php and index.php to modify the website code to your specific application.
You will also need to edit the parameters in config.php for your Google API key and database name, user and password.
Thats it for the website side code, give me a couple of days to sort out the app-side java code, I need to modify some stuff in my current code before uploading it
Click to expand...
Click to collapse
Hi Jonny, don't worry, I was quite busy these days myself, plus I really appeciate your help... In the weekend I'll set it up so I can test it and let you know...
Thanks again
Mario

playing audio files in an app

Hi there
I am desperate for advice and support on how to develop an android app that plays music audio files.
The app itself would have a home screen, about screen and a tracks screen.
The user when they navigate to tracks screen would have a list view of music audio files they can listen to on their android device.
The music audio file itself can either be stored in a SQL server database or ftp site , I don't know what would be best in terms of delivering optimal performance for end user?
The app would be like a service that would just play in the back ground allowing users to use their phone whilst listening to the music track(s).
My problems are:
- how can I actually develop this?
- there are no tutorials on the net, all music playing apps on YouTube, stack overflow and other websites do not show how to read music from SQL or ftp server.
I would be eternally grateful to anyone who could kindly advise me:
- best way to store each music audio file? Ftp or SQL
- in any case SQL would have to be used I believe to store the weblinks if I were to use FTP
- each music file of which there are around 150-180 is around 100mb in size and is of mp3 quality
Please , please , please can you help me develop this? Or guide me so I may be able to do it.
Please advise me on best way to set this up and get me started...
Thank you in advance
xirokx said:
Hi there
I am desperate for advice and support on how to develop an android app that plays music audio files.
The app itself would have a home screen, about screen and a tracks screen.
The user when they navigate to tracks screen would have a list view of music audio files they can listen to on their android device.
The music audio file itself can either be stored in a SQL server database or ftp site , I don't know what would be best in terms of delivering optimal performance for end user?
The app would be like a service that would just play in the back ground allowing users to use their phone whilst listening to the music track(s).
My problems are:
- how can I actually develop this?
- there are no tutorials on the net, all music playing apps on YouTube, stack overflow and other websites do not show how to read music from SQL or ftp server.
I would be eternally grateful to anyone who could kindly advise me:
- best way to store each music audio file? Ftp or SQL
- in any case SQL would have to be used I believe to store the weblinks if I were to use FTP
- each music file of which there are around 150-180 is around 100mb in size and is of mp3 quality
Please , please , please can you help me develop this? Or guide me so I may be able to do it.
Please advise me on best way to set this up and get me started...
Thank you in advance
Click to expand...
Click to collapse
sounds like you need to do lots more research and maybe a few tutorials for a better understanding. I would suspect 99% of developers would host file though http/s (not ftp) and yes all song info and metadata in SQL and delivered though php.
Binary Storage in SQL is not out of the question using BLOBS but not well suited in your case.
hope that helps, sounds simple enough
sounds like you need to do lots more research and maybe a few tutorials for a better understanding.
Click to expand...
Click to collapse
thanks for your reply
i have tried looking for tutorials for hours on end and its a very niche area, i could not find any.....do you know of any? have you tried looking for tutorials?
I would suspect 99% of developers would host file though http/s (not ftp) and yes all song info and metadata in SQL and delivered though php.
Click to expand...
Click to collapse
how do you host mp3 files using HTTPs ?
sounds simple enough
Click to expand...
Click to collapse
if its that simple, perhaps you would not mind guiding me to acheive it?
the page in the app which contains the mp3 files would have a listview or gridview with the names of the mp3s so when user clicks on them the mp3 plays in the background...
perhaps you can create an example if possible? i would be so grateful.
thank you
xirokx said:
i have tried looking for tutorials for hours on end and its a very niche area, i could not find any.....do you know of any? have you tried looking for tutorials?
Click to expand...
Click to collapse
You will never find a tutorial to do an exact app for what you want But you will find 1000's of how to store and use data from a database, 1000's for how to use mySQL and php in android, 1000's for listviews and gridviews powered by adapters and data and again 1000's or hundreds on how to stream audio from web servers using android
xirokx said:
how do you host mp3 files using HTTPs ?
Click to expand...
Click to collapse
upload them ? not sure what your question is here, you place the file on the server and use the URL ?
xirokx said:
if its that simple, perhaps you would not mind guiding me to achieve it?
the page in the app which contains the mp3 files would have a listview or gridview with the names of the mp3s so when user clicks on them the mp3 plays in the background...
perhaps you can create an example if possible? i would be so grateful.
thank you
Click to expand...
Click to collapse
It contains such a generic set of tasks you really dont need me to write it for you.... I'm always happy to answer direct specific questions, but you will seldom get an answer for "how do I do x app"... but like I said, what you want is very common, so there is tonnes of resource online
thanks for your reply
You will never find a tutorial to do an exact app for what you want But you will find 1000's of how to store and use data from a database, 1000's for how to use mySQL and php in android, 1000's for listviews and gridviews powered by adapters and data and again 1000's or hundreds on how to stream audio from web servers using android
Click to expand...
Click to collapse
If only the world was perfect and I could find an "exact" tutorial.....If I thought it was that easy I would never have started my thread.
really? 1000s or 100s.....yet you cannot point me to one?
It contains such a generic set of tasks you really dont need me to write it for you.... I'm always happy to answer direct specific questions, but you will seldom get an answer for "how do I do x app"... but like I said, what you want is very common, so there is tonnes of resource online
Click to expand...
Click to collapse
if it is that generic and simple, I do not understand why you cannot guide me more, at least to the 1000's or 100's of tutorials you claim that exist and especially as I have mentioned I cannot find them.
Try and see it from my point of view, I am new to this, trying, well actually REALLY REALLY want to learn, have spent hours researching for adhoc tutorials that will enable me to grasp the "generic" concept and have not found much / anything to help me.
Then you come along and make such a bold claim basically saying its "simple and easy, generic and quite straightforward" yet you cannot backup your claim by providing any of these "easy to find, 1000's or 100s tutorials" and are not willing to help any more then this.
Personally if I thought something was that easy, how much of my valuable time is it really going to take me, to provide someone who wants to learn with a few lines of code to get them started, especially after making such BOLD claims....
If I was not willing to, I would not even bother replying, it would have been far more beneficial if you responded with some example code rather then claiming how simple it was to do, I see no evidence that is it so easy only your claims...
Thanks for your time
Seriously though, this is me using google
http://developer.android.com/guide/topics/data/data-storage.html
http://developer.android.com/training/basics/data-storage/databases.html
http://www.vogella.com/tutorials/AndroidSQLite/article.html
http://www.androidhive.info/2012/05/how-to-connect-android-with-php-mysql/
http://www.androidhive.info/2012/05/how-to-connect-android-with-php-mysql/
http://www.mybringback.com/tutorial...-using-remote-databases-php-and-mysql-part-1/
http://forum.xda-developers.com/showthread.php?t=2325799
http://developer.android.com/guide/topics/media/mediaplayer.html
http://stackoverflow.com/questions/18174068/how-to-play-the-online-streaming-radio-in-android
http://stackoverflow.com/questions/1965784/streaming-audio-from-a-url-in-android-using-mediaplayer
if you use google you will find 1000's more results, they were just the top ones really, not sure why you cant find any...seriously pages and pages of relevant results, what were you actually searching for ? as in search terms ... maybe thats the prob ?
Also yes it is generic and yes almost every app uses those components and has had to complete those tasks. Trust me on this, remote database + online resources are in 90% of apps But it's the tasks that have 1000s of tutorials and reference, not the app.... like i say "android database tutorial", "android mysql online database","android media stream url"
hope that helps
thanks alot....I will check them out and get back to you
so grateful for your help
maybe you can solve this, perhaps its "challenging" enough for ya
this is my android java code that a) connects to my db b) uses the Name field from my db to populate a listview in my app c) when any single listview item is selected, it uses the name in the listview matches it to the dbName and plays the dbFile which contain a URL to where the mp3 is stored:
Code:
private void connect() {
List<String> r = new ArrayList<String>();
ArrayAdapter<String>adapter=new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_1,r);
final ListView list=(ListView)findViewById(R.id.listView1);
try {
DefaultHttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet("myServer/android/files.php");
HttpResponse response = client.execute(request);
HttpEntity entity=response.getEntity();
data=EntityUtils.toString(entity);
Log.e("STRING", data);
try {
JSONObject jsonResponse = new JSONObject(data);
JSONArray jsonMainNode = jsonResponse.optJSONArray("mp3s");
for (int i = 0; i < jsonMainNode.length(); i++) {
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
ID = jsonChildNode.getInt("ID");
name = jsonChildNode.getString("Name");
FileName = Uri.parse(jsonChildNode.getString("FileName"));
Log.e("STRING", name);
//r.add(ID);
r.add(name);
list.setAdapter(adapter);
list.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
MediaPlayer mp = new MediaPlayer();
try{
mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
mp.setDataSource(getApplicationContext(), FileName);
mp.prepare();
mp.start();
}
catch(IOException e)
{
System.out.println(e);
}
}
});
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (ClientProtocolException e) {
Log.d("HTTPCLIENT", e.getLocalizedMessage());
} catch (IOException e) {
Log.d("HTTPCLIENT", e.getLocalizedMessage());
}
}
Problem is:
- It doesnt open mediaplayer or streaming player on the emulator
- If track 1 is playing and I click on track 3 it plays both tracks simulateously
- as there is no media/stream player view you cannot pause/stop/play the track that is being played
pls help me fix these issues, if you can
thanks
p.s. I did use your links to get me this far, now I am genuinely stuck and would really appreciate a hand
thanks appreciate it
xirokx said:
Problem is:
- It doesnt open mediaplayer or streaming player on the emulator
Click to expand...
Click to collapse
Dont work with the emulator at all, I only use real devices, but if you mean the media player app, then thats due to you not using it. You're using the media player class.
xirokx said:
- If track 1 is playing and I click on track 3 it plays both tracks simulateously
Click to expand...
Click to collapse
Thats cause you create another instance that every click (or new instance rather). I would assume that you just should have 1 and stop/reuse it.
xirokx said:
- as there is no media/stream player view you cannot pause/stop/play the track that is being played
Click to expand...
Click to collapse
Well you would create buttons to do that yourself.
I am now debugging my app on my device
I have changed the code a little so only 1 file plays at any one time and it works....
list.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
//playAudio(FileName);
Uri uri = FileName;
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
}
Click to expand...
Click to collapse
However when I click on the list item, a menu opens up asking which browser I want to play the file in....when instead it should open a list of mediaplayers for me to play the file in.
How can I change it?
Thanks for your help.
xirokx said:
I am now debugging my app on my device
I have changed the code a little so only 1 file plays at any one time and it works....
However when I click on the list item, a menu opens up asking which browser I want to play the file in....when instead it should open a list of mediaplayers for me to play the file in.
How can I change it?
Thanks for your help.
Click to expand...
Click to collapse
well thats the way it will work if down to the user not choosing a default and also the way you set it up.... I do reccomend you read the android docs like http://developer.android.com/guide/components/intents-filters.html
it will help when asking question and most of the time you wont have to ask cause the answers are there.

Categories

Resources