Android: get as a static String a value from a URL - android

URL = http://troyka.esy.es/numberofrows.php
if you put that in your browser you'l get a number (currently it's 9)
I'm trying to pull that number to my android app and display it on a textview
I've tried this method but it shows me nothing on the emulator
internet and network permission are set on manifest
textview id = "textView"
What am I doing wrong?
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
public class MainActivity extends Activity {
public static String ans;
private TextView T1;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
T1 = new TextView(this);
T1 = (TextView) findViewById(R.id.textView);
T1.setText(ans);
}
public String getDATA() throws IOException {
String fullString = "";
URL url = new URL("http://troyka.esy.es/numberofrows.php");
BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));
String line;
while ((line = reader.readLine()) != null) {
fullString += line;
}
reader.close();
return fullString;
}
public void setAns() throws IOException {
ans = getDATA();
}
}

Try this answer please:
First, create an AsyncTask class like this to do the actual HTTP request for you outside the android main thread:
public class FetchColumnAsync extends AsyncTask<String, Void, String>
{
private Context mContext;
public FetchColumnAsync( Context ctx){
this.mContext = ctx;
}
protected String doInBackground(String... urls)
{
String fullString = "";
try{
URL url = new URL(urls[0]);
BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream()));
String line;
while ((line = reader.readLine()) != null) {
fullString += line;
}
reader.close();
}catch(Exception e ){
e.getMessage();
}
return fullString;
}
#Override
protected void onPostExecute(String value){
try{
((OnValueFetchedListener) mContext).onValueFetched(value);
}catch(ClassCastException e){}
}
public interface OnValueFetchedListener{
void onValueFetched(String columns);
}
}
Then in your activity class, implement the above interface like this;
public class MainActivity extends Activity implements FetchColumnAsync.OnValueFetchedListener{
public static String ans;
private TextView T1;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
T1 = (TextView) findViewById(R.id.textView);
//missing piece of code here
new FetchColumnAsync(this).execute("http://troyka.esy.es/numberofrows.php");
}
#Override
public void onValueFetched(String value){
T1.setText(value);
}
}

Related

Oxford Dictionary Api Search Word Through EditText

MainActivivity.java
package com.example.anubhav.notesapp;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity2 extends AppCompatActivity {
String url;
EditText et;
TextView t1;
Button btn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
et = (EditText)findViewById(R.id.editText2);
t1 = (TextView)findViewById(R.id.textView3);
btn = (Button)findViewById(R.id.button);
url = dictionaryEntries();
}
public void requestApiButtonClick(View v)
{
MyDictionaryRequest myDictionaryRequest = new MyDictionaryRequest(this,t1);
myDictionaryRequest.execute(url);
}
private String dictionaryEntries() {
final String language = "en";
final String word = et.getText().toString();
final String word_id = word.toLowerCase();
return "https://od-api.oxforddictionaries.com:443/api/v1/entries/" + language + "/" + word_id;
}
}
DictionaryRequest.java
public class MyDictionaryRequest extends AsyncTask<String,Integer,String> {
final String app_id = "your_apiId";
final String app_key = "Your api_key";
String myurl;
TextView t1;
Context context;
Handler h = new Handler();
MyDictionaryRequest(Context context,TextView t1){
this.context = context;
this.t1=t1;
}
#Override
protected String doInBackground(String... strings) {
myurl = strings[0];
try {
URL url = new URL(myurl);
HttpsURLConnection urlConnection = (HttpsURLConnection) url.openConnection();
urlConnection.setRequestProperty("Accept","application/json");
urlConnection.setRequestProperty("app_id",app_id);
urlConnection.setRequestProperty("app_key",app_key);
// read the output from the server
BufferedReader reader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
StringBuilder stringBuilder = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
stringBuilder.append(line + "\n");
}
return stringBuilder.toString();
}
catch (Exception e) {
e.printStackTrace();
return e.toString();
}
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
String def;
try{
JSONObject js = new JSONObject(s);
JSONArray results = js.getJSONArray("results");
JSONObject lentries = results.getJSONObject(0);
JSONArray lArray= lentries.getJSONArray("lexicalEntries");
JSONObject entries = lArray.getJSONObject(0);
JSONArray e = entries.getJSONArray("entries");
JSONObject senses = e.getJSONObject(0);
JSONArray sensesArray = senses.getJSONArray("senses");
JSONObject d = sensesArray.getJSONObject(0);
JSONArray de = d.getJSONArray("definitions");
def=de.getString(0);
t1.setText(def);
Toast.makeText(context,def,Toast.LENGTH_SHORT).show();
}catch (Exception e)
{
e.printStackTrace();
}
}
}
Everthing is working fine in this code except that I can't get the word's meaning through edit text.
To be more specific :
The code works fine when I add
final String word = "car";
in dictionaryEntries() under Mainactivity.java
but nothing is displayed when :
final String word = et.getText().toString();
you have to move one of your code :
public void requestApiButtonClick(View v) {
MyDictionaryRequest myDictionaryRequest = new MyDictionaryRequest(this, t1);
url = dictionaryEntries();
myDictionaryRequest.execute(url);
}

