Sorting from file Android - 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.

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

Null Pointer Exception at Button's onClick

I have a form having one edittext and an autocompleteview. And a button to search things based on this form. In this form I can either give value in edittext and autocompleteview may be empty and vice versa. On this basis I have passed value of these view to another activity where I made a webservice call and then fetch result.
This is activity where these view are presents:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_patient_section);
getSupportActionBar().hide();
searchByNameEditText = (EditText) findViewById(R.id.searchByNameEditText);
searchByAddressEditText = (EditText) findViewById(R.id.searchByAddressEditText);
searchButton = (Button) findViewById(R.id.searchButton);
autoCompleteTextView = (AutoCompleteTextView) findViewById(R.id.selectStateSpinner);
ArrayAdapter<String> adapter = new ArrayAdapter<>(this,
android.R.layout.simple_dropdown_item_1line,
getResources().getStringArray(R.array.state_arrays));
autoCompleteTextView.setAdapter(adapter);
patientUtilityButton = (Button) findViewById(R.id.patientUtilityButton);
patientUtilityButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
PopupMenu popupMenu = new PopupMenu(PatientSectionActivity.this, patientUtilityButton);
popupMenu.getMenuInflater().inflate(R.menu.patient_utility_button_popmenu, popupMenu.getMenu());
popupMenu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
String patientUtilityMenuItem = item.toString();
patientUtilityButton.setText(patientUtilityMenuItem);
return true;
}
});
popupMenu.show();
}
});
autoCompleteTextView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
selectedStateValue = (String) parent.getItemAtPosition(position);
}
});
doctorName = searchByNameEditText.getText().toString();
// Search Button
searchButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!selectedStateValue.equals(" ") || doctorName.equals(" ")){
Intent intent = new Intent(PatientSectionActivity.this, DoctorNameActivity.class);
intent.putExtra("State Name", selectedStateValue);
startActivity(intent);
} else if (!doctorName.equals(" ") || selectedStateValue.equals(" ")){
Intent intent = new Intent(PatientSectionActivity.this, DoctorNameActivity.class);
intent.putExtra("Name", doctorName);
startActivity(intent);
}
}
});
}
And in other activity, I get these extras from intent and make webservice call in AsyncTask but my app is crashing. Please any one help me as I am new in android.
This is my other activity
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.ProgressBar;
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;
public class DoctorNameActivity extends ActionBarActivity {
ArrayAdapter<String> doctorAdapter;
ListView listView;
ProgressBar progressBar;
String doctorName;
String selectedStateValue;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_doctor_name);
progressBar = (ProgressBar) findViewById(R.id.progress);
listView = (ListView) findViewById(R.id.listView);
Intent intent = getIntent();
selectedStateValue = intent.getStringExtra("State Name");
doctorName = intent.getStringExtra("Name");
if (!selectedStateValue.equals(" ") || doctorName.equals(" ")){
FetchDoctorName fetchDoctorName = new FetchDoctorName();
fetchDoctorName.execute(selectedStateValue);
}else if (!doctorName.equals(" ") || selectedStateValue.equals(" ")){
FetchDoctorName fetchDoctorName = new FetchDoctorName();
fetchDoctorName.execute(doctorName);
}
}
private class FetchDoctorName extends AsyncTask<String, Void, String[]>{
private final String LOG_TAG = FetchDoctorName.class.getSimpleName();
public String[] parseDoctorName(String jsonString) throws JSONException{
final String DOCTOR_NAME_ARRAY = "name";
JSONObject object = new JSONObject(jsonString);
JSONArray array = object.getJSONArray(DOCTOR_NAME_ARRAY);
String[] doctorNamesResult = new String[array.length()];
for (int i = 0 ; i < array.length(); i++){
String doctorName = array.getString(i);
Log.v(LOG_TAG, doctorName);
doctorNamesResult[i] = doctorName;
}
return doctorNamesResult;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
progressBar.setVisibility(ProgressBar.VISIBLE);
}
#Override
protected String[] doInBackground(String... params) {
// 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 doctorJsonString = null;
try {
final String BASE_URL = "http://mycityortho.com/display_result.php";
final String NAME_PARAM = "name";
final String STATE_PARAM = "state";
URL url = null;
if (params[0].equals(doctorName)){
Uri uri = Uri.parse(BASE_URL).buildUpon()
.appendQueryParameter(NAME_PARAM, params[0])
.build();
url = new URL(uri.toString());
Log.v(LOG_TAG, url.toString());
}else if (params[0].equals(selectedStateValue)){
Uri uri = Uri.parse(BASE_URL).buildUpon()
.appendQueryParameter(STATE_PARAM, params[0])
.build();
url = new URL(uri.toString());
Log.v(LOG_TAG, url.toString());
}
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
// Read the input stream into a String
InputStream inputStream = urlConnection.getInputStream();
StringBuffer buffer = new StringBuffer();
if (inputStream == null) {
// Nothing to do.
return null;
}
reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
// Since it's JSON, adding a newline isn't necessary (it won't affect parsing)
// But it does make debugging a *lot* easier if you print out the completed
// buffer for debugging.
buffer.append(line + "\n");
}
if (buffer.length() == 0) {
// Stream was empty. No point in parsing.
return null;
}
doctorJsonString = buffer.toString();
Log.v(LOG_TAG, doctorJsonString);
} catch (IOException e) {
Log.e(LOG_TAG, "Error ", e);
// If the code didn't successfully get the weather data, there's no point in attemping
// to parse it.
return null;
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
if (reader != null) {
try {
reader.close();
} catch (final IOException e) {
Log.e(LOG_TAG, "Error closing stream", e);
}
}
}
try {
return parseDoctorName(doctorJsonString);
}catch (JSONException e){
Log.e(LOG_TAG, e.getMessage(), e);
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String[] result) {
progressBar.setVisibility(ProgressBar.GONE);
if (result != null){
doctorAdapter = new ArrayAdapter<>(DoctorNameActivity.this, android.R.layout.simple_list_item_1, result);
listView.setAdapter(doctorAdapter);
}
}
}
As per your code you are sending only one value in intent that is "State Name" or "Name" but in other activity you are trying to receive both value, that why you get null pointer exception.
So use the following code to solve this error.
searchButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!selectedStateValue.equals(" ") || doctorName.equals(" ")){
Intent intent = new Intent(PatientSectionActivity.this, DoctorNameActivity.class);
intent.putExtra("State Name", selectedStateValue);
intent.putExtra("Name", " ");
startActivity(intent);
} else if (!doctorName.equals(" ") || selectedStateValue.equals(" ")){
Intent intent = new Intent(PatientSectionActivity.this, DoctorNameActivity.class);
intent.putExtra("State Name", " ");
intent.putExtra("Name", doctorName);
startActivity(intent);
}
}
});

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

Categories

Resources