Create table rows dynamically from parsed JSON in AsyncTask in Android - android

I am kind of stuck right now.I want to create a table from parsed JSON data.The JSON is fetched from a webservice using AsyncTask on the click of a button.The fetched json is then parsed within the AsyncTask. I want to parallely create a tabular layout and show it on the user interface. I have included the AsyncTask class.
For example: My JSON is [{"Instrument":"EURCAD"},{"Entry Price","1.453"}]
The table should be like this:
|Instrument | EntryPrice|
|EURCAD | 1.453 |
Please HELP!!!
AsyncTask
package com.shubhamhpcs.fetchdb;
import android.os.AsyncTask;
import android.util.Log;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
/**
* Created by Satyam on 7/11/2016.
*/
public class FetchInstrumentTask extends AsyncTask<Void,Void,String[]> {
private final String LOG_TAG = FetchInstrumentTask.class.getSimpleName();
//To parse JSON String recieved from the server
public String[] getInstrumentDataFromJson(String forecastJsonStr)
throws JSONException {
String[] resultStrs = new String[12];
final String OWM_INSTRUMENT ="Instrument";
final String OWM_NEW_SIGNAL ="NewSignal";
final String OWM_ENTRY_TYPE ="EntryType";
final String OWM_ENTRY_PRICE ="EntryPrice";
final String OWM_TRAILING_STOP_1 ="TrailingStop1";
final String OWM_TRAILING_STOP_2 ="TrailingStop2";
final String OWM_TGT ="TGT";
final String OWM_TGT_HIT ="TGTHit";
final String OWM_P_L ="P&L";
final String OWM_STOP_LOSS ="StopLoss";
JSONArray instrumentArray = new JSONArray(forecastJsonStr);
for (int i = 0; i < instrumentArray.length(); i++) {
JSONObject instrumentObject = instrumentArray.getJSONObject(i);
String instrumentName = instrumentObject.getString(OWM_INSTRUMENT);
String newSignal = instrumentObject.getString(OWM_NEW_SIGNAL);
double EntryType = instrumentObject.getDouble(OWM_ENTRY_TYPE);
double EntryPrice = instrumentObject.getDouble(OWM_ENTRY_PRICE);
double trailingStop1 = instrumentObject.getDouble(OWM_TRAILING_STOP_1);
double trailingStop2 = instrumentObject.getDouble(OWM_TRAILING_STOP_2);
double tgt = instrumentObject.getDouble(OWM_TGT);
String tgtHit = instrumentObject.getString(OWM_TGT_HIT);
String pl = instrumentObject.getString(OWM_P_L);
String stopLoss = instrumentObject.getString(OWM_STOP_LOSS);
resultStrs[i] = instrumentName + "|" + newSignal + " | " + EntryType + " | " + EntryPrice + "|" + trailingStop1 + "|" +
trailingStop2 + "|" + tgt + "|" + tgtHit + "|" + pl + "|" + stopLoss ;
}
for (String s : resultStrs) {
Log.v(LOG_TAG, "Instrument entry: " + s);
}
return resultStrs;
}
#Override
protected String[] doInBackground(Void... voids) {
// These two need to be declared outside the try/catch
// so that they can be closed in the finally block.
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
// Will contain the raw JSON response as a string.
String instrumentJsonStr = null;
try {
URL url = new URL("http://192.168.1.101/tooth/index.php");
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
InputStream inputStream = urlConnection.getInputStream();
StringBuffer buffer = new StringBuffer();
if (inputStream == null) {
return null;
}
reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
buffer.append(line + "\n");
}
if (buffer.length() == 0) {
return null;
}
instrumentJsonStr = buffer.toString();
} catch (IOException e) {
Log.e("FetchInstrumentTask", "Error ", e);
return null;
} finally{
if (urlConnection != null) {
urlConnection.disconnect();
}
if (reader != null) {
try {
reader.close();
} catch (final IOException e) {
Log.e("Fetch", "Error closing stream", e);
}
}
}
Log.v("FetchInstrumentTask ","Data from VPS is: "+instrumentJsonStr);
try {
return getInstrumentDataFromJson(instrumentJsonStr);
} catch (JSONException e) {
Log.e(LOG_TAG, e.getMessage(), e);
e.printStackTrace();
}
return null;
}
}
MainActivity
package com.shubhamhpcs.fetchdb;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
public class Main2Activity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
}
public void getjson(View view){
FetchInstrumentTask fetchInstrumentTask =new FetchInstrumentTask();
fetchInstrumentTask.execute();
}
}

