AsyncTask returns null in OnPostExecute - android

I'm trying to get text from a .txt located on a server to a string (feed_str)
My code:
public class getFeedData extends AsyncTask<String, Integer, String>
{
#Override
protected String doInBackground(String... params)
{
String feed_str = null;
try
{
// Create a URL for the desired page
URL url = new URL("http://www.this.is/a/server/file.txt");
// Read all the text returned by the server
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
while ((feed_str = in.readLine()) != null)
{
// str is one line of text; readLine() strips the newline character(s)
}
in.close();
}
catch (MalformedURLException e)
{
System.out.println("AsyncError: " + e);
}
catch (IOException e)
{
System.out.println("AsyncError: " + e);
}
catch (NullPointerException e)
{
System.out.println("AsyncError: " + e);
}
return feed_str;
}
#Override
protected void onPostExecute(String feed_str)
{
super.onPostExecute(feed_str);
System.out.println("onPostExecute " + feed_str);
}
With this code the logcat should output something like: "onPostExecute text from server" but instead of that it outputs "onPostExecute null"
Any ideas how to fix?
Btw: The url has been checked with a browser and the text was displayed so the url isn't the problem.

This loop doesn't exit until feed_str == null. So, the last value of it is null, which is what you return.
while ((feed_str = in.readLine()) != null)
{
// str is one line of text; readLine() strips the newline character(s)
}
You need to keep a "total" String also, if that's what you want to return.
String entireFeed = "";
while ((feed_str = in.readLine()) != null)
{
entireFeed += feedStr + "\n";
// whatever else you're doing
}
...
return entireFeed;

Related

How to get Jsonobject readable to textview?

I am so beginner about Json. I am trying to understand example on the internet. So that I am doing a translater for myself(Yandex translater). But I have problem I copied and pasted source cod to my project. To making When I clicked my button , Text will be my textview(being translated) Now I cannot get translated string for my textview.How can I get it ?
My TranslatorBackgroundTask AsyncTask (it is not inner class) :
TranslatorBackgroundTask(Context ctx){
this.ctx = ctx;
}
#Override
protected String doInBackground(String... params) {
//String variables
String textToBeTranslated = params[0];
String languagePair = params[1];
String jsonString;
try {
//Set up the translation call URL
String yandexKey =
String yandexUrl = "https://translate.yandex.net/api/v1.5/tr.json/translate?key=" + yandexKey
+ "&text=" + textToBeTranslated + "&lang=" + languagePair;
URL yandexTranslateURL = new URL(yandexUrl);
//Set Http Conncection, Input Stream, and Buffered Reader
HttpURLConnection httpJsonConnection = (HttpURLConnection) yandexTranslateURL.openConnection();
InputStream inputStream = httpJsonConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
//Set string builder and insert retrieved JSON result into it
StringBuilder jsonStringBuilder = new StringBuilder();
while ((jsonString = bufferedReader.readLine()) != null) {
jsonStringBuilder.append(jsonString + "\n");
}
//Close and disconnect
bufferedReader.close();
inputStream.close();
httpJsonConnection.disconnect();
//Making result human readable
String resultString = jsonStringBuilder.toString().trim();
//Getting the characters between [ and ]
resultString = resultString.substring(resultString.indexOf('[')+1);
resultString = resultString.substring(0,resultString.indexOf("]"));
//Getting the characters between " and "
resultString = resultString.substring(resultString.indexOf("\"")+1);
resultString = resultString.substring(0,resultString.indexOf("\""));
Log.d("Translation Result:", resultString);
return jsonStringBuilder.toString().trim() ;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onPostExecute(String result) {
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
My MainActivity :
cevir_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String yazı_string = yazı_EditText.getText().toString();
// trans(yazı_string,language);
String languagePair = "en-fr";
Translate(yazı_string,languagePair);
}
});
private void Translate(String textToBeTranslated, String languagePair) {
TranslatorBackgroundTask translatorBackgroundTask= new TranslatorBackgroundTask(context);
AsyncTask<String, Void, String> translationResult = translatorBackgroundTask.execute(textToBeTranslated,languagePair);
try {
String translationResults = translatorBackgroundTask.execute(textToBeTranslated, languagePair).get();
cevirilmis_tTextView.setText(translationResults);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
Log.d("Translation Result", String.valueOf(translationResult));
}
You could simply get the string from the AsyncTask:
String translationResult = translatorBackgroundTask.execute(textToBeTranslated, languagePair).get();
However this approach defeats the point of using an AsyncTask as you will end up blocking the UI thread as you wait for the result from .get(). Instead you should use a callback like this

Informationparsing from URL-Request not working / Didn't found TextView

i need your help. I want to send a URL Request, get response and create a JSON Object. My first try was totally wrong. Now I found a tutorial and made a new try.
My Activity looks like:
public class Patienten extends Activity {
//Beacon Elemente
private String UUID;
private String Major;
private String Minor;
private TextView output;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_patienten);
output = (TextView) findViewById(R.id.output);
UpdateBeaconInformation();
Button cmdHit = (Button) findViewById(R.id.cmd_hit);
cmdHit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new JSONTask().execute("//http://kusber-web.de/JsonTest.txt");
}
});
setTitle(Surname + ", " + FirstName);
// output.setText(output.getText().toString() + "Gefundener Patient:\n" + "Name: " + Surname + ", " + FirstName + "\nGeb.-Dat: " + Birthdate);
}
Then I created a new Java Class and built an asyncTask with it. But I can't access to the textview output in onPostExecute to update it.
public class JSONTask extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... urls) {
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
//http://kusber-web.de/JsonTest.txt
//http://nilsbenning.selfhost.me/PatientFinder.php?beacon_comID=5181f8a3-7354-46ac-b22d-952ec395ab06&beacon_major=12&beacon_minor=249
URL url = new URL(urls[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line;
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
return buffer.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
output.setText(result);
}
}
What is my mistake? Why I can't access to it? I saw it as a solution here but didn't get it to work:
https://stackoverflow.com/a/12252717/5743912
Hope you can help me now! :)
You probably want to fix this (remove leading slashes):
new JSONTask().execute("//http://kusber-web.de/JsonTest.txt");
In your JSONTask you can reference members of Patienten by using Patienten.this. So in onPostExecute you should change this:
output.setText(result);
to:
Patienten.this.output.setText(result);

