Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I have this code here which should get the information I need to generate strings for each line of text on the TXT document but I am unsure where I have to go from here and whether my app is even getting the information. The strings it needs to generate will be going into a TextView just if that information is needed but I am very unsure where I go from here as I have no knowledge of Jsoup and have been told that this is the easiest way of getting the information from the lines of text into strings but I just need help on how to get it there. The code that is being used is below:
public void updatebutton(View v){
new SyncTask().execute();
Toast.makeText(MainActivity.this, "Updating", Toast.LENGTH_LONG).show();
}
private class SyncTask extends AsyncTask<String, Void, String>{
#Override
protected String doInBackground(String... params) {
Document doc = null;
String returnValue ="";
String baseWebPage = "http://nowactivity.webs.com/teststring.txt";
for(int i = 0; i< params.length; i++){
try {
doc = Jsoup.connect(
baseWebPage)
.get();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Log.i("DOC", "The line " + doc.toString());
}
return returnValue;
}
}
I'm assuming that when you run this code you get every line of teststring.txt printed in your logcat?
If that's the case, then you could change the return type of SyncTask from String to something like ArrayList or even a String array, then add each doc.toString(); to that list using your for loop, then return it.
From there you can access that array of strings and populate your TextViews accordingly.
You could also use Jsoup to cache the text file locally on the user's SD card, then you could populate your TextViews from there without having to reconnect every time.
Edit: Instead of using Jsoup, try using this:
private class SyncTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
String returnValue = "";
String u = "http://nowactivity.webs.com/teststring.txt";
URL url;
InputStream stream;
InputStreamReader streamReader;
BufferedReader reader;
String str;
try {
System.out.println("Reading URL: " + u);
url = new URL(u);
stream = url.openStream();
streamReader = new InputStreamReader(stream);
reader = new BufferedReader(streamReader);
do {
str = reader.readLine();
if (str != null)
System.out.println(str);
} while (str != null);
} catch (MalformedURLException e) {
System.out.println("Invalid URL");
} catch (IOException e) {
System.out.println("Can not connect");
}
return returnValue;
}
}
That would also work inside an AsyncTask, with that you could create the same ArrayList and return it, instead of trying to use Jsoup.
Related
This is a android quiz app code snippet which load the question from text file.
I want to shuffle the question and answer after every next click so how can i implement random function ?
https://github.com/gitssk/quizfun/blob/master/src/ssk/quizfun/QuizFunActivity.java
https://github.com/gitssk/quizfun/blob/master/res/raw/questions.txt
private void loadQuestions() throws Exception {
try {
InputStream questions = this.getBaseContext().getResources()
.openRawResource(R.raw.questions);
bReader = new BufferedReader(new InputStreamReader(questions));
StringBuilder quesString = new StringBuilder();
String aJsonLine = null;
while ((aJsonLine = bReader.readLine()) != null) {
quesString.append(aJsonLine);
}
Log.d(this.getClass().toString(), quesString.toString());
JSONObject quesObj = new JSONObject(quesString.toString());
quesList = quesObj.getJSONArray("Questions");
Log.d(this.getClass().getName(),
"Num Questions " + quesList.length());
} catch (Exception e){
} finally {
try {
bReader.close();
} catch (Exception e) {
Log.e("", e.getMessage().toString(), e.getCause());
}
}
}
https://github.com/gitssk/quizfun/blob/master/src/ssk/quizfun/QuizFunActivity.java
I will refrain from posting much code because I think you should attempt it on your own. It is seriously not that tough. I will give you an approach though.
You have quesList = quesObj.getJSONArray("Questions");. So quesList is the list of questions that is a JSONArray. You want to shuffle this. Just do this:
Get the length of the quesList array. Let's call it len.
Create a simple arrayList called quesOrder containing integers 0 to len.
List<Integer> quesOrder = new ArrayList<>();
for (int i = 0; i <= len; i++)
{
quesOrder.add(i);
}
Once you have the quesOrder array. Just do Collections.shuffle(quesOrder);. Now when you get questions from your quesList array, just get the index from quesOrder list. And you will have a randomized selection. Put it together in a function for convenience.
I know, there are a lot of questions on this, but no answer helped me.
Trying to parse football news from one famous ukrainian portal and put to my listview.
I parsed "news-feed" class:
class ParseTitle extends AsyncTask<Void, Void, HashMap<String, String>>{
#Override
protected HashMap<String, String> doInBackground(Void... params) {
HashMap<String, String> hashMap = new HashMap<>();
try {
Document document = Jsoup.connect("http://football.ua/england.html").get();
Elements elements = document.select(".news-feed");
for (Element element : elements){
Element element1 = element.select("a[href]").first();
hashMap.put(element.text(), element1.attr("abs:ahref"));
}
} catch (IOException e) {
e.printStackTrace();
}
return hashMap;
}
}
Use
Elements elements = document.select("article.news-feed");
Instead of
Elements elements = document.select(".news-feed");
EDIT: comparing my code to yours, I see good differences, firstly and I think more important, you accumulate the read values in a HashMap, I in a StringBuffer. Then I connect and go this way:
try {
doc = Jsoup.connect("http://football.ua/england.html").userAgent("yourPersonalizedUA").timeout(0).ignoreHttpErrors(true).get();
topicList = doc.select("article.news-feed");
for (Element topic : topicList) {
myString += topic.html();
}} catch (IOException e) { System.out.println("io - "+e); }
buffer.append(myString);
Then, if everything worked
return buffer.toString();
Presuming you've already stated at the beggining:
private Document doc;
private String myString;
private StringBuffer buffer;
private Elements topicList;
Not shure if this helps, maybe can lead into a new perspective. Have you succeeded parsing another page with your code?
I'm thinking about making my first android app, It'd be about movies, I found an excellent data source, it is "http://www.google.com/movies?" but I wanted to know how could I extract this information and put it in my app,
I've searched but I don't know which is the optimal way to do this? does google have an API for this? is that what I want? is it better with the source code?what could I read or see to learn to do this?
thanks a lot guys, Is my first time as well programming retrieving information from the cloud,
cheers
Yup. Here is one way to do it.
First, you need to find the source of the SQL. The Yahoo Developer Console is a great place to look for this sort of stuff. It has EVERYTHING. The way these resources work is that you have a long link, like this....
developer.yahoo.com/blah/this . . . &q=KEYWORD_HERE+blah/ . . .
To access the information you are looking for, you stick whatever the correct keyword is where "KEYWORD_HERE" is, and the link will give you info in SQL format. I'll be doing the example as a stocks app.
First you create an Activity and define both sides of your link as strings. It'll look a bit like this:
public class InfoActivity extends Activity {
String firstHalf = "http://query.yahooapis.com/v1/public/blahblahblah&q=";
String secondHalf = "+blah/blah&blah . . . ";
Then, in your onCreate, you'll need to start an aSync task to do the actual pulling and parsing:
protected void onCreate(Bundle bundle) {
super.onCreate(bundle);
setContentView(R.id.layout_name);
final String yqlURL = firstHalf + KEYWORD_HERE + secondHalf;
new MyAsyncTask().execute(yqlURL);
}
Then to define our MrAsyncTask:
private class MyAsyncTask extends AsyncTask<String, String, String>{
protected String doInBackground(String... args) {
try {
URL url = new URL(args[0]);
URLConnection connection;
connection = url.openConnection();
HttpURLConnection httpConnection = (HttpURLConnection)connection;
int responseCode = httpConnection.getResponseCode();
// Tests if responseCode == 200 Good Connection
if (responseCode == HttpURLConnection.HTTP_OK) {
InputStream in = httpConnection.getInputStream();
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document dom = db.parse(in);
Element docEle = dom.getDocumentElement();
NodeList nl = docEle.getElementsByTagName("nodeName1");
if (nl != null && nl.getLength() > 0) {
for (int i = 0 ; i < nl.getLength(); i++) {
//Parse the node here with getTextValue(n1, "Name of element")
//ex: String movieName = getTextValue(n1, "MovieName");
}
}
}
} catch (MalformedURLException e) {
Log.d(TAG, "MalformedURLException", e);
} catch (IOException e) {
Log.d(TAG, "IOException", e);
} catch (ParserConfigurationException e) {
Log.d(TAG, "Parser Configuration Exception", e);
} catch (SAXException e) {
Log.d(TAG, "SAX Exception", e);
}
finally {
}
return null;
}
I hope that gives you some idea of how to do this sort of thing. I'll go see if I can quickly spot a good resource on the yahoo apis to get the movie times at a certain location.
Good luck :) Let me know if you need anything clarified.
EDIT:
Looks like this is EXACTLY what you need (resource wise):
https://developer.yahoo.com/yql/console/?q=show%20tables&env=store://datatables.org/alltableswithkeys#h=select+*+from+google.igoogle.movies+where+movies%3D'68105'%3B
Check that out. Using that, your two halves of the link would be:
String firstHalf = "https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20google.igoogle.movies%20where%20movies%3D'"
String secondHalf = "'%3B&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys"
And then to get your final link, you would just do
String yqlURL = firstHalf + "ZIP CODE OF YOUR LOCATION" + secondHalf;
And you would have all of the movies playing near you returned!
Make your life a lot easier and choose the api that is right for you. Choose one of these:
http://www.programmableweb.com/news/52-movies-apis-rovi-rotten-tomatoes-and-internet-video-archive/2013/01/22
Make your decision not only based on the content, but also ease of use and documentation. Documentation is a biggy.
Good luck!
well i would rather advice you to use an TheMovieDB.com API it is simple and provides every info of movies.
This question already has answers here:
how to faster read text file to ArrayList on android
(2 answers)
Closed 9 years ago.
Here is the code of function:
public void loadTextFile(String textFileName, ArrayList<String> dictionary)
{
AssetManager assetManager = getAssets(); //files manager
//reader = public bufferedReader
//word = public String
//dictionary = public ArrayList<String>
//load file to buffer
try {
reader = new BufferedReader(new InputStreamReader(assetManager.open(textFileName)));
} catch (IOException e1) {
e1.printStackTrace();
}
word = " ";
//loop, save words from buffer to dictionary
while(word != null)
{
try {
word = reader.readLine();
} catch (IOException e) {
e.printStackTrace();
word = null;
}
if (word != null) {
dictionary.add(word);
}
}//end while
//buffer close
try {
reader.close();
} catch (IOException e1) {
e1.printStackTrace();
}
} //end function
If I try load small file <1MB, It works fine and rather fast.
If the files(partialy) are more than 1MB, but less than about 3MB, it works slow (4-6min).
If the files are bigger, it's not working, and I have information in emulator:
"The application app (process processing.test.app) has stopped unexpectedly. Please try again". I don't know what is wrong.
I try: pre-allocated ArrayList, load file to few ArrayList's, but still not working.
I will be grateful for any suggestions.
First off, word can become null somewhere along the file and the loop will exit (since you explicitly set word to null on an exception). Do you get a stack trace?
Try to move the code to a background process using AsyncTask AsyncTask
Execute on real device if you have one
Keep getting ArrayIndexOutOfBoundsException when trying to display a specific item form array list data displays fine in logcat but then after displaying throws exception at top please help is the code kind of new to android
public void loadData(){
InputStream file = ourContext.getResources().openRawResource(R.raw.cashpot);
BufferedReader reader = new BufferedReader(new InputStreamReader(file));
String line ="";
ArrayList<String> values = new ArrayList<String>();
try {
while((line = reader.readLine()) != null) {
values.add(line);
// String[] strings = line.split(",");
/*for(String s : strings) {
values.add(s);
}*/
}
reader.close();
//for(String s : values) Log.d("CSV Test", s);
for(int i = 0; i < values.size();i++){
String[] data = values.get(i).split(",");
Log.d("Test String",data[2] );
}
} catch (IOException e) {
e.printStackTrace();
}
}
Your some lines do not have comma(,)(or 1 comma) and you are trying to split them by comma and storing it in to data array. and you are accessing data[2] location. which might not been created that's why you are getting this exception.
There might not be a 3rd element in your array ,that is created after the split on ",".
You can print value of data before accessing data[2](that might not exist).
Or you can Debug your program and proceed step by step and monitoring the value of each variable.