Let's make an Instrument class, that contains the instrument name and price, which is better than Strings.
Your AsyncTask would return a List of Instruments List<Instrument>, instead of String[].
Then introduce a method onPostExecute to your AsyncTask, that would provide the data to the Activity. You can for example make the activity implement an interface IInstrumentsDisplay, which would have a method void showInstruments(List<Instrument>). Then you would initialize the AsyncTask with a reference to this interface (the activity).
In this method showInstruments in the activity you would construct an adapter, for example ArrayAdapter<Instrument>, that you would initialize with the data returned by the AsyncTask, and then point your ListView (that would display the table) to this adapter.
Your activity would include a ListView in its layout xml, you also need to define an item row xml layout file, and in the adapter you would override the getView() method to display the name and price in the correct place of the row.

Try this
try {
JSONObject jsonObject=array.getJSONObject(0);
ArrayList<String> headers=getKeys(jsonObject);
TableRow row=(TableRow)((Activity)context).getLayoutInflater().inflate(R.layout.template_row, null);
//user the first row as the header
for (int i=0;i<headers.size();i++){
//TextView textView=new TextView(context);
TextView textView = (TextView)((Activity)context).getLayoutInflater().inflate(R.layout.template_text_medium, null);
textView.setText(headers.get(i));
row.addView(textView);
}
table.addView(row);
for (int j=0;j<array.length();j++){
JSONObject jObj=array.getJSONObject(j);
ArrayList<String> values=getValues(jObj);
TableRow new_row=null;
if (j==array.length()-1){
new_row =(TableRow)((Activity)context).getLayoutInflater().inflate(R.layout.template_row_last, null);
}
else {
new_row =(TableRow)((Activity)context).getLayoutInflater().inflate(R.layout.template_row, null);
}
for (int i=0;i<values.size();i++){
String value=values.get(i);
if (value.equals("null"))
value="";
TextView textView = (TextView)((Activity)context).getLayoutInflater().inflate(R.layout.template_text_medium, null);
textView.setText(value);
new_row.addView(textView);
}
table.addView(new_row);
}
} catch (JSONException e) {
e.printStackTrace();
}

Related

API call with AsyncTask

