Android - HangMan App Errors - android

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!

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

Save a Site's HTML code into string Android

So I've been trying to Save a website's code, (This website contains only html/php), into a String inside android.
Now, I've tried ASyncTask, and Couldn't get it to work. I've read the whole documentary..
I have to admit, I'm a starter in Android.
Still, for some reason, Everything I've tried either made it crash or didn't work.
Now, I'm asking you for a simple example, how to get a website's code, and set it as a String.
Thanks in advance!
Edit:
MainTabView.java
package com.example.projectnova;
import java.net.URL;
import com.example.projectnova.R.string;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TabHost;
import android.widget.Toast;
import android.widget.TabHost.TabSpec;
public class MainTabView extends Activity implements OnClickListener{
TabHost th;
TabSpec specs;
Button search;
EditText searchText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_tab_view);
search = (Button)findViewById(R.id.searchButton);
searchText = (EditText)findViewById(R.id.searchInputText);
th = (TabHost)findViewById(R.id.tabhost);
search.setOnClickListener(this);
th.setup();
specs = th.newTabSpec("tag1");
specs.setContent(R.id.Search);
specs.setIndicator("Search");
th.addTab(specs);
specs = th.newTabSpec("tag2");
specs.setContent(R.id.Download);
specs.setIndicator("Downloads");
th.addTab(specs);
/*
*
* Example in (I believe)PHP
*
function streaminfo($file,$port) {
global $src;
$fp = #fsockopen ($file, $port, &$errno, &$errstr, 5);
if (!$fp) {
echo "Could not connect to <b>{$file}:{$port}</b> ({$errno}) - {$errstr}\n";
} else {
fputs ($fp, "GET /7 HTTP/1.1\r\nUser-Agent:Mozilla\r\n\r\n");
while (!feof($fp)) {
$stream = fgets($fp,1024);
}
list(,$stream) = explode("<body>",$stream);
list($stream) = explode("</body>",$stream);
list($user, $status, $user_peak, $user_max,$filler ,$bitrate, $song) = explode(",",$stream);
if($status== 0 ) {
} else {
$arr = array('nameofsong' => $song);
echo json_encode($arr);
}
fclose($fp);
}
}
streaminfo("188.138.79.175",8030);
*/
}
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
switch(arg0.getId()){
case R.id.searchButton:
int i = searchText.getText().toString().length();
if(i == 0){
Context context = getApplicationContext();
CharSequence text =("The search box is empty");
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
else{
String s = searchText.getText().toString();
String htmlText = s.replace(" ","_"); // Works
String link = "WebsiteUrl.com/" + htmlText + ".html"; //Works
// searchText.setText(link); Test Purposes
}
}
}
private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> {
protected Long doInBackground(URL... urls) {
int count = urls.length;
long totalSize = 0;
for (int i = 0; i < count; i++) {
totalSize += Downloader.downloadFile(urls[i]);
publishProgress((int) ((i / (float) count) * 100));
// Escape early if cancel() is called
if (isCancelled()) break;
}
return totalSize;
}
protected void onProgressUpdate(Integer... progress) {
setProgressPercent(progress[0]);
}
protected void onPostExecute(Long result) {
showDialog("Downloaded " + result + " bytes");
}
}
}
Can I ask why you need to do that?
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet(url);
HttpResponse response = client.execute(request);
String html = "";
InputStream in = response.getEntity().getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder str = new StringBuilder();
String line = null;
while((line = reader.readLine()) != null)
{
str.append(line);
}
in.close();
html = str.toString();

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