How to display a message/toast if JSON response is null - android

I'm searching an api from an android app and I would like to display a Toast/error message to the user when the search returns no results from the api.
When the api returns no results the following is displayed to the logs:
{boards: null}
This is where I would like to display a message/toast.
I have tried:
if (name.equals ("null");
also many other 'solutions' that i've found, but none seem to work.
please see code below:
public class apitestsearch extends AppCompatActivity {
EditText boardName;
TextView resultView;
public void findBoard (View view){
// Log.i("board", boardName.getText().toString());
InputMethodManager mgr = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
mgr.hideSoftInputFromWindow(boardName.getWindowToken(), 0);
DownloadTask task = new DownloadTask();
task.execute("https://www.api.com/airquality/api/json.php?boardID="+ boardName.getText().toString());
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_apitestsearch);
boardName = (EditText)findViewById(R.id.boardName);
resultView = (TextView) findViewById(R.id.resultView);
}
public class DownloadTask extends AsyncTask<String, Void, String>{
#Override
protected String doInBackground(String... urls) {
String result = "";
URL url;
HttpURLConnection urlConnection = null;
try {
url = new URL(urls[0]);
urlConnection = (HttpURLConnection) url.openConnection();
InputStream in = urlConnection.getInputStream();
InputStreamReader reader = new InputStreamReader(in);
int data = reader.read();
while (data != -1)
{
char current = (char) data;
result += current;
data = reader.read();
}
return result;
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "No results found", Toast.LENGTH_SHORT);
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
try {
String message = " ";
JSONObject jsonObject = new JSONObject(result);
String board = jsonObject.getString("boards");
// Log.i("boardID", board);
JSONArray arr = new JSONArray(board);
for(int i = 0; i < 1; i++)
{
JSONObject jsonPart = arr.getJSONObject(i);
String name = "";
name = jsonPart.getString("boardID");
if(name != ""){
message += name + "\r\n";
}
}
if (message != "") {
resultView.setText(message);
}
} catch (JSONException e) {
Toast.makeText(getApplicationContext(), "No results found", Toast.LENGTH_SHORT);
}
// Log.i("Content", result);
}
}
}

You can try this.
if(jsonObject.isNull("boards")){
// null handling goes here..
}else{
String board = jsonObject.getString("boards");
}
and if you want to use board as globally then
String board;
if(jsonObject.isNull("boards")){
// null handling goes here..
}else{
board = jsonObject.getString("boards");
}
and more short
String board;
if(!jsonObject.isNull("boards")){
board = jsonObject.getString("boards");
}

String board = "Not available";
//null check
if(!jsonObject.isNull("boards")){
board = jsonObject.getString("boards");
}else{
// your toast
Toast.makeText(context, "Board " + board, Toast.LENGTH_SHORT).show();
}

Related

Text in textview is not showing strings from java file - openweathermap