I am trying to use android studio to access a streaming/internet API. My API call works in Eclipse without using AsyncTask so I'm trying to use AsyncTask in Android Studio to call the API but I'm not sure why it's not working. The way I use the buffered reader and input stream are the same as the way I used them in eclipse when the call works. I also have permission to use internet in my AndroidManifest.xml.
Note: I took out my API key for obvious reasons.
import android.content.Intent;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.os.AsyncTask;
import android.view.View;
import android.widget.EditText;
import android.view.View.OnClickListener;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends Activity implements OnClickListener {
private static final String TAG_DEBUG = MainActivity.class.getName();
public static final String TAG_ID = "id";
public static final String TAG_CURRENTTEMP = "currenttemp";
public static final String TAG_MAXTEMP = "maxtemp";
public static final String TAG_MINTEMP = "mintemp";
private EditText enteredzip;
private String zip;
private Button button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
enteredzip = (EditText) findViewById(R.id.editText);
button = (Button) findViewById(R.id.button);
button.setOnClickListener(this);
}
public void onClick(View v) {
zip = enteredzip.getText().toString();
new RetrieveFeedTask().execute();
}
class RetrieveFeedTask extends AsyncTask<Void, Void, String> {
private Exception exception;
protected void onPreExecute() {
}
protected String doInBackground(Void... urls) {
String BASE_URL = "http://api.openweathermap.org/data/2.5/weather?zip=";
String API_CALL = "&APPID=key";
// Do some validation here
HttpURLConnection con = null;
InputStream is = null;
String bufferedOutput = "";
try {
con = (HttpURLConnection) (new URL(BASE_URL + zip + API_CALL)).openConnection();
con.setRequestMethod("GET");
con.setDoInput(true);
con.setDoOutput(true);
con.connect();
StringBuffer buffer = new StringBuffer();
is = con.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
String line = null;
while((line = br.readLine()) != null)
buffer.append(line + "\r\n");
is.close();
con.disconnect();
bufferedOutput = buffer.toString();
return bufferedOutput;
}
catch(Exception e) {
Log.e("ERROR", e.getMessage(), e);
return null;
} finally {
try{
is.close();
}catch(Throwable T){}
try{
con.disconnect();
}catch(Throwable T){}
}
}
protected void onPostExecute(String response) {
if(response == null) {
//response = "THERE WAS AN ERROR";
//Toast.makeText(MainActivity.this, getResources().getString(R.string.error_et), Toast.LENGTH_LONG).show();
return;
}
//Log.i("INFO", response);
// TODO: check this.exception
// TODO: do something with the feed
Toast.makeText(MainActivity.this, response, Toast.LENGTH_LONG).show();
String id = "";
String currenttemp = "";
String maxtemp = "";
String mintemp = "";
for (int i = 0; i < response.length(); i++) {
if (response.substring(i, i + 2).equals("id")) {
id = response.substring(i + 4, i + 7);
break;
}
}
for (int i = 0; i < response.length(); i++) {
if (response.substring(i, i + 4).equals("temp")) {
currenttemp = response.substring(i + 6, i + 9);
break;
}
}
for (int i = 0; i < response.length(); i++) {
if (response.substring(i, i + 8).equals("temp_min")) {
mintemp = response.substring(i + 10, i + 13);
break;
}
}
for (int i = 0; i < response.length(); i++) {
if (response.substring(i, i + 8).equals("temp_max")) {
maxtemp = response.substring(i + 10, i + 13);
break;
}
}
launchMain2Activity(id, currenttemp, maxtemp, mintemp);
}
}
private void launchMain2Activity(String id, String currenttemp, String maxtemp, String mintemp) {
Intent Main2Activity = new Intent(MainActivity.this, Main2Activity.class);
Main2Activity.putExtra(TAG_ID, id);
Main2Activity.putExtra(TAG_CURRENTTEMP, currenttemp);
Main2Activity.putExtra(TAG_MAXTEMP, maxtemp);
Main2Activity.putExtra(TAG_MINTEMP, mintemp);
startActivity(Main2Activity);
}
try to use this :
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8")) ;
UTF-8 is a method for encoding Unicode characters using 8-bit sequences.

App Crashes while switching from one Activity to another