How to use sockets to read data from server?

The app has MainActivity(contains an EditText and a Button) and DisplayActivity(contains a single TextView)The user enters a message in the EditText and presses the send button. The message string from the EditText gets sent to the server. Then starts a new intent to DisplayActivity. DisplayActivity will read data from the server with readLine(), and set TextView from the data received from the server.
activity_main.xml has a EditText with id="#+id/message_textView" and Button with id="#+id/send_button". DisplayActivity has android:id="#+id/displayTextView".
My code to send data to the server works, but when I try to read data from the server, readline() just stops there and sits there forever.
Android app has MainActivity and DisplayActivity class.
I run the server code in eclipse.
Server code.
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
import java.net.*;
import java.io.*;
public class MyServer {
public static void main(String[] args) throws IOException {
int portNumber = 4442;
System.out.println("Starting server..");
try {
while(true) {
ServerSocket serverSocket =
new ServerSocket(portNumber);
Socket clientSocket = serverSocket.accept();
PrintWriter out =
new PrintWriter(clientSocket.getOutputStream(), true);
BufferedReader in = new BufferedReader(
new InputStreamReader(clientSocket.getInputStream()));
String message = in.readLine();
System.out.println(message);//Just print to console, to test if server got message
out.println(message);
serverSocket.close();
clientSocket.close();
// out.close();
// in.close();
}
} catch (IOException e) {
System.out.println("Exception caught when trying to listen on port "
+ portNumber + " or listening for a connection");
System.out.println(e.getMessage());
}
}
}
MainActivity
import android.content.Intent;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.Socket;
public class MainActivity extends AppCompatActivity {
static Socket client;
private PrintWriter printWriter;
private EditText messageET;
private Button sendButton;
private String message;
static String hostIP = "10.0.2.2";
static int port = 4442;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
messageET = findViewById(R.id.message_textView);
sendButton = findViewById(R.id.send_button);
sendButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
message = messageET.getText().toString();
messageET.setText("");
MyTask myTask = new MyTask();
myTask.execute();
Intent intent = new Intent(getApplicationContext(), DisplayActivity.class);
startActivity(intent);
}
});
}
class MyTask extends AsyncTask<String,Void,String>
{
#Override
protected String doInBackground(String... strings) {
try
{
client = new Socket(hostIP, port);
printWriter = new PrintWriter(client.getOutputStream(), true);
//printWriter.write(message);
printWriter.println(message);
//printWriter.flush();
printWriter.close();
client.close();
}catch(IOException e)
{
e.printStackTrace();
}
return null;
}
}
}
DisplayActivity
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
public class DisplayActivity extends AppCompatActivity {
//final String TAG = "displayactivitylog";
private Socket socket;
private BufferedReader bufferedReader;
private TextView displayTV;
private String msgReceived = null;
String hostIP = "10.0.2.2";
int port = 4442;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display);
displayTV = findViewById(R.id.displayTextView);
ReadTask readTask = new ReadTask();
readTask.execute();
}
class ReadTask extends AsyncTask<String,Void,String>
{
#Override
protected String doInBackground(String... strings) {
String result = "";
try
{
//create a new socket and attempt to read from it
socket = new Socket(hostIP,port);
bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
//*****the app stops on this line, and nothing happens after*****
msgReceived = bufferedReader.readLine();
//************************************
// while((msgReceived = bufferedReader.readLine()) != null){
// result += msgReceived;
// }
bufferedReader.close();
socket.close();
}catch(IOException e)
{
e.printStackTrace();
}
return result;
}
//update the TextView with the message from the server
#Override
protected void onPostExecute(String s) {
displayTV.setText(s);
super.onPostExecute(s);
}
}
}
When i run debugger, it literally just stops in DisplayActivity.java on msgReceived = bufferedReader.readLine() in the doInBackground() method and gives no error.
My server starts fine and when I send data from my app to the server, on eclipse it prints out what was sent(and sometimes null for some reason).
---------------SOLUTION---------------
Question was answered by green apps, but basically the server class expects to read something when a connection first opens, and then send out data. However in ReadTask, all it does is try to read data from the server(but it should send data first, then read from it)
Updated code.
MainActivity.java
public class MainActivity extends AppCompatActivity {
private EditText messageET;
private Button sendButton;
static String message;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
messageET = findViewById(R.id.message_textView);
sendButton = findViewById(R.id.send_button);
sendButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
message = messageET.getText().toString();
messageET.setText("");
Intent intent = new Intent(getApplicationContext(), DisplayActivity.class);
startActivity(intent);
}
});
}
}
DisplayActivity.java
public class DisplayActivity extends AppCompatActivity {
private Socket socket;
private PrintWriter printWriter;
private BufferedReader bufferedReader;
private TextView displayTV;
private String msgReceived = null;
String hostIP = "10.0.2.2";
int port = 4442;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display);
displayTV = findViewById(R.id.displayTextView);
ReadTask readTask = new ReadTask();
readTask.execute();
}
class ReadTask extends AsyncTask<String,Void,String>
{
#Override
protected String doInBackground(String... strings) {
String result = "";
try
{
//create a new socket and attempt to write to it first then read from it
socket = new Socket(hostIP,port);
//add data to the server
printWriter = new PrintWriter(socket.getOutputStream(), true);
printWriter.println(MainActivity.message);
//get a stream, to be able to read data from the server
bufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
msgReceived = bufferedReader.readLine();
displayTV.setText(msgReceived);
//close the socket connections
printWriter.close();
bufferedReader.close();
socket.close();
}catch(IOException e)
{
e.printStackTrace();
}
return result;
}
}
}
You have two clientsocketss. And two serversockets.
Which is a very strange approach.
The first client sends a line and closes the connection. This works ok as the server tries to read that line and does. Both then close.
Then you start the second client. This one connects to a new serversocket. But this client directly tries to read a line. As the server also tries to read a line from this new client both will wait for eternity on readLine().