d How can I use progress bar while fetching data from database?

I'm really bad at googling things I want so I decided to ask here. My question is is it possible to show a progress bar while fetching the data from the database? I'm using the typical code when fetching data(Pass value to php and the php will do the query and pass it again to android)
Edit(I have tried adding proggressdialog but the problem now is the loaded data will appear first before the progress dialog here's my AsyncTask code)
public class getClass extends AsyncTask<String, Void, String> {
public getClass()
{
pDialog = new ProgressDialog(getActivity());
}
URLConnection connection = null;
String command;
Context context;
String ip = new returnIP().getIpAddresss();
String link = "http://" + ip + "/android/getClass.php";//ip address/localhost
public URLConnection getConnection(String link) {
URL url = null;
try//retrieves link from string
{
url = new URL(link);
} catch (MalformedURLException e) {
e.printStackTrace();
}
URLConnection connection = null;
try//opens the url link provided from the "link" variable
{
connection = url.openConnection();
} catch (IOException e) {
e.printStackTrace();
}
connection.setDoOutput(true);
return connection;
}
public String getResult(URLConnection connection, String logs) {
//this is the functions that retrieves what the php file echoes
//everything that php throws, the phone receives
String result = "";
OutputStreamWriter wr = null;
try {
wr = new OutputStreamWriter(connection.getOutputStream());//compiles data to be sent to the receiver
} catch (IOException e) {
e.printStackTrace();
}
try {
wr.write(logs);
} catch (IOException e) {
e.printStackTrace();
}
try {
wr.flush();//clears the cache-esque thingy of the writer
} catch (IOException e) {
e.printStackTrace();
}
BufferedReader reader = null;
try {
reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
} catch (IOException e) {
e.printStackTrace();
}
StringBuilder sb = new StringBuilder();
String line = null;
//Read server response
try {
while ((line = reader.readLine()) != null) {
sb.append(line);
}
} catch (IOException e) {
e.printStackTrace();
}
result = sb.toString();
return result;
}
#Override
protected void onPreExecute() {
pDialog.setMessage("Loading...");
pDialog.show();
}
#Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
String result = "";
//Toast.makeText(View_Classes.this, "ako n una", Toast.LENGTH_LONG).show();
try {
//first data sent is sent in command
command = (String) arg0[0];//it's in array, because everything you input here is placed in arrays
//Toast.makeText(View_Classes.this, "andtio n me", Toast.LENGTH_LONG).show();
if (command == "getCourses") {
connection = getConnection(link);
String logs = "";
logs = "&command=" + URLEncoder.encode(command, "UTF-8");
logs += "&username=" + URLEncoder.encode(username, "UTF-8");
result = getResult(connection, logs);
} else if (command == "getSections") {
connection = getConnection(link);
String logs = "";
logs = "&command=" + URLEncoder.encode(command, "UTF-8");
logs += "&username=" + URLEncoder.encode(username, "UTF-8");
logs += "&course=" + URLEncoder.encode(course, "UTF-8");
result = getResult(connection, logs);
}
return result;
} catch (Exception e) {
return result;
}
}
#Override
protected void onPostExecute(String result) {//this is going to be the next function to be done after the doInBackground function
// TODO Auto-generated method stub
if (pDialog.isShowing()) {
pDialog.dismiss();
}
if (result.equalsIgnoreCase(""))//if there's nothing to return, the text "No records" are going to be thrown
{
} else //Array adapter is needed, to be a place holder of values before passing to spinner
{
}
}
}
Have you tried using an AsyncTask?
You can show your progress bar on the preExecute method and then hide it on postExecute. You can do your querying inside the doInBackground method.
In addition to what #torque203 pointed, I would suggest you to check
http://developer.android.com/reference/android/os/AsyncTask.html#onProgressUpdate(Progress...)
this method was created for that purpose, showing progress to the user.
From developers docs:
private class DownloadFilesTask extends AsyncTask<URL, Integer, Long> {
#Override
protected void onPreExecute() {
//show progress bar here
}
protected Long doInBackground(URL... urls) {
//Pass value to PHP here
//get values from your PHP
}
protected void onPostExecute(Long result) {
//Here you are ready with your PHP value. Dismiss progress bar here.
}
}
public void onPreExecute() {
Progress Dialog pDialog = new ProgressDialog(this);
pDialog.setMessage("Loading...");
pDialog.show();
}
public void doInBackground() {
//do your JSON Coding
}
public void onPostExecute() {
Progress Dialog pDialog = new ProgressDialog(this);
pDialog.setMessage("Loading...");
pDialog.show();
}
public URLConnection getConnection(String link) {
URL url = null;
try//retrieves link from string
{
url = new URL(link);
} catch (MalformedURLException e) {
e.printStackTrace();
}
URLConnection connection = null;
try//opens the url link provided from the "link" variable
{
connection = url.openConnection();
} catch (IOException e) {
e.printStackTrace();
}
connection.setDoOutput(true);
return connection;
}
public String getResult(URLConnection connection, String logs) {
//this is the functions that retrieves what the php file echoes
//everything that php throws, the phone receives
String result = "";
OutputStreamWriter wr = null;
try {
wr = new OutputStreamWriter(connection.getOutputStream());//compiles data to be sent to the receiver
} catch (IOException e) {
e.printStackTrace();
}
try {
wr.write(logs);
} catch (IOException e) {
e.printStackTrace();
}
try {
wr.flush();//clears the cache-esque thingy of the writer
} catch (IOException e) {
e.printStackTrace();
}
BufferedReader reader = null;
try {
reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
} catch (IOException e) {
e.printStackTrace();
}
StringBuilder sb = new StringBuilder();
String line = null;
//Read server response
try {
while ((line = reader.readLine()) != null) {
sb.append(line);
}
} catch (IOException e) {
e.printStackTrace();
}
result = sb.toString();
return result;
}
public class getClass extends AsyncTask<String, Void, String> {
#Override
protected void onPreExecute() {
pDialog.setMessage("Loading...");
pDialog.show();
URLConnection connection = null;
String command;
Context context;
String ip = new returnIP().getIpAddresss();
String link = "http://" + ip + "/android/getClass.php";//ip address/localhost
}
#Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
String result = "";
//Toast.makeText(View_Classes.this, "ako n una", Toast.LENGTH_LONG).show();
try {
//first data sent is sent in command
command = (String) arg0[0];//it's in array, because everything you input here is placed in arrays
//Toast.makeText(View_Classes.this, "andtio n me", Toast.LENGTH_LONG).show();
if (command == "getCourses") {
connection = getConnection(link);
String logs = "";
logs = "&command=" + URLEncoder.encode(command, "UTF-8");
logs += "&username=" + URLEncoder.encode(username, "UTF-8");
result = getResult(connection, logs);
} else if (command == "getSections") {
connection = getConnection(link);
String logs = "";
logs = "&command=" + URLEncoder.encode(command, "UTF-8");
logs += "&username=" + URLEncoder.encode(username, "UTF-8");
logs += "&course=" + URLEncoder.encode(course, "UTF-8");
result = getResult(connection, logs);
}
return result;
} catch (Exception e) {
return result;
}
}
#Override
protected void onPostExecute(String result) {//this is going to be the next function to be done after the doInBackground function
// TODO Auto-generated method stub
if (pDialog.isShowing()) {
pDialog.dismiss();
}
if (result.equalsIgnoreCase(""))//if there's nothing to return, the text "No records" are going to be thrown
{
} else //Array adapter is needed, to be a place holder of values before passing to spinner
{
}
}
}