Aim: Building app on Google API to fetch the data about the books the user searches
Problem Explanation:
Whenever I hit the submit Button, my app crashes.
This is my first approach in making a network request app and I need guidance.
MainActivityClass
package com.example.vidit.books;
import android.app.Activity;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText query = (EditText) findViewById(R.id.query);
Button submit= (Button) findViewById(R.id.submit);
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent= new Intent(MainActivity.this,Request.class);
intent.putExtra ( "text", query.getText().toString() );
startActivity(intent);
}
});
}
}
Second Class
package com.example.vidit.books;
import android.content.Intent;
public class Request {
Intent i = getIntent();
String text = i.getStringExtra ("text");
public static final String LOG_TAG = Request.class.getSimpleName();
String APIURL="https://www.googleapis.com/books/v1/volumes?q= " + text;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_request);
}
public void UpdateUi(Book book)
{
BookAdapter bookAdapter = new BookAdapter(this,book);
ListView listView= (ListView) findViewById(R.id.listview_all);
}
private class BookAsyncTask extends AsyncTask<URL,Void,Book>
{
#Override
protected Book doInBackground(URL... urls) {
URL url = createUrl(APIURL);
String jsonResponse = "";
try {
jsonResponse = makeHttpRequest(url);
} catch (IOException e) {
// TODO Handle the IOException
}
final Book book = extractFeatureFromJson(jsonResponse);
return book;
}
/**
* Make an HTTP request to the given URL and return a String as the response.
*/
private String makeHttpRequest(URL url) throws IOException {
String jsonResponse = "";
HttpURLConnection urlConnection = null;
InputStream inputStream = null;
try {
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setReadTimeout(10000 /* milliseconds */);
urlConnection.setConnectTimeout(15000 /* milliseconds */);
urlConnection.connect();
if(urlConnection.getResponseCode()==200) {
inputStream = urlConnection.getInputStream();
jsonResponse = readFromStream(inputStream);
}
} catch (IOException e) {
// TODO: Handle the exception
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
if (inputStream != null) {
// function must handle java.io.IOException here
inputStream.close();
}
}
return jsonResponse;
}
/**
* Convert the {#link InputStream} into a String which contains the
* whole JSON response from the server.
*/
private String readFromStream(InputStream inputStream) throws IOException {
StringBuilder output = new StringBuilder();
if (inputStream != null) {
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, Charset.forName("UTF-8"));
BufferedReader reader = new BufferedReader(inputStreamReader);
String line = reader.readLine();
while (line != null) {
output.append(line);
line = reader.readLine();
}
}
return output.toString();
}
/**
* Returns new URL object from the given string URL.
*/
private URL createUrl(String stringUrl) {
URL url = null;
try {
url = new URL(stringUrl);
} catch (MalformedURLException exception) {
Log.e(LOG_TAG, "Error with creating URL", exception);
return null;
}
return url;
}
private Book extractFeatureFromJson(String bookJSON) {
try {
JSONObject baseJsonResponse = new JSONObject(bookJSON);
JSONArray items = baseJsonResponse.getJSONArray("items");
// If there are results in the features array
for(int i=0;i<10;i++)
{
JSONObject firstFeature = items.getJSONObject(i);
JSONArray author=firstFeature.getJSONArray("author");
for(int j=0;j<author.length();j++)
{
JSONObject authorFeature=author.getJSONObject(j);
}
String title = items.getString(Integer.parseInt("title"));
// Create a new {#link Event} object
return new Book(title,author);
}
} catch (JSONException e) {
Log.e(LOG_TAG, "Problem parsing the earthquake JSON results", e);
}
return null;
}
}
}
BookAdapter Class:
package com.example.vidit.books;
import android.app.Activity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import java.util.List;
public class BookAdapter extends ArrayAdapter<Book> {
public BookAdapter(Activity context, Book book)
{
super(context,0, (List<Book>) book);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View listItemView = convertView;
if(listItemView == null) {
listItemView = LayoutInflater.from(getContext()).inflate(
R.layout.list_item, parent, false);
}
Book cbook=getItem(position);
TextView title = (TextView) listItemView.findViewById(R.id.title);
title.setText(cbook.getmTitle());
TextView author=(TextView) listItemView.findViewById(R.id.author);
author.setText((CharSequence) cbook.getmAuthor());
return listItemView;
}
}
Showing error in statement:
String text = i.getStringExtra ("text");
Need guidance
I don't know how your code gets compiled when you have overridden onCreate() in Request class and the Request class isn't extending Activity or AppCompatActivity.
Secondly, this line :
Intent i = getIntent();
String text = i.getStringExtra ("text");
should be inside the onCreate() method.
Showing error in statement : String text = i.getStringExtra ("text");
Request for Guidance
Well you need to get the data passed inside onCreate like below.
String APIURL;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_request);
Bundle bundle = getIntent().getExtras();
String text = bundle.getString("text");
APIURL="https://www.googleapis.com/books/v1/volumes?q= " + text;
}
And although you have the asyncTask class i can't see where exactly you execute the class. You need to do that inside onCreate as well.
Try moving this code to your onCreate method
Intent i = getIntent();
String text = i.getStringExtra ("text");
The intent extras is not available in the constructor for your Request class.

Android - HangMan App Errors

