Display ListView when button Click - android

I'm new to android and I hope someone could help me here. I have an activity Faculty and a button.
This is my XML layout browse_faculty:
<Button
android:onClick="searchFSTEHandler"
android:id="#+id/bFSTE"
android:layout_width="220dp"
android:layout_height="80dp"
android:layout_alignLeft="#+id/bFBE"
android:layout_below="#+id/bFBE"
android:layout_marginTop="20dp"
android:text="#string/fste" />
and this is my Faculty Activity which displays the buttons:
I use Intent to view ListView
public class Faculty extends Activity{
#Override
protected void onCreate(Bundle BrowseFaculty) {
// TODO Auto-generated method stub
super.onCreate(BrowseFaculty);
setContentView(R.layout.browse_faculty);
}
//on the XML,this is the "searchFSTEHandler" i want to use to show ListView
public void searchFSTEHandler(View target){
Intent courseList = new Intent(this, HttpActivity.class);
startActivity(courseList);
}
}
and below is the "HttpActivity" class is the class that displays my ListView. This class read a php file which gets data from a MySQL server and converts to JSON data then parses it into a array list.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.ListActivity;
import android.widget.ArrayAdapter;
public class HttpActivity extends ListActivity {
public String f1 = "FSTE";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.faculty_course);
new getHttp().execute();
getHttp test =new getHttp();
String strJsonData = test.doInBackground(f1);
// Convert String JSON data to Java class
ArrayList<Courses> arrayCourse= test.parseJsonData(strJsonData);
//Create an ArrayAdapter which shows the ArrayList data
this.setListAdapter(new ArrayAdapter<Courses>(this,android.R.layout.simple_list_item_1,arrayCourse));
}
private class getHttp extends AsyncTask<String, Void, String> {
public getHttp() {
}
#Override
protected String doInBackground(String... faculty) {
InputStream is = null;
try {
URL url = new URL("http://10.0.2.2/sqlWebService.php?faculty=FSTE");
URLConnection con = url.openConnection();
con.setConnectTimeout(10000);
con.setReadTimeout(10000);
is = con.getInputStream();
BufferedReader br = new BufferedReader(
new InputStreamReader(is));
StringBuffer sb = new StringBuffer();
String str;
while ((str = br.readLine()) != null) {
sb.append(str);
}
return sb.toString();
} catch (IOException e) {
e.printStackTrace();
return "";
} finally {
try {
if (is != null)
is.close();
} catch (IOException e2) {
e2.printStackTrace();
}
}
}
//------------------------------------------------------
private ArrayList<Courses> parseJsonData(String strJson) {
ArrayList<Courses> Course = new ArrayList<Courses>();
try {
// Generate JSONArray object by JSON String data
JSONArray arr = new JSONArray(strJson);
//from the JSONArray, get one element (row) of JSONData
for (int i = 0; i < arr.length(); i++) {
//Get JSON Object which is one element of the array
JSONObject ob = arr.getJSONObject(i);
Courses exam = new Courses();
//get the value by key, and set to exam class
exam.setCode(ob.optString("code"));
//save exam class to exam array list
Course.add(exam);
}
} catch (JSONException e) {
e.printStackTrace();
}
return Course;
}
}
}
The application crashes as soon as I click on the button and gives a error:
"android.os.NetworkOnMainThreadException"
Help Please !