Android - Ignoring Catch Clause?

Can "catch" clause be ignored? I have this code and what I wanna do is to scan all words containing a specific string and store them in String res.
But the code I have now does not iterate through the loop because it stops when the "catch" clause interrupts. Is there a way to ignore catch clause and just let the "try" continue the loop until it reaches the end of file?
String delimiter = " - ";
String[] del;
String res = new String();
if(curEnhancedStem.startsWith("a"))
{
InputStream inputStream = getResources().openRawResource(R.raw.definitiona);
try {
BufferedReader in = new BufferedReader(new InputStreamReader(inputStream));
String s = in.readLine();
while(s != null)
{
s = in.readLine();
del = s.split(delimiter);
if (del[0].contains(curEnhancedStem))
{
res = res + s + "\n\n";
}
}
return res;
}
catch (Exception e) {
// nothing to do here
}
}
If you really want it to continue on the inner loop even after an error you could put another try block in there.
String delimiter = " - ";
String[] del;
String res = new String();
if(curEnhancedStem.startsWith("a"))
{
InputStream inputStream = getResources().openRawResource(R.raw.definitiona);
try {
BufferedReader in = new BufferedReader(new InputStreamReader(inputStream));
String s = in.readLine();
while(s != null)
{
try {
s = in.readLine();
del = s.split(delimiter);
if (del[0].contains(curEnhancedStem))
{
res = res + s + "\n\n";
}
}
catch (Exception e) {
// Error in string processing code (as opposed to IO) - Don't care... Continue
}
}
}
return res;
}
catch (Exception e) {
// nothing to do here
}
}
Another idea is to use more specific Exceptions - not just the general catch all Exception
I thing you must be getting exception inside while, So try this.
try {
BufferedReader in = new BufferedReader(new InputStreamReader(inputStream));
String s = in.readLine();
while(s != null)
{
try{
s = in.readLine();
del = s.split(delimiter);
if (del[0].contains(curEnhancedStem))
{
res = res + s + "\n\n";
}
} catch(Exception e){
// Do Something
}
}
return res;
}
catch (Exception e) {
// nothing to do here
}
}
If you get exception it would be handled inside the loop but your loop will continue.
There is nothing in your catch clause. Try to add something like below for while loop(keep it in try block) as well to find out which exception u got:
catch(Exception e)
{
Log.e("Exception here: "+ e.getMessage());
}