I do not understand why my app crashes in this code, and there is no error or stacktrace in logcat.
package org.concordacademy.hangman;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Random;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
public class PlayScreen extends Activity {
// The String Below will tell Console/LogCat the processes of The PlayScreen Activity
private final String PS = "Play Screen";
private char[] secretWord;
private char[] displayedWord;
// Below is an array of the Letters already guessed.
private ArrayList<Character> chosenLetters = new ArrayList<Character>();
Random random = new Random();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_playscreen);
Log.i(PS, "Loading Play Screen.");
startGame();
}
// Read Text File entitled wordsEn.txt
public String readFromFile() {
String words = "";
// Array List That Words being added to
ArrayList<String> wordLineArray = new ArrayList<String>();
try {
InputStream inputstream = openFileInput("wordsEn.txt");
if (inputstream != null) {
InputStreamReader inputStreamReader = new InputStreamReader(inputstream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String receiveString = "";
StringBuilder stringBuilder = new StringBuilder();
while ( (receiveString = bufferedReader.readLine()) != null ) {
wordLineArray.add(receiveString);
stringBuilder.append(receiveString);
}
inputstream.close();
// Possible pointless code below
words = stringBuilder.toString();
}
}
catch (FileNotFoundException e) {
Log.e("login activity", "File not found: " + e.toString());
} catch (IOException e) {
Log.e("login activity", "Can not read file: " + e.toString());
}
//R Generator for Strings in wordLineArray
//String secretWordString = wordLineArray.get(getRandomNumber(0, wordLineArray.size()));
String secretWordString = "HelloWorld";
secretWord = secretWordString.toCharArray();
for (int i = 0; i < secretWord.length; i++) {
displayedWord[i] = '-';
}
return words;
}
// Choose a random number that is assigned to a corresponding String in ArrayList
public int getRandomNumber(int min, int max) {
int number = min + (int)(Math.random() * ((max - min) + 1));
return number;
}
public void startGame() {
readFromFile();
String secretWordString = "HelloWorld";
secretWord = secretWordString.toCharArray();
displayedWord = new char[secretWord.length];
for (int i = 0; i < secretWord.length; i++) {
displayedWord[i] = '-';
}
}
public void findLetters(String guess) {
for (int i = 0; i < secretWord.length; i++) {
// Change Guess to CharArray and 0 Index.
if (!guess.isEmpty()) {
if (guess.toCharArray()[0] == secretWord[i]) {
Log.i(PS, "Correct Guess");
displayedWord[i] = guess.toCharArray()[0];
}
}
}
// Add Guess to the already chosen letter array
if (!guess.isEmpty()) {
chosenLetters.add(guess.toCharArray()[0]);
}
}
public boolean checkWin() {
if (displayedWord == secretWord) {
return true;
} else {
return false;
}
}
public void guessButtonClick(View v) {
TextView displayText = (TextView) findViewById(R.id.displayedWord);
displayText.setText(displayedWord.toString());
EditText inputGuess = (EditText) findViewById(R.id.textField);
String guess = inputGuess.getText().toString();
findLetters(guess);
}
}
Secondly, When I use the text view to display dashes, instead, it doesn't display anything and when i submit a letter it shows a memory location. I know I am not providing much information, but I am deeply confused. I am also reading a txt file and storing it into an array, and it vital I need it.
You have a problem with the displayedWord variable. It is being initialized after you use it in startGame()
readFromFile(); // here you use it
//...
displayedWord = new char[secretWord.length]; // here you initialize it
You need to initialize it first, and THEN used it!

Faster Way to parse data and populate array?

