-1

I need a bit of help phrased in easy to understand terms. I've tried asking this question on multiple forums, but keep getting answers back that assume some knowledge even though I specified that I have only rudimentary skills in Android building and Java.

The user Skynet was very helpful when I asked my initial question here, but the research he/she prompted me to do proved difficult to follow up on. https://stackoverflow.com/questions/28403243/how-to-make-an-app-that-syncs-via-internet

I want to make an app with a textview that updates via internet everytime the user open the app.

What is the best way to do this? And what would I have to do to do it?

Thank you in advance!

To get an idea of how new to this I am, here's an app I've published: https://play.google.com/store/apps/details?id=theveshtheva.debatebreaker

EDIT: I'm trying something but it doesn't seem to work. Could someone tell me what I'm doing wrong?

The webpage I'm trying to pull data from is here: http://ktjdaily.blogspot.com/2015/02/menu-of-day.html

Here's my activity java file:

package theveshtheva.practice;

import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import android.widget.TextView;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.protocol.BasicHttpContext;
import org.apache.http.protocol.HttpContext;


public class onlinetext extends ActionBarActivity {


    private String HTML;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_onlinetext);

        /*FROM HERE*/
        TextView outtext = (TextView) findViewById(R.id.textView);

        try {
            getHTML();
        } catch (Exception e) {
            e.printStackTrace();
        }
        outtext.setText("" + HTML);
        /*TO HERE*/
    }

    private void getHTML() throws IOException

    {
        HttpClient httpClient = new DefaultHttpClient();
        HttpContext localContext = new BasicHttpContext();
        HttpGet httpGet = new HttpGet("http://ktjdaily.blogspot.com/2015/02/menu-of-day.html"); //URL!
        HttpResponse response = httpClient.execute(httpGet, localContext);
        String result = "";

        BufferedReader reader = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));

        String line;
        while ((line = reader.readLine()) != null) {
            result += line + "\n";
            HTML = result;
        }

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_onlinetext, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}

And here's the Manifest file, where I've set permissions:

<?xml version="1.0" encoding="utf-8" ?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="theveshtheva.practice">

  <uses-permission android:name="android.permission.INTERNET" />

  <application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme">
    <activity android:name=".onlinetext" android:label="@string/app_name">
      <intent-filter>
        <action android:name="android.intent.action.MAIN" />

        <category android:name="android.intent.category.LAUNCHER" />
      </intent-filter>
    </activity>
  </application>

</manifest>
Community
  • 1
  • 1
Thev
  • 1,105
  • 2
  • 13
  • 24

2 Answers2

0

There are HTTP apis already in Android that do this. There's like an Earthquake monitor sample application that pulls XML via HTTP in a background service.

Start there.

0

I feel like there is a lot of questions on how to sync android apps with online services or backend systems in general. So basically, I will try to expose here some ways you may have of doing so and I will try to keep it as simple as possible:

1)The world outside your mobile application

Ok, so you want to make an app that sends and retrieves information from through the internet...fine! But first of all, before even thinking about your app, have you thought about your server? the online service that holds the info your app should manipulate? So, yes! Your server/service should be ready and working when you start to think about writing an application that will do any online sync. By the way, a reasonable advice would be to start facing the term "application" as your whole service environment , including mobile apps and everything, not just one single mobile application per say.

If you have your own online service good to go or you just need to use 3rd party online services that are also ready, then that's the end of step 1.

2)Communicating with the outside world

Here you already have your functional online service. Now you need to set ways of communicating with it. Think as the "communication part" as a different project. Don't think it as just a bridge between your mobile app and your backend system. Think it as a bridge for any application from any environment to your system. A unique way that apps can reach your system and your system can reach them, exchanging valuable information for what they concern. We have some options here, but I will stick with the RESTApi. I won't describe here what is a RESTApi and how you actually write code around it(I guess that must be one of your biggest concerns), because someone already did in this epic SO question.

What you really need to understand here is the whole concept and then later you can checkout some frameworks(there are a lot) to actually implement it(you'll see that is the easiest part). To end the step 2, here is a REALLY simple diagram to show it (not the best, I know): simple communication flux

3) Finally, your android app

As using RESTApi , we're going to handle http requests. In order to do so, we have many ways of doing it in our android application. I will provide some code using the built-in HttpClient for better understanding : RestClient.java . This class is a real basic rest client that will do POST and GET http requests by just:

 RestClient client = new RestClient();
 client.execute("http://youronlineservice.com:3430/api/somegetrequest",RequestMethod.GET);
 client.execute("http://youronlineservice.com:3430/api/somepostrequest",RequestMethod.POST);

Now, when dealing with the android environment, be careful with NetworkOnMainThreadException:

The exception that is thrown when an application attempts to perform a networking operation on its main thread.

Therefore, I strong recommend the use of AsyncTask when dealing with simple http requests, because:

AsyncTask enables proper and easy use of the UI thread. This class allows to perform background operations and publish results on the UI thread without having to manipulate threads and/or handlers.

AsyncTask is designed to be a helper class around Thread and Handler and does not constitute a generic threading framework. AsyncTasks should ideally be used for short operations (a few seconds at the most.) If you need to keep threads running for long periods of time, it is highly recommended you use the various APIs provided by the java.util.concurrent package such as Executor, ThreadPoolExecutor and FutureTask.

An asynchronous task is defined by a computation that runs on a background thread and whose result is published on the UI thread. An asynchronous task is defined by 3 generic types, called Params, Progress and Result, and 4 steps, called onPreExecute, doInBackground, onProgressUpdate and onPostExecute.

For ending, as you may be wondering, when you do a http request for your api you have to handle the response that will come. As you will figure out, there will be various types you can treat responses depending on the format you designed your api to work.

Mainly, you'll probably work with XML or JSON. But don't worry! There are plenty of stuff on how working with these formats in your android applications, including some awesome frameworks that you better discover yourself to see what fits you best.

After you're done with this, you may want to check some other stuff to increase the sync experience in your app, such as:

http://developer.android.com/training/sync-adapters/creating-sync-adapter.html

http://developer.android.com/reference/android/app/Service.html

And keep in mind that the best references you can get are here: http://developer.android.com/training/index.html

Hope it can help you and others!

Community
  • 1
  • 1
vinitius
  • 3,212
  • 2
  • 17
  • 22