I am trying to use openweathermap to get basic data about weather and paste it into textview, but strings to which I am getting data doesn't refresh texts in textviews.
Code:
#SuppressLint("StaticFieldLeak")
class DownloadJSON extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... strings) {
URL url;
HttpURLConnection httpURLConnection;
InputStream inputStream;
InputStreamReader inputStreamReader;
StringBuilder result = new StringBuilder();
try {
url = new URL(strings[0]);
httpURLConnection = (HttpURLConnection) url.openConnection();
inputStream = httpURLConnection.getInputStream();
inputStreamReader = new InputStreamReader(inputStream);
int data = inputStreamReader.read();
while (data != -1) {
result.append((char) data);
}
} catch (IOException e) {
e.printStackTrace();
}
return result.toString();
}
}
txtCity = findViewById(R.id.txtCity);
txtTemp = findViewById(R.id.txtTemp);
DownloadJSON downloadJSON = new DownloadJSON();
try {
String result = downloadJSON.execute(url).get();
JSONObject jsonObject = new JSONObject(result);
String temp = jsonObject.getJSONObject("main").getString("temp");
String feel_like = jsonObject.getJSONObject("main").getString("feels_like");
txtCity.setText(City);
txtValueFeelLike.setText(feel_like);
txtTemp.setText(temp);
} catch (ExecutionException | InterruptedException | JSONException e) {
e.printStackTrace();
}
}
'''
String City = "Warsaw";
String url = "http://api.openweathermap.org/data/2.5/weather?q="+City+"&units=metric&appid=eace0bd8251cf6ab043ab9858b796256";
TextView txtCity, txtValueFeelLike, txtTemp;
What am I doing wrong?
Ok, I made a change, tried to make it from the scratch again, but now with onPostExecute(). Still nothing...
public class Weather {
private static final String OPEN_WEATHER_MAP_URL =
"http://api.openweathermap.org/data/2.5/weather?q=Warsaw&units=metric&appid=eace9b6857889076855263cfdb5707c0d00";
public interface AsyncResponse {
void processFinish(String output1, String output2, String output3, String output4, String output5, String output6);
}
public static class placeIdTask extends AsyncTask<String, Void, JSONObject> {
public AsyncResponse delegate = null;//Call back interface
#Override
protected JSONObject doInBackground(String... params) {
JSONObject jsonWeather = null;
try {
jsonWeather = getWeatherJSON();
} catch (Exception e) {
Log.d("Error", "Cannot process JSON results", e);
}
return jsonWeather;
}
#Override
public void onPostExecute(JSONObject json) {
try {
if(json != null){
JSONObject details = json.getJSONArray("weather").getJSONObject(0);
JSONObject main = json.getJSONObject("main");
DateFormat df = DateFormat.getDateTimeInstance();
String city = json.getString("name").toUpperCase(Locale.US) + ", " + json.getJSONObject("sys").getString("country");
String description = details.getString("description").toUpperCase(Locale.US);
#SuppressLint("DefaultLocale") String temperature = String.format("%.2f", main.getDouble("temp"))+ "°";
String humidity = main.getString("humidity") + "%";
String pressure = main.getString("pressure") + " hPa";
String updatedOn = df.format(new Date(json.getLong("dt")*1000));
delegate.processFinish(city, description, temperature, humidity, pressure, updatedOn);
}
} catch (JSONException e) {
}
}
}
public static JSONObject getWeatherJSON() {
try {
URL url = new URL(OPEN_WEATHER_MAP_URL);
HttpURLConnection connection =
(HttpURLConnection) url.openConnection();
BufferedReader reader = new BufferedReader(
new InputStreamReader(connection.getInputStream()));
StringBuilder json = new StringBuilder(1024);
String tmp = "";
while ((tmp = reader.readLine()) != null)
json.append(tmp).append("\n");
reader.close();
JSONObject data = new JSONObject(json.toString());
// This value will be 404 if the request was not
// successful
if (data.getInt("cod") != 200) {
return null;
}
return data;
} catch (Exception e) {
return null;
}
}}
And Main Activity:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
cityField = (TextView) findViewById(R.id.city_field);
updatedField = (TextView) findViewById(R.id.updated_field);
detailsField = (TextView) findViewById(R.id.details_field);
currentTemperatureField = (TextView) findViewById(R.id.current_temperature_field);
humidity_field = (TextView) findViewById(R.id.humidity_field);
pressure_field = (TextView) findViewById(R.id.pressure_field);
Weather.placeIdTask asyncTask = new Weather.placeIdTask() {
public void processFinish(String weather_city, String weather_description, String weather_temperature, String weather_humidity, String weather_pressure, String weather_updatedOn) {
cityField.setText(weather_city);
updatedField.setText(weather_updatedOn);
detailsField.setText(weather_description);
currentTemperatureField.setText(weather_temperature);
humidity_field.setText("Humidity: " + weather_humidity);
pressure_field.setText("Pressure: " + weather_pressure);
}
};
No idea what to do now.

My UI is not updating after API call of openweather

I want to parse JSON from the Openweather API but after many iterations and debugging, my JSON string is not updating, I do not think that there is any problem still the temperatures( minTemperature and maxTemperature) and the name of the place(mPlace) is not set, also I logged the maxtemperature but the console is showing nothing please look into my code.
public class MainActivity extends AppCompatActivity {
private EditText placeText;
private Button enterPlaceButton;
private TextView minTemperature;
private TextView maxTemperature;
private TextView mPlace;
private static final String AppID ="56a5e01eba3af36a7a9b7b210a437d09";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setTitle("Weather");
placeText = findViewById(R.id.myPlaceEditText);
enterPlaceButton = findViewById(R.id.enterPlace);
minTemperature = findViewById(R.id.minTemperature);
maxTemperature = findViewById(R.id.maxTemperature);
mPlace = findViewById(R.id.mPlace);
}
#Override
protected void onResume() {
final URL[] url = {null};
enterPlaceButton.setOnClickListener(v -> {
url[0] = makeUrl(placeText.getText().toString());
placeText.setText("");
});
if (url[0] != null) {
MyAsync myAsync = new MyAsync();
myAsync.execute(url[0]);
}
super.onResume();
}
public URL makeUrl(String place) {
Uri.Builder uriBuilder = new Uri.Builder();
uriBuilder.scheme("http");
uriBuilder.authority("api.openweathermap.org/");
uriBuilder.appendPath("data");
uriBuilder.appendPath("2.5");
uriBuilder.appendPath("weather");
uriBuilder.appendQueryParameter("q",place);
uriBuilder.appendQueryParameter("appid",AppID);
try {
return new URL(uriBuilder.build().toString());
} catch (MalformedURLException e) {
Toast.makeText(MainActivity.this, "Sorry could not able to fetch the Data", Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
return null;
}
public class MyAsync extends AsyncTask<URL, Void, String> {
#Override
protected String doInBackground(URL... urls) {
StringBuilder jsonResponseBuilder = new StringBuilder();
try {
HttpURLConnection httpURLConnection = (HttpURLConnection) urls[0].openConnection();
httpURLConnection.setRequestMethod("GET");
httpURLConnection.setReadTimeout(10000);
httpURLConnection.setConnectTimeout(15000);
httpURLConnection.setDoInput(true);
httpURLConnection.setDoOutput(true);
httpURLConnection.connect();
if (httpURLConnection.getResponseCode() == 200) {
InputStreamReader inputStreamReader = new InputStreamReader(httpURLConnection.getInputStream());
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String line = bufferedReader.readLine();
while (line != null) {
jsonResponseBuilder.append(line);
line = bufferedReader.readLine();
}
httpURLConnection.disconnect();
}
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(MainActivity.this, "Sorry could not able to fetch the Data", Toast.LENGTH_SHORT).show();
}
Log.d(MyAsync.class.getName(),jsonResponseBuilder.toString());
return jsonResponseBuilder.toString();
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onPostExecute(String s) {
setDataFromJSON(s);
super.onPostExecute(s);
}
public void setDataFromJSON(String s) {
try {
JSONObject jsonObject = new JSONObject(s);
JSONObject getMainObject = jsonObject.getJSONObject("main");
String maxTemp = getMainObject.getString("temp_max");
Log.i(MainActivity.class.getName(), maxTemp);
maxTemperature.setText(maxTemp);
String minTemp = getMainObject.getString("temp_min");
minTemperature.setText(minTemp);
mPlace.setText(jsonObject.getString("name"));
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(MainActivity.this, "Sorry could not able to fetch the Data", Toast.LENGTH_SHORT).show();
}
}
}
}

arraymap is better than sparse array to memorise some data catched from a JSON file?

I had wrote a code which use a parse to catch some data from a JSON file but i don't know what kind of structure is better between the sparse array or the array map for memorise these data ?
I had used a array map but I don't know if it's too wasted on so little data data.
public class MainActivity extends AppCompatActivity {
private ProgressDialog pd;
private String TAG = MainActivity.class.getSimpleName();
public ArrayMap<Integer, ValoriDiSueg> ArrayDati = new ArrayMap<>();
Button buttonProg;
TextView textViewProg;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buttonProg = (Button) findViewById(R.id.button);
textViewProg = (TextView) findViewById(R.id.textView);
buttonProg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new JsonCLASS().execute("https://samples.openweathermap.org/data/2.5/weather?q=London,uk&appid=b6907d289e10d714a6e88b30761fae22");
}
});
}
private class JsonCLASS extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pd = new ProgressDialog(MainActivity.this);
pd.setMessage("Please wait");
pd.setCancelable(false);
pd.show();
}
#Override
protected String doInBackground(String... params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line + "\n");
Log.d("Response: ", "> " + line); //here u ll get whole response...... :-)
}
return buffer.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
The parse of these data
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
try {
JSONObject jsonObject = new JSONObject(result);
JSONArray Arr = new JSONArray(jsonObject.getString("weather"));
for (int i = 0; i < Arr.length(); i++){
JSONObject jsonPart = Arr.getJSONObject(i);
ArrayDati.put(i,new ValoriDiSueg( jsonPart.getString("main"), jsonPart.getString("description")));
//ArrayDati.put(i,new ValoriDiSueg("description : "+ jsonPart.getString("description")));
textViewProg.setText(textViewProg.getText()+"main : "+ ArrayDati.get(i).Main +"\n"+textViewProg.getText()+"description : "+ ArrayDati.get(i).Description );
}
} catch (Exception e ){
e.printStackTrace();
}
if (pd.isShowing()) {
pd.dismiss();
}
}
}
}
And I created a class:
public class ValoriDiSueg {
String Main;
String Description;
public ValoriDiSueg(String main, String description) {
this.Main = main;
this.Description = description;
}
}
any suggestions??
In simple:
If your key is int or long, you should use SparseArray, SparseLongArray as it will not boxing/un-boxing the key value when operates. Also, it provides similar classes for int/long values as long as the key is int/long.
If you key is not int nor long, such as an object or String, you should use ArrayMap instead as it will handle the conflicts of key hashes.
There are no much performance and memory usage difference between these two class as they are all requires O(log n) to search and O(n) to insert/delete (in most cases).

Null Pointer Exception - Android studio

I keep on getting a null pointer exception error. I looked through my code and I am not sure why I am getting this error. I populates when i complile the program
The error reads like this
Null pointer Exception: Attempt to invoke virtual method int java.lang.String.length() on a null object reference. Thanks in advance.
EditText enterCity;
TextView weatherView;
public void onClick (View view) {
downloadAPIInfo task = new downloadAPIInfo();
String APIKEY = "b4fabae83c89c469d7a458a230b7a267";
String website = "http://api.openweathermap.org/data/2.5/weather?q=";
String url = website + enterCity.getText().toString() + APIKEY;
task.execute(url);
Log.i("User Entry", enterCity.getText().toString());
}
public class downloadAPIInfo extends AsyncTask<String, Void, String> {
URL url;
HttpURLConnection httpURLConnection = null;
String result = "";
#Override
protected String doInBackground(String... urls) {
try {
url = new URL(urls[0]);
httpURLConnection = (HttpURLConnection) url.openConnection();
InputStream input = httpURLConnection.getInputStream();
InputStreamReader reader = new InputStreamReader(input);
int data = reader.read();
while(data != -1) {
char one = (char) data;
result += one;
data = reader.read();
}
return result;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
//Onpostexecute interacts with the UI
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
try {
String message = "";
JSONObject object = new JSONObject(result);
String weatherInfo = object.getString("weather");
Log.i("Weather content", weatherInfo);
JSONArray array = new JSONArray(weatherInfo);
for(int i = 0; i < array.length(); i++ ) {
JSONObject jsonPart = array.getJSONObject(i);
Log.i("main", jsonPart.getString("main"));
String main = "";
String description = "";
main = jsonPart.getString("main");
description = jsonPart.getString("description");
if(main != "" && description != "") {
message+= main + ":" + description + "\r\n";
}
}
if(message != "") {
weatherView.setText(message);
}
} catch (JSONException e) {
e.printStackTrace();
}
//Log.i("WebsiteContent", result);
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
enterCity = (EditText) findViewById(R.id.cityeditText);
weatherView = (TextView) findViewById(R.id.weathertextView);
}
}
The JSONArray named 'array' is null in your onPostExecute mehtod.
Most probably your weatherInfo string is null.
I suggest you post the full stacktrace for a better explanation.

AsyncTask to fetch global game scores from a server

I am new to android and am completely puzzled by AsyncTasks. I need to create a leaderboard which will pull global leaderboard scores from a server.
I have posted below the two methods that were created in the LeaderboardsFragment which are used to access and display the scores - getGlobalScores and readStream.
I am unsure of how to use these in the AsyncTask - mostly how and what parameters to pass to the AsyncTask - most of the tutorials I have been looking at do not deal with 2D arrays. Any hints would be really appreciated, I am really having trouble understanding the literature surrounding this.
package uk.ni.appidemic.whackamole;
import java.io.BufferedReader;
public class LeaderboardsFragment extends Fragment {
AssetStore AS;
private TextView TopScores;
private String[][] global_scores = new String[10][3];
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_leaderboards, container, false);
//Go and get the asset store from the activity
AS = WhackAMoleActivity.getAssetManager();
TopScores = (TextView) rootView.findViewById(R.id.leaderboards);
// Extract and display the top score text view from the preferences
displayLocalScores();
// this method is used to send a highscore to the server (name and score)
// this method may get pulled out to the gameloop as its the only place it should be used in the final game
// but this can be used for testing purposes atm (Server needs to be on)
// sendScoreGlobal("porter", 1001);
//async Get global scores from the server and display them - new thread
new AsyncOperation().execute();
...................
public void getGlobalScores() {
//gets global score in HTML format to be parsed
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
try {
URL url = new URL("http://62........./high_scores");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
readStream(con.getInputStream());
} catch (Exception e) {
e.printStackTrace();
}
}
/gets the data and stores the global scores in a 2d array
//it then displays to screen
public void readStream(InputStream in) {
BufferedReader reader = null;
try {
StringBuilder htmlIn = new StringBuilder();
StringBuilder globalScoreBuilder = new StringBuilder();
htmlIn.append("");
reader = new BufferedReader(new InputStreamReader(in));
String line = "";
while ((line = reader.readLine()) != null) {
htmlIn.append(line);
}
// String to be scanned to find the pattern.
String html = htmlIn.toString();
String regexPattern = "<td align=\"left\" style=\"padding-left:10px;\">(\\d+?)</td>|<td align=\"right\" style=\"padding-right:10px;\">(\\w+?)</td>";
// Create a Pattern object
Pattern patternObject = Pattern.compile(regexPattern);
// Now create matcher object.
Matcher matcherObject = patternObject.matcher(html);
Log.d(getActivity().getResources().getString(R.string.LOG_TAG), "Trying to find regex matches");
TopScores.append("\n");
int nextFreePointer = 0;
int rowCount = 0;
while (matcherObject.find()) {
if (matcherObject.group(1) != null) {
Log.d(getActivity().getResources().getString(R.string.LOG_TAG), "Regex match : " + matcherObject.group(1));
globalScoreBuilder.append(matcherObject.group(1) + " ");
global_scores[rowCount][nextFreePointer] = matcherObject.group(1);
nextFreePointer++;
}
if (matcherObject.group(2) != null) {
Log.d(getActivity().getResources().getString(R.string.LOG_TAG), "Regex match : " + matcherObject.group(2));
globalScoreBuilder.append(matcherObject.group(2) + " ");
global_scores[rowCount][nextFreePointer] = matcherObject.group(2);
nextFreePointer++;
}
if (nextFreePointer > 2) {
nextFreePointer = 0;
rowCount++;
}
globalScoreBuilder.append("\n");
}
StringBuilder sb = new StringBuilder();
String lineSeparator = System.getProperty("line.separator");
for (String[] row : global_scores) {
sb.append(Arrays.toString(row)).append(lineSeparator);
}
String text = sb.toString();
TopScores.append("Global Top 10 Scores\n");
TopScores.append(text);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public class AsyncOperation extends AsyncTask<String, Void, Void>{
protected void onPreExecute(){
}//end of onPreExecute
#Override
protected Void doInBackground(Void... values) {
}//doinBackground
protected void onProgressUpdate(Void... values){
}//onProgressUpdate
protected void onPostExecute(Void... result){
}//end of onPostExecute
}//end of AsyncOperation inner class
}//end of Leaderboards class
You should fetch your game score through a WebService class that extentds AsynTask. Below is my class that I am using in order to fetch remote data safely.
CODE:
public class WebServiceRestTask extends AsyncTask<HttpUriRequest, Void, Object> {
private static final String TAG = "WebServiceRestTask";
private AbstractHttpClient mClient;
private WeakReference<WebServiceRestCallback> mCallback;
private int ws_task;
public WebServiceRestTask(int ws_task) {
this(new DefaultHttpClient(), ws_task);
}
public WebServiceRestTask(AbstractHttpClient client, int task_number) {
mClient = client;
this.ws_task = task_number;
}
public interface WebServiceRestCallback {
public void onRequestSuccess(String response);
public void onRequestError(Exception error);
}
public void setResponseCallback(WebServiceRestCallback callback) {
mCallback = new WeakReference<WebServiceRestCallback>(callback);
}
#Override
protected Object doInBackground(HttpUriRequest... params) {
try {
HttpUriRequest request = params[0];
HttpResponse serverResponse = mClient.execute(request);
BasicResponseHandler handler = new BasicResponseHandler();
String response = handler.handleResponse(serverResponse);
return response + ws_task;
} catch (Exception e) {
Log.w(TAG, e);
return e;
}
}
#Override
protected void onPostExecute(Object result) {
if (mCallback != null && mCallback.get() != null) {
if (result instanceof String) {
mCallback.get().onRequestSuccess((String) result);
} else if (result instanceof Exception) {
mCallback.get().onRequestError((Exception) result);
} else {
mCallback.get().onRequestError(
new IOException("Unknown Error Contacting Host"));
}
}
}
}
Not at my workstation but think something like this should work.
public class AsyncOperation extends AsyncTask<String, Void, Void>{
private String[][] global_scores = new String[10][3];
protected void onPreExecute(){
// optionally show loading indicator
TopScores.append("\n");
}//end of onPreExecute
#Override
protected Void doInBackground(Void... values) {
try {
URL url = new URL("http://62........./high_scores");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
readStream(con.getInputStream());
} catch (Exception e) {
e.printStackTrace();
}
}//doinBackground
protected void onProgressUpdate(Void... values){
}//onProgressUpdate
protected void onPostExecute(Void... result){
// optionally hide loading indicator
StringBuilder sb = new StringBuilder();
String lineSeparator = System.getProperty("line.separator");
for (String[] row : global_scores) {
sb.append(Arrays.toString(row)).append(lineSeparator);
}
String text = sb.toString();
TopScores.append("Global Top 10 Scores\n");
TopScores.append(text);
}//end of onPostExecute
private void readStream(InputStream in) {
BufferedReader reader = null;
try {
StringBuilder htmlIn = new StringBuilder();
StringBuilder globalScoreBuilder = new StringBuilder();
htmlIn.append("");
reader = new BufferedReader(new InputStreamReader(in));
String line = "";
while ((line = reader.readLine()) != null) {
htmlIn.append(line);
}
// String to be scanned to find the pattern.
String html = htmlIn.toString();
String regexPattern = "<td align=\"left\" style=\"padding-left:10px;\">(\\d+?)</td>|<td align=\"right\" style=\"padding-right:10px;\">(\\w+?)</td>";
// Create a Pattern object
Pattern patternObject = Pattern.compile(regexPattern);
// Now create matcher object.
Matcher matcherObject = patternObject.matcher(html);
Log.d(getActivity().getResources().getString(R.string.LOG_TAG), "Trying to find regex matches");
int nextFreePointer = 0;
int rowCount = 0;
while (matcherObject.find()) {
if (matcherObject.group(1) != null) {
Log.d(getActivity().getResources().getString(R.string.LOG_TAG), "Regex match : " + matcherObject.group(1));
globalScoreBuilder.append(matcherObject.group(1) + " ");
global_scores[rowCount][nextFreePointer] = matcherObject.group(1);
nextFreePointer++;
}
if (matcherObject.group(2) != null) {
Log.d(getActivity().getResources().getString(R.string.LOG_TAG), "Regex match : " + matcherObject.group(2));
globalScoreBuilder.append(matcherObject.group(2) + " ");
global_scores[rowCount][nextFreePointer] = matcherObject.group(2);
nextFreePointer++;
}
if (nextFreePointer > 2) {
nextFreePointer = 0;
rowCount++;
}
globalScoreBuilder.append("\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}//end of AsyncOperation inner class

Categories

Resources