My code i use to parse HTMl is this below, and the 2nd code is how i call on it to populate an array for a simplelist.
The problem i have is it take upwards of 5 or 6 seconds to download, parse and display the data, which is far too long.
What is a way to speed up the process so its as close so instant as possible
Also, just so its clear i hard coded the url into the 2nd bit of code, once done, that will be passed in, depending on waht route, direction and stop you use.
public ArrayList<String> getStops(String URL) {
ArrayList<String> BusStop = new ArrayList<String>();
String HTML = DownloadText(URL);
String temp = null;
String temp2[] = new String[40];
Pattern p = Pattern.compile("<a class=\"ada\".*</a>", Pattern.DOTALL);
Matcher m = p.matcher(HTML);
while (m.find()) {
temp = m.group();
temp2 = temp.split("<br></td>");
}
for (int i = 0; i < temp2.length; i++) {
temp = temp2[i];
temp = temp.replaceAll("<a class=\"ada\" title=\"", "");
temp = temp.replaceAll("\".*\"", "");
temp = temp.replaceAll("\n", "");
temp = temp.replaceAll("\t", "");
temp = temp.replaceAll(",</a>", "");
temp = temp.replaceAll("</tr>.*>", "");
temp = temp.replaceAll("<td.*>", "");
temp = temp.replaceAll(">.*", "");
BusStop.add(temp);
}
return BusStop;
}
..
TransitXMLExtractor extractor;
static String baseURL5 = "http://www.ltconline.ca/webwatch/ada.aspx?r=1&d=2";
/** Populates string array with bus routes */
public String[] busStopArray() {
extractor = new TransitXMLExtractor();
String[] busStopArray = new String[31];
for (int n = 0; n < busStopArray.length; n++) {
busStopArray[n] = extractor.getStops(baseURL5).get(n);
}
return busStopArray;
}
It seems like you could speed things up by pulling the exact text you want with the regular expression and reducing the parsing loop.
public ArrayList<String> getStops(String URL) {
ArrayList<String> BusStop = new ArrayList<String>();
String HTML = DownloadText(URL);
Pattern p = Pattern.compile("<a class=\"ada\" title=\"([\\w\\s]+)\"");
Matcher m = p.matcher(HTML);
while (m.find()) {
BusStop.add(m.group(1));
}
return BusStop;
}
Also, the calling bit could just be:
public String[] busStopArray() {
extractor = new TransitXMLExtractor();
return extractor.getStops(baseURL5).toArray(new String[0]);
}
The way I have it now, it should pull the text in the title attribute from each link of class 'ada'.
EDIT: To be clear, it should actually pull the the <a class="ada" title="(whatever)", one at a time with the group(1) getting the (whatever) text for you.
EDIT 2: I updated the examples to match what I found to be working code. Also, here is the entire Activity I used to test with:
package com.kiswa.test;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
public class TestActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
StringBuilder sb = new StringBuilder();
for (String stop : busStopArray()) {
sb.append(stop);
}
Log.d("STRING_TEST", sb.toString());
setContentView(R.layout.main);
}
public String DownloadText() throws UnsupportedEncodingException, IOException {
Log.d("STRING_TEST", "In DownloadText");
URL url = new URL("http://www.ltconline.ca/webwatch/ada.aspx?r=1&d=2");
BufferedReader reader = null;
StringBuilder builder = new StringBuilder();
try {
reader = new BufferedReader(new InputStreamReader(url.openStream(), "UTF-8"));
for (String line; (line = reader.readLine()) != null;) {
builder.append(line.trim());
}
} finally {
if (reader != null) try { reader.close(); } catch (IOException logOrIgnore) {}
}
return builder.toString();
}
public ArrayList<String> getStops() {
Log.d("STRING_TEST", "In getStops");
ArrayList<String> BusStop = new ArrayList<String>();
String HTML = "";
try {
HTML = DownloadText();
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Pattern p = Pattern.compile("<a class=\"ada\" title=\"([\\w\\s]+)\"");
Matcher m = p.matcher(HTML);
while (m.find()) {
BusStop.add(m.group(1));
}
return BusStop;
}
public String[] busStopArray() {
Log.d("STRING_TEST", "In busStopArray");
return getStops().toArray(new String[0]);
}
}

Sorting from file Android