Using getSupportFragmentManager() inside AsyncTask

I have an Activity which has a Navigation Drawer that has many buttons and one of them is leading to a fragment.
The problem is that I have to make an AsyncTask to get some information from the server but I can't get to use getSupportFragmentManager() inside the AsyncTask.
I tried to use context or activity but I can't get it to work.
I get this error cannot resolve method getSupportFragmentManager()
AsyncTask.java:
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.support.v4.app.FragmentManager;
import android.util.Log;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.Toast;
public class AsyncTask extends AsyncTask<Void, Void, String> {
private Context c;
private String urlAddress;
private String token;
private DatabaseHelper db;
private Activity mainActivity;
public AsyncTask(Context c, DatabaseHelper databaseHelper, String urlAddress, Activity activity) {
this.c = c;
this.db = databaseHelper;
this.urlAddress = urlAddress;
this.mainActivity = activity;
//GET token FROM database
this.token = db.getValueFromColumn(0, DatabaseHelper.getTableUser(), DatabaseHelper.getUserToken());
}
#Override
protected String doInBackground(Void... params) {
return this.send();
}
#Override
protected void onPostExecute(String response) {
super.onPostExecute(response);
if (response != null) {
//SUCCESS
mainActivity.getSupportFragmentManager().beginTransaction()
.add(R.id.content_frame
, new SessionsFragment())
.addToBackStack("back")
.commit();
} else {
//NO SUCCESS
}
}
private String send() {
//CONNECT
HttpURLConnection connection = Connector.connect(urlAddress);
if (connection == null) {
return null;
}
try {
OutputStream outputStream = connection.getOutputStream();
//WRITE
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
bufferedWriter.write(new DataPackager(token).packData());
bufferedWriter.flush();
//RELEASE RES
bufferedWriter.close();
outputStream.close();
//HAS IT BEEN SUCCESSFUL?
int responseCode = connection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
//GET EXACT RESPONSE
InputStream stream = connection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
StringBuilder buffer = new StringBuilder();
String line;
//READ LINE BY LINE
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
String finalJson = buffer.toString();
JSONObject parentObject = new JSONObject(finalJson);
JSONObject secondParentObject = parentObject.getJSONObject("data");
//json getter and adder to database
JSONArray array = secondParentObject.getJSONArray("s");
for (int i = 0; i < array.length(); i++) {
JSONObject finalObject = array.getJSONObject(i);
db.SessionsAddJson(finalObject);
//RELEASE RES
reader.close();
}
return "c";
} else {
}
} catch (IOException | JSONException e) {
e.printStackTrace();
} finally {
connection.disconnect();
}
return null;
}
}
I call the task by:
new $AsyncTask(getApplicationContext(), db, URL, MyActivity.this).execute();
Thank you for your help.
Upd.:
You should pass the AppCompatActivity in constructor, like this:
Replace
private Activity mainActivity;
with
private AppCompatActivity mainActivity;
Also when you use it: replace
new $AsyncTask(getApplicationContext(), db, URL).execute();
with
new $AsyncTask(getApplicationContext(), db, URL, YourCurrentActivity.this).execute();
Notice that YourCurrentActivity should extends AppCompatActivity.
You just confuse AppCompatActivity with Activity. Activity haven't getSupportFragmentManager(), but AppCompatActivity have this.
If you are using an asyntask class then to load fragment you need context,i.e context of particular activity.
So typecast the context to the respective activity where you want to load the fragment and onPostExecute load the fragment using particular activity fragmentManager.
public class sampleAsyncTask extends AsyncTask<Void, Void, Void> {
private YourActivity mActivity;
#Override
protected Void doInBackground(Void... voids) {
return null;
}
public sampleAsyncTask(Context context) {
super();
activity = (YourActivity) context;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
mActivity.getSupportFragmentManager().beginTransaction()
.add(R.id.content_frame
, new Fragment())
.addToBackStack("back")
.commit();
}
}
EDIT:
In this line of code instead of storing generic reference of activity typecast to particular activity i.e your current activity.
private YOURACTIVITY mainActivity;
public AsyncTask(Context c, DatabaseHelper databaseHelper, String urlAddress, Activity activity) {
this.c = c;
this.db = databaseHelper;
this.urlAddress = urlAddress;
//TypeCast to your particular activity
mainActivity =(YOURACTIVITY) activity;
this.token = db.getValueFromColumn(0, DatabaseHelper.getTableUser(), DatabaseHelper.getUserToken());
}
Your activity should be AppCompatActivity not Activity
try this
getActivity().getFragmentManager().beginTransaction()
.add(R.id.content_frame
, new Fragment())
.addToBackStack("back")
.commit();

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.