getting the html source code with a url in an android application

I was trying to write some codes that takes in a url from the user and after which when the submit button is clicked, I will take the url and make a call and retrieve the html source code from the page. However, I have gotten a exception of the following:
W/System.err(14858): android.os.NetworkOnMainThreadException
W/System.err(14858): at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1077)
It seems that for android 3.0 the platform that I am trying to development on doesn't allow me to use the network resources on the main method. I understand that there are methods such as running it in the background or use the async method should work, but can anyone guide me on this? I'm not too sure on how to go about it. I'm new to programming.
Thanks in advance.
Below is my current code, on the onclick method:
String htmlCode = "";
try {
URL url = new URL("http://www.google.com");
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
htmlCode += inputLine;
Log.d(LOG_TAG, "html: " + inputLine);
}
in.close();
} catch (Exception e) {
e.printStackTrace();
Log.d(LOG_TAG, "Error: " + e.getMessage());
Log.d(LOG_TAG, "HTML CODE: " + htmlCode);
}
You could use a Runnable or Thread, but probably the most idiomatic Android way to do this is to use an AsyncTask.
new AsyncTask<String, Void, String>(){
#Override
protected String doInBackground(String... urlStr){
// do stuff on non-UI thread
StringBuffer htmlCode = new StringBuffer();
try{
URL url = new URL(urlStr[0]);
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
String inputLine;
while ((inputLine = in.readLine()) != null) {
htmlCode += inputLine;
Log.d(LOG_TAG, "html: " + inputLine);
}
in.close();
} catch (Exception e) {
e.printStackTrace();
Log.d(LOG_TAG, "Error: " + e.getMessage());
Log.d(LOG_TAG, "HTML CODE: " + htmlCode);
}
return htmlCode.toString();
}
#Override
protected void onPostExecute(String htmlCode){
// do stuff on UI thread with the html
TextView out = (TextView) findViewById(R.id.out);
out.setText(htmlCode);
}
}.execute("http://www.google.com");

Categories

Resources