I'm thinking about making my first android app, It'd be about movies, I found an excellent data source, it is "http://www.google.com/movies?" but I wanted to know how could I extract this information and put it in my app,
I've searched but I don't know which is the optimal way to do this? does google have an API for this? is that what I want? is it better with the source code?what could I read or see to learn to do this?
thanks a lot guys, Is my first time as well programming retrieving information from the cloud,
cheers
Yup. Here is one way to do it.
First, you need to find the source of the SQL. The Yahoo Developer Console is a great place to look for this sort of stuff. It has EVERYTHING. The way these resources work is that you have a long link, like this....
developer.yahoo.com/blah/this . . . &q=KEYWORD_HERE+blah/ . . .
To access the information you are looking for, you stick whatever the correct keyword is where "KEYWORD_HERE" is, and the link will give you info in SQL format. I'll be doing the example as a stocks app.
First you create an Activity and define both sides of your link as strings. It'll look a bit like this:
public class InfoActivity extends Activity {
String firstHalf = "http://query.yahooapis.com/v1/public/blahblahblah&q=";
String secondHalf = "+blah/blah&blah . . . ";
Then, in your onCreate, you'll need to start an aSync task to do the actual pulling and parsing:
protected void onCreate(Bundle bundle) {
super.onCreate(bundle);
setContentView(R.id.layout_name);
final String yqlURL = firstHalf + KEYWORD_HERE + secondHalf;
new MyAsyncTask().execute(yqlURL);
}
Then to define our MrAsyncTask:
private class MyAsyncTask extends AsyncTask<String, String, String>{
protected String doInBackground(String... args) {
try {
URL url = new URL(args[0]);
URLConnection connection;
connection = url.openConnection();
HttpURLConnection httpConnection = (HttpURLConnection)connection;
int responseCode = httpConnection.getResponseCode();
// Tests if responseCode == 200 Good Connection
if (responseCode == HttpURLConnection.HTTP_OK) {
InputStream in = httpConnection.getInputStream();
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document dom = db.parse(in);
Element docEle = dom.getDocumentElement();
NodeList nl = docEle.getElementsByTagName("nodeName1");
if (nl != null && nl.getLength() > 0) {
for (int i = 0 ; i < nl.getLength(); i++) {
//Parse the node here with getTextValue(n1, "Name of element")
//ex: String movieName = getTextValue(n1, "MovieName");
}
}
}
} catch (MalformedURLException e) {
Log.d(TAG, "MalformedURLException", e);
} catch (IOException e) {
Log.d(TAG, "IOException", e);
} catch (ParserConfigurationException e) {
Log.d(TAG, "Parser Configuration Exception", e);
} catch (SAXException e) {
Log.d(TAG, "SAX Exception", e);
}
finally {
}
return null;
}
I hope that gives you some idea of how to do this sort of thing. I'll go see if I can quickly spot a good resource on the yahoo apis to get the movie times at a certain location.
Good luck :) Let me know if you need anything clarified.
EDIT:
Looks like this is EXACTLY what you need (resource wise):
https://developer.yahoo.com/yql/console/?q=show%20tables&env=store://datatables.org/alltableswithkeys#h=select+*+from+google.igoogle.movies+where+movies%3D'68105'%3B
Check that out. Using that, your two halves of the link would be:
String firstHalf = "https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20google.igoogle.movies%20where%20movies%3D'"
String secondHalf = "'%3B&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys"
And then to get your final link, you would just do
String yqlURL = firstHalf + "ZIP CODE OF YOUR LOCATION" + secondHalf;
And you would have all of the movies playing near you returned!
Make your life a lot easier and choose the api that is right for you. Choose one of these:
http://www.programmableweb.com/news/52-movies-apis-rovi-rotten-tomatoes-and-internet-video-archive/2013/01/22
Make your decision not only based on the content, but also ease of use and documentation. Documentation is a biggy.
Good luck!
well i would rather advice you to use an TheMovieDB.com API it is simple and provides every info of movies.
Related
I'm developing an Android application for in-house of a certain company, and it needs to log the working time of employees. Therefore, the work with system time is crucial. My application badly needs to know when the user changes the system time. Big deal, you say, see this: Is there a way to detect when the user has changed the clock time on their device?
The problem is that the user may circumvent that solution by doing Force Stop of the application prior to changing the time. The application then won't receive system notification, which is brilliantly described here: https://stackoverflow.com/a/19856367/1309803
I don't mind checking that upon the next launch of the application, but how can I possibly know if the user has changed the time? I'm aware about SystemClock.elapsedRealtime(). I could figure time shift based on delta of those values provided that the user hasn't reboot the device, but this is what I'm unsure of. My application is subscribed to BOOT_COMPLETED event, but that one won't be received either while the application is in stopped state.
And, to cap it all, employees of that company are supposed to work in condition of having no network access, so I can't rely on Web servers. So is there any other possible approach?
Getting the time from the third-party servers is not reliable most of the times and some of them are paid services.
If you want to get the exact time and check with the phone whether it is correct or not, irrespective of the proper way, you can use the following simple trick to get the actual time.
private class GetActualTime extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
try {
HttpURLConnection urlConnection = null;
StringBuilder result = new StringBuilder();
try {
URL url = new URL(urls[0]);
urlConnection = (HttpURLConnection) url.openConnection();
int code = urlConnection.getResponseCode();
if (code == 200) {
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(in));
String line = "";
while ((line = bufferedReader.readLine()) != null)
result.append(line);
in.close();
}
else {
return "error on fetching";
}
return result.toString();
} catch (MalformedURLException e) {
return "malformed URL";
} catch (IOException e) {
return "io exception";
} finally {
if (urlConnection != null) {urlConnection.disconnect();
}
}
} catch (Exception e) { return "null"; }
}
#Override
protected void onPostExecute(String time) {
Calendar calendar = Calendar.getInstance();
SimpleDateFormat mdformat = new SimpleDateFormat("h:mm");
String times = mdformat.format(calendar.getTime());
try {
String areatime = time.substring(time.indexOf(String.valueOf(times)), time.indexOf(String.valueOf(times)) + 5).trim();
Toast.makeText(this, "The actual time is " + areatime, Toast.LENGTH_SHORT).show();
}
catch(IndexOutOfBoundsException e){
Toast.makeText(this, "Mobile time is not same as Internet time", Toast.LENGTH_SHORT).show();
}
}
}
}
Call the class in the onCreate();
new GetActualTime().execute("https://www.google.com/search?q=time");
So this is actually getting the time from Google. This works pretty awesomely in my projects. In order to check whether the system time is wrong, you can use this trick. Instead of depending on the time servers, you can trust Google.
As it is more sensitive in checking, even a minute ahead or lag will catch the exception. You can customise the code if you want to handle that.
Previously I've asked some questions regarding what method I should use to save some data from my app to retrieve at a later time after it's been closed/stopped. I got the answers I was looking for, I think. But since then, my efforts to implement such a feature has fallen way short. I've researched various questions I've had, for which I thought I found answers. But it seems that the answers, while maybe correct, are not a match necessarily for each other. What I mean, is they might work separately, but coming from various sources, they don't work together as a whole, and for me they don't work at all. I'm led to believe I want to use SharedPreferences. That may or may not be the case, but that has been the direction of my efforts lately.
So I'll ask this multi-part question.
How would you go about saving an array of integers(or boolean values)?
Before loading that saved array, how would I check if it exists?
How would I load the array to use its values again?
Those are the basis of my issues right now. Even at this point, as frustrated as I may be, I don't mind doing more research if someone can point me in the right direction, but everywhere I've looked seems to be missing information and I'm unable to really understand/see how to code what I want to do.
If you REALLY want to see some code, I can show you all my broken pieces at the moment (what I haven't deleted), but I don't see it doing you any good. That said, I'll answer any questions you may need to help me out.
Thanks in advance.
EDIT: The array will change very little from app version to version. It should be about 500-2000 integers or boolean values (either/or will work the same for me). The array is basically a set of flags that tells the app to do one thing or another depending on the value. The size will only change if I add or remove items between versions. For this reason, after checking if the file/array exists, I'll compare the saved array with one in the app and act accordingly.
I've had similar issues with data that has to be preserved through a reboot. I found two ways to do it.
1) Data is seldom accessed.
Store data in .../files in some format that can be easily saved/retrieved. I used JSONArrays to hold the data. mContext.getFilesDir() will get you the path, and you can simply see if your file.exists() to determine if the data exists.
You will need to create an object that will:
1) convert your data to the stored format
for(int i = 0; i < mArray.size(); i++ )
{
JSONObject jo = new JSONObject();
jo.put("THINGY", mArray[i]);
ja.put(jo);
}
2) retrieve your data from the store
String js = readFromFile(fileName);
if( !js.isEmpty() )
ja = new JSONArray( js );
for( int i = 0; i < ja.length(); i++
{
// CONVERT THIS ARRAY TO YOUR INT...
}
3) read/write files like this:
private void writeToFile(String fileName, String data)
{
try
{
FileOutputStream fOut = openFileOutput( fileName, MODE_PRIVATE );
OutputStreamWriter osw = new OutputStreamWriter(fOut);
// Log.d(TAG, "Writing output log...");
osw.write(data);
osw.flush();
osw.close();
}
catch( Exception e )
{
Log.e(TAG, "Cannot create " + fileName );
}
}
private String readFromFile(String fileName)
{
String ret = "";
try
{
InputStream inputStream = openFileInput(fileName);
if ( inputStream != null )
{
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String receiveString = "";
StringBuilder stringBuilder = new StringBuilder();
while ( (receiveString = bufferedReader.readLine()) != null )
{
stringBuilder.append(receiveString);
}
inputStream.close();
ret = stringBuilder.toString();
}
}
catch (FileNotFoundException e)
{
Log.e(TAG, "File not found: " + e.toString());
}
catch (IOException e)
{
Log.e(TAG, "Can not read file: " + e.toString());
}
return ret;
}
JSON works well in this case because there are easy methods to convert to/from strings.
2) Frequent Access
I used SQLiteDatabase. I use a Singlton and DBHelper.getInstance() to get access to it. This seems like overkill, but it is a good solution if the amount of data you are saving is increasing beyond a simple array of Integers.
A really basic (but sound) place to start is: http://www.vogella.com/tutorials/AndroidSQLite/article.html. Note his page was written for 4.3.
HTH.
How can I parse /proc/cpuinfo virtual file of my Android tablet to get information of the processor's core and clockspeed?
I don’t need all information provided by the above file; just these two bits.
Can someone please help?
It is not clear if you want this information inside your app, or just for your own use.
you can get this information on with adb:
adb shell cat /proc/cpuinfo
If you want to use this information in your app, create a simple function to return a Map<String,String>, for example,
public static Map<String, String> getCpuInfoMap() {
Map<String, String> map = new HashMap<String, String>();
try {
Scanner s = new Scanner(new File("/proc/cpuinfo"));
while (s.hasNextLine()) {
String[] vals = s.nextLine().split(": ");
if (vals.length > 1) map.put(vals[0].trim(), vals[1].trim());
}
} catch (Exception e) {Log.e("getCpuInfoMap",Log.getStackTraceString(e));}
return map;
}
Note, this will not get multiple cpus information, overwrites. Most of the values are similar anyways. or Modify to create List of CpuInfoMaps.
try,
Log.d("getCpuInfoMap test", getCpuInfoMap().toString());
I hope its not too late for an answer but, this is how i get the current frequency for a specific cpu core:
public class MainActivity extends Activity{
private static final int INSERTION_POINT = 27;
private static String getCurFrequencyFilePath(int whichCpuCore){
StringBuilder filePath = new StringBuilder("/sys/devices/system/cpu/cpu/cpufreq/scaling_cur_freq");
filePath.insert(INSERTION_POINT, whichCpuCore);
return filePath.toString();
}
public static int getCurrentFrequency(int whichCpuCore){
int curFrequency = -1;
String cpuCoreCurFreqFilePath = getCurFrequencyFilePath(whichCpuCore);
if(new File(cpuCoreCurFreqFilePath).exists()){
try {
BufferedReader br = new BufferedReader(new FileReader(new File(cpuCoreCurFreqFilePath)));
String aLine;
while ((aLine = br.readLine()) != null) {
try{
curFrequency = Integer.parseInt(aLine);
}
catch(NumberFormatException e){
Log.e(getPackageName(), e.toString());
}
}
if (br != null) {
br.close();
}
}
catch (IOException e) {
Log.e(getPackageName(), e.toString());
}
}
return curFrequency;
}
}
From here its a piece of cake, you simply call the method :-D
int core1CurrentFreq = getCurrentFrequency(1, this);
Sometimes the cores go offline, in which case the file path will not exist and -1 will be returned
NOTE. the returned value is in KHz
MHz value is core1CurrentFreq / 1e3
GHz value is core1CurrentFreq / 1e6
Some explainations on the getCurFrequencyFilePath() method since it is not all that clear.
Current frequency is usually stored in the file: scaling_cur_freq
The file path is:
"/sys/devices/system/cpu/cpu(XX)/cpufreq/scaling_cur_freq"
where (XX) is substituted for the cpu core number eg:
"/sys/devices/system/cpu/cpu2/cpufreq/scaling_cur_freq"
The INSERTION_POINT variable is nothing more than the index of (XX), the point at which we want to place the number corresponding to the cpu core
I suggest you take a look at some of the other files in the cpufreq folder, you can use them to get other information like maximum and minimum frequency, list of availables frequencies etc.
Click this
Link
and scroll down to heading 3
I may be misunderstanding what String.contains does. I am now trying to pull a specific link using Jsoup in Android. I'm trying to just get the faceBook one as an example. Ive tried a few things. this one It Seems to be outputting got it on the ones that do not contain the facebook url and leaving the facebook ones blank. How do I just get the FaceBook ones and stop the loop.
protected Void doInBackground(Void... params) {
Document doc = null;
try {
doc = Jsoup.connect("http://www.homedepot.com").get();
Elements link = doc.select("a[href]");
String stringLink = null;
for (int i = 0; i < link.size(); i++) {
stringLink = link.toString();
if (stringLink.contains("https://www.facebook.com/")){
System.out.println(stringLink+"got it");
}
else{
//System.out.println(stringLink+"not it");
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}
The following line is causing the problem:
stringLink = link.toString();
The link variable is a collection of Elements (in this case every link on the page), so by calling link.toString() you're getting the String representation of every single link on the page all at once! That means stringLink will always contain the facebook link!
Change the line to:
stringLink = link.get(i).toString();
This line gets only the link at index i on each iteration and checks whether or not it contains the facebook link.
I'm new to Android development and I will appreciate any help I can get.
I'm designing an app that at some point needs to ask user for his Friends' names in order to work with those names later on, i.e those names will be used in drop-down lists and will be displayed at a separate View.
My question is: what is the best way to efficiently store those names and then be able to get access to them for reading, editing and deleting? The amount of names will not be big (at most 20 items).
In response to the comment about adding more info:
I need a user to specify list of names (strings) that will be used in 2 different Android Activities:
1) This list of names will be used in a Spinner that is a part of an application form
2) This list of names will be used on a separate Activity designed for Manipulating (Editing and Deleting) of existing items and adding new ones.
I also need that after manipulations (editing, deleting and creating new items) with this list changes took place in Both Activities. This list should be available after user exits the app, so as I understand it should be stored somewhere in Internal Storage.
I hate when people answer a question by just posting the link to the docs, so I won't do that.
I will post the link to the docs AND provide an answer:
DOCS: http://developer.android.com/guide/topics/data/data-storage.html
(it is actually a good read, not too long, and good to know what your options are).
It looks to me you need to save an ArrayList or something, and you are saying 20 names would be the maximum amount, so I would say you have 3 viable options, which I present here, ordered in ascending order of simplicity using my humble opinion as a comparator:
1- InternalStorage
2- SharedPreferences
3- Very interesting way I just found while researching one of the options to help you, and I will definatelly use this when I need to save a small array of data...
So the steps I would recomend are: put the names in your favourite collection object (ArrayList, HashSet, etc), then refer to those examples for the methods cited above, respectivelly:
1- https://stackoverflow.com/a/22234324/367342 (YES, this a link to a answer given on this thread, I voted it up, I feel better for cheating now).
2- Save ArrayList to SharedPreferences
3- https://stackoverflow.com/a/5703738/367342 <- this
- Convert your data to a JSONObject
- Convert it to a string
- Save this string using shared preferences
- Read it later as a jsonobject
Example on 3 (untested, sorry):
//Convert the ArrayList to json:
JSONObject json = new JSONObject();
json.put("uniqueArrays", new JSONArray(items));
//Make it into a string
String myLittleJason = json.toString();
//save it to the shared preferences
PreferenceManager.getDefaultSharedPreferences(context).edit().putString("KEY_TO_THE_NAMES_OF_MY_DEAR_FRIENDS", myLittleJason).commit();
//Loading it back from the preferences
String loadedJsonString = PreferenceManager.getDefaultSharedPreferences(context).getString("KEY_TO_THE_NAMES_OF_MY_DEAR_FRIENDS", "I have no friends, this is the default string returned if the key was not found, so, jokes aside, better make this a empty JSON string");
//making it into a JSON again
JSONObject loadedJson = new JSONObject(loadedJsonString);
//Converting the Json back into a ArrayList
ArrayList items = loadedJson.optJSONArray("uniqueArrays");
I loved that JSON approach, if you like it too, upvote the original (too ;) ) https://stackoverflow.com/a/5703738/367342
If you are going to store only 20 items, maybe the best way is to write and read a file.
public void writeItems(String fileName) {
final String ls = System.getProperty("line.separator");
BufferedWriter writer = null;
try {
writer =
new BufferedWriter(new OutputStreamWriter(openFileOutput(fileName,
Context.MODE_PRIVATE)));
writer.write("Item 1" + ls);
writer.write("Item 2" + ls);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (writer != null) {
try {
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public void readItems(String fileName) {
BufferedReader br = null;
try {
br = new BufferedReader(new InputStreamReader(openFileInput(fileName)));
String line;
while ((line = input.readLine()) != null) {
//do something
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (input != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
openFileInput and openFileOutput reference : http://developer.android.com/reference/android/content/Context.html#openFileInput(java.lang.String)
You have many options but I will give you two options:
SharedPreferences
SQLLite
If it's temporary and doesn't require intense data manipulation, I would go with SharedPreferences as it's easier to setup and easy to use and recycle.