The problem that you are having is network operation like what you are trying to do cannot and should not be performed on the main UI thread. Doing so will lead to an ANR (Android Not Responding), which is exactly the kind of error you are getting just now. What you want to do is move your code to a separate thread or to an AsyncTask that will perform this action in the background on a different thread using the doInBackground() method which does not have access to your views on the main UI thread. For example,
private class ExampleOperation extends AsyncTask<String, Void, String> {
public ExampleOperation() { //ctor }
#Override
protected void onPreExecute() {
//things that you want to initialize and maybe show dialog to user.
}
#Override
protected String doInBackground(String... params) {
//this is where you perform that network related operation.
}
#Override
protected void onPostExecute(String result) {
//this is where get the results from the network related task.
}
#Override
protected void onProgressUpdate(Void... values) {
//you can update your progressbar if any; otherwise omit method.
}
}
Then all you have to do is call the AsyncTask where ever you want to use it: new ExampleOperation().execute();

You can't make HTTP calls in the main thread, they take too long and would make the UI unresponsive. You need to do it in an AsyncTask.

Related

AsyncTask with Progress bar

I have an application with 3 or more AsycTask that are called sequentially. Because these asyntasks are all similar, I created a separated class and it works properly.
Now I would like to add a progress bar in order to show something when these asynctasks ask and process the result...but not work.
My application work as follow:
I open my camera and with ZXing library I decode a qrCode
using HttpRequest I ask to my server some informations and my application processes these informations
The point is that during the processing my application shows a black screen with the tipical viewfinder of ZXing library (I think that you understand what I mean). How can replace this view with another block with a progress bar?
I already tried to modified the progress bar visibility, on the event onPreExecute and onPostExecute, also I tried to use the event onProgressUpdate, but nothig is change. The viewfinder remains on the screen until the asyncTask is not finish.
Follow my code for execute the AsyncTask:
response = asynkTaskDeleteMissionQueue.execute().get();
and my AsyncTask class
package com.klainrobotics.lucalombardi.krmir;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;
import android.view.View;
import android.widget.ProgressBar;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.ProtocolException;
import java.net.URL;
import java.util.List;
import java.util.Vector;
/**
* Created by Luca Lombardi on 27/11/2017.
*/
public class MiRCall extends AsyncTask <String, Void, List<Object> >{
public AsyncResponse delegate = null;
private String url;
private String method;
private ProgressBar progress;
public MiRCall(Context v, ProgressBar prg, String...params){
method = params[0];
url = params[1];
progress = prg;
}
#Override
protected void onPreExecute(){
}
#Override
protected void onProgressUpdate(Void... v) {
super.onProgressUpdate(v);
}
#Override
protected List<Object> doInBackground(String... arg0) {
int result = -1;
publishProgress();
List<Object> response = new Vector<Object>();
String jsonResponse = "";
BufferedReader br;
try {
URL urlMissionQueue = new URL(url);
HttpURLConnection connection = (HttpURLConnection) urlMissionQueue.openConnection();
if (connection != null) {
connection.setRequestMethod(method);
connection.setRequestProperty(Costanti.headers, Costanti.StringaHeader());
connection.setRequestProperty(Costanti.contentType, Costanti.contentTypeJSon);
customBody(connection);
connection.connect();
result = connection.getResponseCode();
response.add(result);
if (200 <= result && result <= 299) {
br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
} else {
br = new BufferedReader(new InputStreamReader(connection.getErrorStream()));
}
for (String line; (line = br.readLine()) != null; jsonResponse += line);
response.add(jsonResponse);
}else {
Log.e("Url", "Connection is null");
}
} catch (Exception ex) {
Log.e("MiRCall", "doInBackgound: " + ex.toString());
}
return response;
}
#Override
protected void onPostExecute(List<Object> result) {
if (delegate != null) {
delegate.processFinish(result);
} else {
Log.e("MiRCall", "You have not assigned AsyncTask delegate");
}
}
public void customBody(HttpURLConnection connection) throws ProtocolException {
// Do nothing
}
}
Thanks in advance
response = asynkTaskDeleteMissionQueue.execute().get();
Pretty bad to use the .get() function on it. Do away with get(). Only start the task.
asynkTaskDeleteMissionQueue.execute();
Then in onPostExecute() handle the response.
Thanks for your suggestion. I execute
response = asynkTaskDeleteMissionQueue.execute().get();
because my asyncTask returns a list of object, so I don't know another way....
And about the original question? Any suggestions?
Thanks in any case for your time

Pass parameter to a URL AsyncTask android

I'm developing an app and now I have to pass a parameter to a RESTful Service's URL. I'm using AsyncTask, and I need to pass a text from a list view as a parameter to the URL, for example: the URL is http://ip:7001/product?product_name=PARAM I need to get the text from the selected item from my list view, and pass as a parameter in PARAM, using AsyncTask. I've already got the text from the item in the listView, now I just need to pass it as a parameter.
This is my AsycTask class:
package com.tumta.henrique.teste;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import com.tumta.henrique.teste.ProdutoFragment;
/**
* Created by Henrique on 18/05/2015.
*/
public class FiltraProduto extends AsyncTask<String, Void, List<String>> {
private ConsultaConcluidaFiltroProdutoListener listener;
public static String URL_STRING = "http://192.168.0.20:7001/com.henrique.rest/api/v1/status/pro_filtro?pro_nome=";
public FiltraProduto(ConsultaConcluidaFiltroProdutoListener listener) {
this.listener = listener;
}
private List<String> InterpretaResultado(String resultado) throws JSONException {
JSONObject object = new JSONObject(resultado);
JSONArray jsonArray = object.getJSONArray("produto");
//JSONObject jsonProduto = jsonArray.getJSONObject(0);
// String id = jsonProduto.getString("pro_id");
//proId = id;
List<Object> listaNomes = new ArrayList<>();
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonProdutoInfo = jsonArray.getJSONObject(i);
String proNome= jsonProdutoInfo.getString("pro_nome");
double proPreco = jsonProdutoInfo.getDouble("pro_preco");
double proSdAtual = jsonProdutoInfo.getDouble("pro_sdAtual");
listaNomes.add(i, proNome);
listaNomes.add(i, proPreco);
listaNomes.add(i, proSdAtual);
}
List<String> strings = new ArrayList<String>();
for (Object o : listaNomes) {
strings.add(o != null ? o.toString() : null);
}
return strings;
}
private String ConsultaServidor() throws IOException {
InputStream is = null;
try {
URL url = new URL(URL_STRING);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setConnectTimeout(10000);
conn.setReadTimeout(15000);
conn.setRequestMethod("GET");
conn.setDoInput(true);
conn.connect();
conn.getResponseCode();
is = conn.getInputStream();
Reader reader = null;
reader = new InputStreamReader(is);
char[] buffer = new char[2048];
reader.read(buffer);
return new String(buffer);
} finally {
if (is != null) {
is.close();
}
}
}
#Override
protected List<String> doInBackground(String... params) {
try {
String resultado = ConsultaServidor();
return InterpretaResultado(resultado);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(List<String> result) {
listener.onConsultaConcluida(result);
super.onPostExecute(result);
}
public interface ConsultaConcluidaFiltroProdutoListener {
void onConsultaConcluida(List<String> result);
}
}
In the URL_STRING I need to pass the param at pro_nome=?
Here I get the item text. This is in my Fragment that has the List View:
public String retornaParam(String param){
return param;
}
#Override
public void onConsultaConcluida(List<String> result) {
final ListView listaProdutos = (ListView) getView().findViewById(R.id.listaprodutos);
ArrayAdapter arrayAdapter = new ArrayAdapter<>(getView().getContext(),android.R.layout.simple_list_item_1, result);
listaProdutos.setAdapter(arrayAdapter);
listaProdutos.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parentAdapter, View view, int position,
long id) {
String nomeProduto = listaProdutos.getItemAtPosition(position).toString();
retornaParam(nomeProduto);
Intent intent = new Intent(getActivity(), DetalhesProdutoActivity.class);
//intent.putExtra("pro_nome", listaProdutos.getItemAtPosition(position).toString());
startActivity(intent);
}
});
}
I get the text and store it in param from the retornaParam method.
Does somebody know how to do it?
If you need more information, just let me know.
You pass in params to an AsyncTask using:
YourAsyncTask.execute(yourview.getText(), "and", "more", "params");
You can then access them in
#Override
protected String doInBackground(String... params) {
URL_STRING += params[0];
...
Just add the following code before sending executing your httpClient:
URL_STRING + = textInsideYourTextView;
It should work, just avoid to manipulate your ui elements outside your UI thread.

Read text file from web

I recover my text file distant, my text contains number one "1". I tried to convert my text "1"(char)to int, but it is giving error. I used method Integer.parseInt(String)
this is my code:
MainActivity.java
package mypackage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import android.app.Activity;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.Bundle;
import android.widget.TextView;
public class MainActivity extends Activity {
PackageInfo pinfo;
String contentFichier;
TextView txt;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recoverContentTextFile();
txt = (TextView) findViewById(R.id.txt);
try {
pinfo = getPackageManager().getPackageInfo(getPackageName(), 0);
} catch (NameNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//Here error
int i = Integer.parseInt(contentFichier);
}
public void recoverContentTextFile() {
new Thread() {
#Override
public void run() {
String path ="my_url_text_file";
URL u = null;
try {
u = new URL(path);
HttpURLConnection c = (HttpURLConnection) u.openConnection();
c.setRequestMethod("GET");
c.connect();
InputStream in = c.getInputStream();
final ByteArrayOutputStream bo = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
in.read(buffer); // Read from Buffer.
bo.write(buffer); // Write Into Buffer.
runOnUiThread(new Runnable() {
#Override
public void run() {
contentFichier = bo.toString();
try {
bo.close();
} catch (IOException e) {
e.printStackTrace();
}
}
});
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (ProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}.start();
}
}
thank you in advance.
First of all it's not a good idea at all to use threads in the way you're implementing in your method recoverContextTextFile. What happens if the user rotate the device and the petition takes 8 minutes to complete? You have created a memory leak!
The second thing as you have created a thread the variable contentFichier will be sometimes null (because recoverContextTextFile does create a thread) and calling the Integer.parseInt(contentFichier);will raise an Exception.
For this case I think that it's better to use an AsyncTask (which I highly dislike and taking care of not leaking the activity when rotation occurs), do the petition in the onBackground method and in the method onPostExecute call the Integer.parseInt(contentFichier);.
I recommend reading this tutorial by Lars Vogel as it explains a lot about background processing.
The problem here is probably that you are trying to convert the String before the thread has finished. And also, Android has a better way than Threads to handle most (simple) background tasks, the AsyncTask. You could do something like this:
public class MainActivity extends Activity {
PackageInfo pinfo;
String contentFichier;
TextView txt;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Setup your activity here
new ContentFetcher().execute("http://......");
}
private class ContentFetcher extends AsyncTask<String, Void, String>{
#Override
protected String doInBackground(String... params) {
String stringResponse = null;
try{
HttpResponse httpResponse = new DefaultHttpClient().execute(new HttpGet(params[0]));
stringResponse = EntityUtils.toString(httpResponse.getEntity());
} catch (IOException ignored) {
}
return stringResponse;
}
#Override
protected void onPostExecute(String s) {
//DO something with the response here - maybe test if the s variable is indeed an integer
int i = Integer.parseInt(s);
}
}
}
To execute the task run:
new ContentFetcher().execute("http://whatever.com/mytext.txt");
Add log statement to show the value of the contentFichier:
Log.i("contentFichier", "["+contentFichier+"]"
You will see which content is being parsed. Maybe there is a whitespace on the beginning or the end. Also the server may be returning wrong value or empty string.

How to reuse data from a JSONArray which got data in onPostExecute

this is my code for getting data from a PHP site into a ListView.
package be.pressd.arrangementen;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
public class MainActivity extends Activity implements OnClickListener{
Button fetch;
EditText et;
String aantalPersonen;
private ListView lv;
private ArrayAdapter<String> listAdapter ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
fetch = (Button) findViewById(R.id.fetchButton);
et = (EditText) findViewById(R.id.aantalPersonen);
// Find the ListView resource.
lv = (ListView) findViewById(R.id.arrangementenLijst);
listAdapter = new ArrayAdapter<String>(this, R.layout.line_row);
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//Toast.makeText(getApplicationContext(), "Click nummer " + position, Toast.LENGTH_LONG).show();
String arrangement = (String) lv.getItemAtPosition(position);
// Launching new Activity on selecting single List Item
Intent i = new Intent(getApplicationContext(), ArrangementItem.class);
// sending data to new activity
i.putExtra("arrangement", arrangement);
startActivity(i);
}
});
fetch.setOnClickListener(this);
}
class task extends AsyncTask<String, String, Void>
{
private ProgressDialog progressDialog = new ProgressDialog(MainActivity.this);
InputStream is = null ;
String result = "";
protected void onPreExecute() {
progressDialog.setMessage("Fetching data...");
progressDialog.show();
progressDialog.setOnCancelListener(new OnCancelListener() {
#Override
public void onCancel(DialogInterface arg0) {
task.this.cancel(true);
}
});
}
#Override
protected Void doInBackground(String... params) {
String url_select = "http://mywebsite/thephpform.php?aantpers=" + aantalPersonen;
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url_select);
ArrayList<NameValuePair> param = new ArrayList<NameValuePair>();
try
{
httpPost.setEntity(new UrlEncodedFormEntity(param));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
//read content
is = httpEntity.getContent();
} catch (Exception e) {
Log.e("log_tag", "Error in http connection "+e.toString());
}
try {
BufferedReader br = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = "";
while((line=br.readLine())!=null)
{
sb.append(line+"\n");
}
is.close();
result=sb.toString();
} catch (Exception e) {
Log.e("log_tag", "Error converting result "+e.toString());
}
return null;
}
protected void onPostExecute(Void v) {
try
{ listAdapter.clear();
JSONArray Jarray = new JSONArray(result);
for(int i=0; i < Jarray.length(); i++)
{
JSONObject Jasonobject = null;
Jasonobject = Jarray.getJSONObject(i);
String name = Jasonobject.getString("naam");
listAdapter.add(name);
}
this.progressDialog.dismiss();
lv.setAdapter( listAdapter);
} catch (Exception e) {
Log.e("log_tag", "Error parsing data "+e.toString());
}
}
}
#Override
public void onClick(View v) {
switch(v.getId()) {
case R.id.fetchButton :
aantalPersonen = et.getText().toString();
if (aantalPersonen.trim().equals("")) {
Toast.makeText(this, "Gelieve het aantal personen in te geven", Toast.LENGTH_SHORT).show();
return;
}
else
{
new task().execute();
break;
}
}
}
}
It is my first Android code ever, so besides my question it is possible that this code can be made better.
What I would like to do is to show ALL data, nicely, which was gotten from the website. But, as a ListView can not contain the ID and other data, I'm wondering if I can reuse the data in the JSONObject to be shown in next screen (on click of ListView item) ?
Greetings and thanks in advance,
Davy
Create variables for which you want to store information and loop through JsonArray and get each JsonObject and parse/extract information that you need and store it in variables.
here is sample code to iterate JsonArray //Here response is JsonArray
Create Simple class like
public class PersonInfo{
String name,address; //Create variables of your requirement.
//Add Getter Setter Methods for these variables
}
//End of class PersonInfo
ArrayList<PersonInfo> persons = new ArrayList<PersonInfo>();
PersonInfo person;
JSONObject product;
try
{
for (int j = 0; j < response.length(); j++)
{
person = new Person();
product = response.getJSONObject(j);
person.name = product.getString("JSON_KEY_NAME"); //like these assign values to each variable of PersonInfo class
//Other values initialization
}
persons.add(person); // Add PersonInfo object to ArrayList
}
catch (Exception e)
{
e.printStackTrace();
}
something like that .
you can get json values upon your requirments.
This is just sample code .
You could
save the JSON and parse it again later (you would have to do a lot of parsing)
save the data you parse from the json
in sharedpreferences (only if small amount of data)
in a local sqlite db (probably cleanest approach with best user experience, but a lot of work since you have to create a class that does all the db CRUD operations)
It depends on your data. For user preferences I would use SharedPreferences, for larger amounts a local DB. Also you could create some objects to store the data you need, maybe as signletons or something, and parse the stored JSONs everytime you start the app.
See the google docs on data storage for reference.
To save data you are getting in background task you have to use shared preferences.
Refer this link to get details about shared preferences.
To pass data to next page you have to use following code :
Intent intent = new Intent( currentActivity.this, NextActivity.class);
intent.putExtra("key", "value");
startActivity(intent);
On nextActivity.java add following code inside onCreate()
Intent currentPageIntent = getIntent();
String strValue = currentPageIntent.getStringExtra("key");
If you are having any other data type than string you have to use other method instead of getStringExtra()
To get id of item clicked, you can use following code :
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
try {
JSONArray jsonArray = new JSONArray(jsonData);
if (jsonArray != null) {
for (int i = 0; i < jsonArray.length(); i++) {
if (i == id) {
//Add your code here
}
}
}
} catch (Exception e) {
e.printStackTrace();
} finally { }
}
});
Note that you have to process jsonData on your own. This is just sample code I used in one of my porjects.

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