How do I get the text from a textfile into a String?

I'm trying to get it so my app can read the words from my textfile separated by a carriage enter and spit them back out from a String array. My app starts up then just gives me a blank page which is pretty frustrating. Here is my code:
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Timer;
import java.util.Vector;
import android.os.Bundle;
import android.app.Activity;
import android.widget.TextView;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView helloTxt= (TextView)findViewById(R.id.hellotxt);
ArrayList<String> list = new ArrayList<String>();
try {
InputStream is = getResources().openRawResource(R.raw.test);
if (is != null) {
InputStreamReader isr = new InputStreamReader(is);
BufferedReader buffythevampireslayer = new BufferedReader(isr);
String line;
do {
line = buffythevampireslayer.readLine();
list.add(line);
} while (line != null);
}
is.close();
} catch (Exception ex) {
}
String[] wordsArray=new String[list.size()];
list.toArray(wordsArray);
Thread timer=new Thread(); {
for (int c=0;c<list.size();c++){
helloTxt.setText(wordsArray[c]);
System.out.println("TEXTSET");
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
timer.start();
}
}
I'd really appreciate it if anyone could help, thanks so much!!!
EDIT::::
After getting some help in this post, I now have the working app! Thanks so much! Here is the new code:
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import java.util.Timer;
import java.util.Vector;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.SystemClock;
import android.app.Activity;
import android.content.res.AssetManager;
import android.widget.TextView;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ReadAndUpdateTextTask readAndUpdateTextTask = new ReadAndUpdateTextTask();
readAndUpdateTextTask.execute();
}
class ReadAndUpdateTextTask extends AsyncTask<Void, String, String> {
public String currentString = "";
String line="";
InputStream isr;
#Override
protected void onPreExecute() {
isr = getResources().openRawResource(R.raw.test);
}
#Override
protected String doInBackground(Void... params) {
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(isr));
while ((line = reader.readLine())!= null) {
currentString += line + "\n";
publishProgress(currentString);
// I don't think you really need this but you want a sleep for 5000 ms
SystemClock.sleep(5000);
}
isr.close();
} catch (Exception ex) {
}
return currentString;
}
#Override
protected void onProgressUpdate(String... currentString) {
TextView helloTxt= (TextView)findViewById(R.id.hellotxt);
helloTxt.setText(currentString[0]);
}
#Override
protected void onPostExecute(String result) {
TextView helloTxt= (TextView)findViewById(R.id.hellotxt);
helloTxt.setText(result);
}
}
}
I don't know if this will solve anything, but you can try declaring your List as shown in Oracle's documentation. I will look further in a bit.
List<String> list = new ArrayList<String>();
if it's not a typo, your problem is here:
String[] wordsArray=new String[list.size()];
list.toArray(wordsArray);
it should be:
String[] wordsArray = list.toArray( new String[0] );
otherwise the array is filled with nulls
First, you need to store your text file in the assets folder
then you need to call the AssetManager to get the assets in your assets folder
AssetManager assetManager = getAssets();
InputStream inputStream = null;
surround these statements with a try block, in case the file is not found in the stated path
inputStream = assetManager.open("texts/sample.txt"); // path is relative to the assets folder
ByteArrayOutputStream bytesOutputStream = new ByteArrayOutputStream();
byte[] bytes = new byte[4096];
int length = 0;
read the the bytes and write them in an output stream
while((length = inputStream.read(bytes)) > 0)
bytesOutputStream.write(bytes,0,length);
create a new String, use the constructor with the byteOutputStream
encode it with UTF8(assuming there wont be any chinese, japanese, etc characters)
See this for more details about UTF Details
String yourString = new String(bytesOutputStream.toByteArray(), "UTF8");
Java String class has a method "split", which takes a regex as a parameter
it splits the string and stores it into a single element in an array everytime it encounters a new line
in your case, use '\n' which stands for new line
String[] yourStringArray = yourString.split("\n");
Surround everything with a try-catch clause (IOException), which is thrown in case file is not found
you can now use yourStringArray as
textView.setText(yourStringArray[index]);
You got a blank screen because you have a sleep at your main UI thread. Do reading the file in an AsyncTask and publish its process.
Your onCreate method should look like this:
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ReadAndUpdateTextTask readAndUpdateTextTask = new ReadAndUpdateTextTask();
readAndUpdateTextTask.execute();
}
class ReadAndUpdateTextTask extends AsyncTask<Void, String, String> {
InputStream isr;
#Override
protected void onPreExecute() {
isr = getResources().openRawResource(R.raw.test);
}
#Override
protected String doInBackground(Void... params) {
try {
String currentString = "";
BufferedReader reader = new BufferedReader(new InputStreamReader(isr));
while ((line = reader.readLine())!= null) {
currentString += line + "\n";
publishProgress(currentString);
// I don't think you really need this but you want a sleep for 5000 ms
SystemClock.sleep(5000);
}
isr.close();
} catch (Exception ex) {
}
return currentString;
}
#Override
protected void onProgressUpdate(String... currentString) {
TextView helloTxt= (TextView)findViewById(R.id.hellotxt);
helloTxt.setText(currentString[0]);
}
#Override
protected void onPostExecute(String result) {
TextView helloTxt= (TextView)findViewById(R.id.hellotxt);
helloTxt.setText(result);
}
}
}

Categories

Resources