Faster Way to parse data and populate array? - android

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]);
}
}

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.

Create table rows dynamically from parsed JSON in AsyncTask in 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();
}

Display large text from BufferedReader into viewPager fragments (text reader type implementation)

Im trying to make a reader app wherein the data is completely static. So i have saved that data in text files in the assets folder. I want to read that data using a bufferedReader and display it in a viewPager. As the user goes on swiping to the right, pages should be added to the viewPager along with data from the bufferedReader if there is data to display.
This is my getItem function inside the viewPagerAdapter.
public Fragment getItem(int i) {
Fragment pageFragment = new PageFragment();
StringBuilder sb = new StringBuilder();
BufferedReader reader = null;
try {
InputStream file = context.getAssets().open("chap1.txt");
reader = new BufferedReader(new InputStreamReader(file));
// do reading, usually loop until end of file reading
String mLine = reader.readLine();
while (mLine != null) {
//process line
sb.append(mLine);
sb.append("\n");
mLine = reader.readLine();
}
} catch (IOException e) {
//log the exception
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
//log the exception
}
}
}
//Log.e("READ TEXT", sb.toString());
Bundle bundle = new Bundle();
bundle.putString("content", sb.toString());
pageFragment.setArguments(bundle);
return pageFragment;
}
I dont want the pages to have scroll views.
How can I achieve this?
How can I limit the text read from the bufferedReader?
Or how can I split the text data and add it to different fragments?
If my problem is not clear, please ask questions. Im not able to explain properly.
PS: Any other approach is also welcomed.
i hope this is going to help
package com.admin.viewpagerex;
import android.content.Context;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;
public class CustomAdapter extends FragmentPagerAdapter {
int WordsNumber = 100;
int WordCounter = 0;
String content ;
Context context;
public CustomAdapter(FragmentManager fm, Context context1) {
super(fm);
context = context1;
}
#Override
public Fragment getItem(int position) {
MyFragment myFragment = new MyFragment();
loadContent();
myFragment.setContent(content);
WordsNumber = WordCounter + 100;
myFragment.pageNumber = position++;
return myFragment;
}
private void loadContent() {
try {
InputStreamReader file = new InputStreamReader(context.getAssets().open("yourtext.txt"));
Scanner reader = new Scanner(file);
StringBuffer PageWriter = new StringBuffer();
int i = 0;
while (reader.hasNext()&& WordCounter < WordsNumber) {
String words = reader.next();
if (i == WordCounter) {
PageWriter.append(words + " ");
WordCounter++;
}
i++;
}
content = PageWriter.toString();
reader.close();
} catch (IOException e) {
e.printStackTrace();
}catch (Exception ex){
}
}
#Override
public int getCount() {
return 16; // number of pages
}
}
and in your fragment add setContent() method like this
public void setContent(String pagetext) {
content = pagetext; // make sure the content is global String variable
}

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!

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