I want to get text from file, and show it on TextView sorted.
I have class called RankActivity where I with zapisi() method writing one string and one integer called poenibrojanje to the file called 3.txt.
public void zapisi() {
// WRITING
String eol = System.getProperty("line.separator");
String a = txtIme.getText().toString();
try {
FileOutputStream fOut = openFileOutput("3.txt", MODE_APPEND);
OutputStreamWriter osw = new OutputStreamWriter(fOut);
osw.write("Ime: " + a + " Poeni: " + a1.poenibrojanje + eol);
// Log.d("Writing", "This is writing log: " + a +
// +a1.poenibrojanje);
// osw.flush();
osw.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
Also I have class where I read stuff from file, and show it in TextView. That class is called RankPrikazActivity and here is full code.
package com.test.brzoracunanje;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class RankPrikazActivity extends Activity implements OnClickListener {
TextView tvRank, tvRankPrikaz;
Button btnPovratak;
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.rankprikaz);
tvRank = (TextView)findViewById(R.id.tvRank);
tvRankPrikaz = (TextView)findViewById(R.id.tvRankPrikaz);
btnPovratak = (Button)findViewById(R.id.btnPovratak);
btnPovratak.setOnClickListener(this);
citaj();
}
#Override
public void onClick(View v) {
Intent intent = new Intent(this,PocetnaActivity.class);
startActivity(intent);
}
public void citaj() {
// READING
String eol = System.getProperty("line.separator");
try {
BufferedReader input = new BufferedReader(new InputStreamReader(
openFileInput("3.txt")));
String line;
StringBuffer buffer = new StringBuffer();
while ((line = input.readLine()) != null) {
buffer.append(line + eol);
}
//Log.d("Reading log", "This is reading log:" + buffer);
//System.out.println(buffer);
tvRankPrikaz.setText(buffer.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
}
With method called citaj() method under this class, I read it from file and show it in TextView with this line:
tvRankPrikaz.setText(buffer.toString());
Now I want to show it on this text box sorted by integer poenibrojanje from RankActivity class.
How to do it?
Just put these lines to the reading part instead of your code:
StringBuffer buffer = new StringBuffer();
LinkedList<String> strings = new LinkedList<String>();
while ((line = input.readLine()) != null) {
strings.add(line);
}
Collection.sort(strings);
String text = "";
for(String string : strings) {
text += string + eol;
}
tvRankPrikaz.setText(text);
Try this instead:
public void citaj() {
// READING
try {
BufferedReader input = new BufferedReader(new InputStreamReader(
openFileInput("3.txt")));
String line;
TreeMap<Integer,String> sorted_map = new TreeMap<Integer,String>(new Comparator(){
public int compare(Object o1, Object o2){
Integer i1 = (Integer)o1;
Integer i2 = (Integer)o2;
return -(i1.compareTo(i2));
}
public boolean equals(Object o1){
return this == o1;
}
});
while ((line = input.readLine()) != null) {
Pattern intsOnly = Pattern.compile("\\d+");
Matcher makeMatch = intsOnly.matcher(line);
makeMatch.find();
Integer inputInt = Integer.valueOf(makeMatch.group());
sorted_map.put(inputInt, line);
}
//Log.d("Reading log", "This is reading log:" + buffer);
//System.out.println(buffer);
String toOutput = "";
for(Integer i: sorted_map.keySet()){
toOutput += sorted_map.get(i) + "\n";
}
tvRankPrikaz.setText(toOutput);
} catch (Exception e) {
e.printStackTrace();
}
}
Here I wrote you simple example of sorting by numbers.
All you have to do is to parse the integer from the string you fetch from file and put it as key for the map, and the string (link) for the value of that key...
This is example I just wrote. You need to adjust it by your needs.
Map<Double, String> map = new HashMap<Double, String>();
map.put(new Double(22.02), "TEST 1");
map.put(new Double(12.3), "TEST 2");
map.put(new Double(1.3), "Test 3");
Set<Double> nums = map.keySet();
Collection<String> strings = map.values();
Object[] Arr = nums.toArray();
List list= Arrays.asList(Arr);
Collections.sort(list);
for(Object o: list)
map.put((Double) o, map.get(o));
for(Double d: map.keySet())
Log.i("TEST", map.get(d));
The simples thing to do would be to use a database instead. Then when you do the select query, you can just have the results sorted using the ORDER BY clause.

Categories

Resources