Change the message of a ProgressDialog in AsyncTask - android

I have a ProgressDialog running in a AsyncTask.
I`m trying to achive that as soon as the Length of a buffer is bigger then lets say 10000, the message from the ProgressDialog changes.
Can somebody help me please, is this possible?
Thank you in advance.
#Override
protected void onProgressUpdate(Integer... progUpdate) {
if (progUpdate[0] >= 10000){
progress.setMessage("Informatie wordt opgehaald....");
}
}
The buffer is created in a AsyncTask doInBackGround:
try {
HttpResponse response = httpClient.execute(request);
System.out.println("Response: " + response.getEntity().getContentLength());
/******* READ CONTENT IN BUFFER *******/
InputStream inputStreamActivity = response.getEntity().getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStreamActivity));
StringBuilder sb = new StringBuilder();
String line = null;
int count = sb.length();
while ((line = reader.readLine()) != null) {
sb.append(line);
publishProgress(sb.length());
}
/******* CLOSE CONNECTION AND STREAM *******/
System.out.println(sb);
inputStreamActivity.close();
kpn = sb.toString();
httpClient.getConnectionManager().shutdown();
}

To change your dialog's message, you'll want to use the onProgressUpdate method of the AsyncTask and define the 2nd paramater of your AsyncTask as an Integer. The onProgressUpdate will look something like:
protected void onProgressUpdate(Integer... progUpdate) {
if (progUpdate[0] >= 10000){ // change the 10000 to whatever
progress.setMessage("The new message");
}
}
To call this, you'll want to update these lines in your doInBackground method of your AsyncTask:
while ((line = reader.readLine()) != null) {
sb.append(line);
publishProgress(sb.length());
}
And get rid of that Runnable. You don't need it. Take a look at the official android documentation for AsyncTask here: http://developer.android.com/reference/android/os/AsyncTask.html There's a great example for you on that page.

Related

I don't understand these codes

I'm making an android app for my final project at school.
I only know basic Java and I need to make my app connect to my mysql database.
So I followed this tutorial here with the get method:
https://www.tutorialspoint.com/android/android_php_mysql.htm
Aside from the php part and how it connects and execute the code what I don't understand is this line
StringBuffer sb = new StringBuffer("");
String line="";
while ((line = in.readLine()) != null) {
sb.append(line);
break;
}
in.close();
return sb.toString();
I tried to read this:
https://developer.android.com/reference/java/lang/StringBuffer.html
But I suck at English and reading that won't make me understand what StringBuffer do a bit. I only know that it returns something and it is converted to string type so I think it is the php result.
What I want to know is what does StringBuffer do in the tutorial above? Like they return the value of the php result or not?
And if they do can I use it like this? Because I tried to do like this but got a catch (Exception e) with e.getMessage is null
TextView text2 = (TextView) findViewById(R.id.textView);
text2.setText(sb.toString());
If they do not, how can I set the result of the php value to my textview?
StringBuffer is a way of building a String piece by piece. It is an alternate to manually concatenating strings like this:
String string3 = string0 + string1 + string2;
You would instead do.
stringBuffer.append(string0)
.append(string1)
.append(string2);
Therefore, all it is doing is taking the Strings from in line-by-line and combining it into one String.
Well mate, it depends what result you are expecting you can connect to database for example to send or get some data, and then you need a php file as well.
But the easiest way to connect to db is to use Volley or AsyncTask.
Analise these sample code, it is fully working (but you need a php file which connects with your request:
private class YourTask extends AsyncTask<Void, Void, String> {
#Override
protected String doInBackground(Void... voids) {
String strUrl = "http://YOUR_PLACE_ON_A_SERVER_WHERE_THE_PHP_FILE_IS.php";
URL url = null;
StringBuffer sb = new StringBuffer();
try {
url = new URL(strUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream iStream = connection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(iStream));
String line = "";
while ((line = reader.readLine()) != null) {
sb.append(line);
}
reader.close();
iStream.close();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return sb.toString();
}
//Here you can manage things you want to execute
}

OutOfMemory JSON Android

I'm trying to obtain an JSON answer type but is to big and at 50 MB Android Studio throw new Exception OutOfMemory
class MyClass extends AsyncTask<Void, Void, Void>
{
String result="";
#Override
protected Void doInBackground(Void... params){
HttpClient httpClient=new DefaultHttpClient();
String URL="http://82.79.121.114:1001/api/search/category/3,1,1";
try{
HttpGet httpGet = new HttpGet(URL);
httpGet.setHeader("Authorization", "Bearer " + AccesToken);
HttpResponse httpResponse=httpClient.execute(httpGet);
//Log.e("EROARE!!!!!!","EROARE!!!!!");
HttpEntity httpEntity=httpResponse.getEntity();
InputStream is=httpEntity.getContent();
result=convert(is);
}catch (Exception e){
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void aVoid){
Toast.makeText(MainActivity.this,result,Toast.LENGTH_SHORT).show();
if(result.length() == 0 || result == null)
{
Toast.makeText(MainActivity.this,result.Toast.LENGTH_SHORT).show();
if(result.length() == 0 || result == null)
{
Toast.makeText(MainActivity.this,"Nu merge!!!",Toast.LENGTH_SHORT).show();
}
}
public String convert(InputStream is) throws IOException {
BufferedReader reader = null;
StringBuffer buffer = new StringBuffer();
try {
reader = new BufferedReader(new InputStreamReader(is,"UTF-8"),8192);
int read;
char[] chars = new char[1024];
while ((read=reader.read(chars)) != -1)
buffer.append(chars, 0, read);
}
finally {
if (reader != null)
reader.close();
}
return buffer.toString();
}
Your JSON object is simply too large, as most of the devices do not have such big heap. If you own the server-side, you should change the response you send to the clients and make it few separate responses, handled in a sequence.
In addition, I recommend you to rethink why you send so much data at once. It will take a very long time to load even on an average internet connection.
If indeed the OutOfMemory problem is related with the size of the data returned by your REST service then you are doing it wrong both on server and client side. A mobile application should care about users data traffic and also about their battery so instead of loading the entire JSON in one shot maybe you can split it in pages and load only the first page first. Once the user is interested in more (maybe you are using a ListView there to show those categories) then you load the next page and so on. Please see the Endless List Patter for Android Here:
https://github.com/codepath/android_guides/wiki/Endless-Scrolling-with-AdapterViews

AsyncTask sanity check

I've been going over various Asynctask tutorials and examples, but I'm still a little confused. If I want to issue 3 web requests and return their response
like:
//example
String[] response = new String[3];
response[0] = webrequest("http://www.google.com"); //simple HTTP GET request
response[1] = webrequest("http://www.bing.com"); //simple HTTP GET request
response[2] = webrequest("http://www.aj.com"); //simple HTTP GET request
//sample results from request
response[0] = "blah";
response[1] = "arg";
response[2] = "meh";
To do this with an AsyncTask, would I need to implement 3 different ATs? Should I be using something else?
String[] response = new String[3];
webCreate sample = new webCreate();
try{
response[0] = sample.execute("http://www.google.com").get().toString();
response[1] = sample.execute("http://www.google.com").get().toString();
response[2] = sample.execute("http://www.google.com").get().toString();
}
catch (Exception sampleMsg)
{}
public class webCreate extends AsyncTask<String, String, String> {
}
protected String doInBackground(String... params) {
// String url=params[0];
String webRequestResponse = null; //the
// web request
BufferedReader in = new BufferedReader(
new InputStreamReader(con.getInputStream()));
String inputLine;
StringBuffer response = new StringBuffer();
while ((inputLine = in.readLine()) != null) {
response.append(inputLine);
}
return reponse;
}
I know I could access the response data by using .get(), but then my "Async" would become "sync" lol. I feel like I should be using something other than AsyncTask, but I have no idea what that is. Please help.
Your approach is okay, from doInBackground of your AsyncTask call a function that initiates the webrequests and wait for the result with . get(). Due to the fact, that the request are then, not running on the mainUi and blocking it, I see no problem in doing so.

Write JSON response to a text view

I am authenticating an external system via a REST API. The http authentication request is of the Basic Authorization form. The response is in JSON format.
I am running this code under an AsyncTask.
url The GET url of the API.
credentials is the authentication credentials. It is a string.
response is the text view.
getmessage is a string variable.
connection = (HttpURLConnection)new URL(url).openConnection();
connection.setRequestMethod("GET");
connection.setRequestProperty("Authorization", "Basic" + Base64.encode(credentials.getBytes(), Base64.DEFAULT ));
// I am reading the response here,
InputStreamReader in = new InputStreamReader(connection.getInputStream());
buf = new BufferedReader(in);
getmessage = buf.readLine();
// After making the request, I am updating the response to a text view on the UI thread
runOnUiThread(new Runnable() {
#Override
public void run() {
response.setText(getmessage);
}
});
I am unable to write the whole JSON data to the text view. I know that buf.readline returns the response till the end of a line. Right now I am only getting a part of the JSON response, "Not Authenticated:", but I need the whole response.
How do I update the whole JSON response to the text view (response)? If I loop the data using buf.readline in a loop then where can I use it? In which thread?
If there is anything unusual in my code. Please let me know.
I would suggest you to go trough AsyncTask
private class GetDataFromUrl extends AsyncTask<URL, Integer, String> {
protected String doInBackground(URL... urls) {
connection = (HttpURLConnection)new URL(url).openConnection();
connection.setRequestMethod("GET");
connection.setRequestProperty("Authorization", "Basic" + Base64.encode(credentials.getBytes(), Base64.DEFAULT ));
InputStreamReader in = new InputStreamReader(connection.getInputStream());
buf = new BufferedReader(in);
StringBuilder sb = new StringBuilder();
while ((getmessage = buf.readLine()) != null) {
sb.append(getmessage);
}
getmessage = sb.toString();
return getmessage;
}
protected void onPostExecute(String result) {
// Result will be available here (this runs on main thread)
// Show result in text view here.
response.setText(result);
}
}
To understand better, as you call AsyncTask, doInBackground runs on the new thread created. Where the network call in placed and data is parsed. Now, we need to access the data on the main thread to update the TextView so override onPostExecute inside AsyncTask that is taking result as a parameter, from doInBackground. Also if you notice..
private class GetDataFromUrl extends AsyncTask<URL, Integer, String>
Here URL is the type we are passing to our AsyncTask for doInBackground
String is what we passing from doInBackground to onPostExecute
and Integer is used to show progress for another method you can override i.e onProgressUpdate .. You can read more in the documentation liked above. Hope it was helpful.
You're only reading the first line of the response with readLine(). Call that in a loop until all lines are read, and append each new line to the previous.
If i understood correcly, you are trying to read all response data line by line. Can you try the following?
#Override
protected String doInBackGround(...){
. . .
BufferedReader rd = new BufferedReader(new InputStreamReader(inputStream), 8 * 1024);
String line = "";
StringBuilder sb = new StringBuilder();
while ((line = rd.readLine()) != null) {
sb.append(line);
}
String response = sb.toString();
return response;
}
#Override
protected void onPostExecute(String response){
Textview tv = your_textview;
your_textview.settext(whatever_part_you_get_from_response);
}
Hope this helps.
Try this:
StringBuilder sb = new StringBuilder();
while ((getmessage = buf.readLine()) != null) {
sb.append(getmessage);
}
getmessage = sb.toString();
EDITED
In your code:
getmessage = buf.readLine();
in variable getmessage reads only first line of JSON. You need to read all lines and concatenate it. How to know did you read all lines or not?
Here is what documentation says about it:
public String readLine()
throws IOException
Returns:
A String containing the contents of the line, not including any
line-termination characters, or null if the end of the stream has been
reached
As you can see, you should invoke this method, save result of it into variable, and check, if variable is not null, then you have read line of JSON. If variable is null, then you have read all JSON into variable and you have completely JSON String.
StringBuilder used to avoid creating unnecessary objects, read more about it here

Simplest way to download text from URL

Is there a simplest way to download small text string from URL like this one:"http://app.georeach.com/ios/version.txt"
In iOS its pretty simple. But for android em not finding something good. what is the method for getting text like that from the above URL??
I used this code in onCreate of hello app,n app crashed:
try {
// Create a URL for the desired page
URL url = new URL("http://app.georeach.com/ios/version.txt");
// Read all the text returned by the server
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
String str;
StringBuilder sb = new StringBuilder(100);
while ((str = in.readLine()) != null) {
sb.append(str);
// str is one line of text; readLine() strips the newline character(s)
}
in.close();
tv.setText(sb.toString());
} catch (MalformedURLException e) {
tv.setText("mal");
} catch (IOException e) {
tv.setText("io");
}
You have to create a new class extended from AsyncTask. You can't do network stuff in the main thread. It could work but you may not want to do that. Take a look at this link : http://developer.android.com/reference/android/os/AsyncTask.html
Also don't forget to add Internet permissions to your AndroidManifest.xml.
Try this:
URL url = new URL("http://bla-bla...");
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
InputStream in = connection.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(in));
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
sb.append(line);
}
// your text is here
String text = sb.toString()
Do not forget to catch and handle IOException and close all streams.
An "easier" way would be this:
String url2txt = null;
try {
// Being address an URL instance
url2txt = new Scanner(address.openStream(), "UTF-8").useDelimiter("\\A").next();
} catch (IOException e) { ... }
The thing is what you consider "easier". As far as code goes, probably this is the shortest way, but it depends on what you want to do afterwards with the obtained text.

Categories

Resources