Trouble in calculating the size of URL - android

I want to know the size of the url in order to download the file but its crashing on runtime. Here is my code:
public class MainActivity extends AppCompatActivity {
TextView t1;
private int i;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
t1=(TextView)findViewById(R.id.text1);
try {
URL url = new URL("https://www.planwallpaper.com/static/images/beautiful-sunset-images-196063.jpg");
URLConnection conection = url.openConnection();
conection.connect();
// getting file length
i = conection.getContentLength();
}
catch (Exception e) {
Log.e("Error: ", e.getMessage());
}
t1.setText(i + "MB");
}
}

all url task done in background,so use Async Task class for this........
Below code ......look like this
class SignInAsyntask extends AsyncTask<String, String, String> {
String result;
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... strings) {
// doing all url works.................
return result;
}
#Override
protected void onPostExecute(String response) {
super.onPostExecute(response);
Log.e("Result", response);
}
}
and call it onCreate() method look like tis......
new SignInAsyncTask().execute();

The reason your app crashes is because you're accessing the network on the main thread. You should make the network call on a background thread, using AsyncTask.

Related

Async HttpRequest Timing Out

The Problem
I have an AsyncTask task called from an Activity's OnCreate method. This task makes an http request. The HTTP request hangs. Once the "CODE HANGS HERE" code in the code below is executed, I observe in the debugger that the Async threads are perpetually 'running' and never return anything.
The Code
Here's the OnCreate method of the activity:
protected void onCreate(Bundle savedInstanceState) {
asyncRequest.delegate = this;
super.onCreate(savedInstanceState);
setContentView(R.layout.activty_attach);
Button retakeButton = (Button) (findViewById(R.id.retake_button));
retakeButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent(AttachActivity.this, MainActivity.class);
startActivity(intent);
}
});
try {
URL url;
url = new URL("http://btl-cromwell:9000/api/engine/v1/version");
asyncRequest.execute(url);
} catch (Exception e) {
Log.e(logtag, e.toString());
}
}
Note the URL that is passed to he async task should just return JSON containing the version number of the service receiving the request.
The async task (asyncRequest) code is below:
public class AsyncRequest extends AsyncTask<URL, Void, List<String>> {
private String logtag = "AsyncRequestTask";
public AsyncResponse delegate;
List<String> projects = new ArrayList<String>();
#Override
protected void onPreExecute(){
super.onPreExecute();
}
#Override
protected List<String> doInBackground(URL... urls) {
try {
// Creating & connection Connection with url and required Header.
HttpURLConnection urlConnection = (HttpURLConnection) urls[0].openConnection();
urlConnection.setRequestProperty("Content-Type", "application/json");
urlConnection.setRequestMethod("GET"); //POST or GET
urlConnection.setRequestProperty("User-Agent", "Test");
// CODE HANGS HERE
int responseCode = urlConnection.getResponseCode();
String responseMessage = urlConnection.getResponseMessage();
projects.add(responseMessage);
} catch (Exception e) {
Log.e(logtag, e.toString());
}
return projects;
}
#Override
protected void onPostExecute(List<String> result){
delegate.processFinish(result);
}
}
Once I have the request working I will populate the projects variable with what I actually want to return but for now I just have it set to responseMessage. I'm sure this is just something to do with my unfamiliarity in making requests in Java, but I have spent days on this and can't figure it out. Any help is greatly appreciated.
asyncRequest.execute(url);
asyncRequest.getStatus();
String[] projects = asyncRequest.get();
It is not possible to do both an .execute and a .get().
As you should never use .get(), you better remove that statement.
Remove all code after asyncRequest.execute(url); and put that code in the onPostExecute of your AsyncTask.

How get the return of AsyncTask and put on a edittext in the activity?

Im studying android, and i want to make an app that connects to a service and gets the values from there..
main activity:
public class teste extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
new api().execute();
}
}
AsyncTask
public class api extends AsyncTask<Void, Void, String> {
#Override
protected String doInBackground(Void... params) {
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
try {
URL url = new URL("https://randomuser.me/api/0.7");
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
InputStream inputStream = urlConnection.getInputStream();
reader = new BufferedReader(new InputStreamReader(inputStream));
String linha;
StringBuffer buffer = new StringBuffer();
while((linha = reader.readLine()) != null) {
buffer.append(linha);
buffer.append("\n");
}
return buffer.toString();
} catch (Exception e) {
e.printStackTrace();
if (urlConnection != null) {
urlConnection.disconnect();
}
if (reader != null) {
try {
reader.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
return null;
}
#Override
protected void onPostExecute(String dados) {
}
}
how can i fill a EditText in the mainactivity with the values returned from the asynctask?
Ive searched in the web, but cand find a answer that works..
thankss!
Rafael
Since you don't provide code for your EditText view, consider the following piece of code and modify accordingly to suit your case. You need to write the following on the onPostExecute method of your AsyncTask
#Override
protected void onPostExecute(String dados) {
EditText simpleEditText = (EditText) findViewById(R.id.simpleEditText); //replace here with your editText's id
simpleEditText.setText(dados); //dados contains the result returned from the doInBackground() method
}
EDIT
I now realised that the api class is in different file from the teste class, so you need to pass a reference of the latter one (the activity) to the AyncTask, api. You can do this by declaring a constructor:
public class api extends AsyncTask<Void, Void, String> {
private Activity activity;
//constructor
public api(Activity activity) {
this.activity = activity;
}
//rest of your code
#Override
protected void onPostExecute(String dados) {
EditText simpleEditText = (EditText) activity.findViewById(R.id.simpleEditText); //replace here with your editText's id
simpleEditText.setText(dados); //dados contains the result returned from the doInBackground() method
}
}
and call your api in teste:
public class teste extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
new api(this).execute();
}
}
You don't. The point of an AsyncTask is its asynchronous. It doesn't return anything. You should never call .get() on one, if you do then there's no point in using an AsyncTask. Instead, all the code that needs the result should be placed in onPostExecute.

Exact procedure to add an image through json android

Hello so I have already an expirience with AsyncTask so I can manage to get some data with PHP scripts from an SQL Server and parsed them with JSON. Now what I would want is to know how can I use the AsyncTask in order to load images to some activities. Also is there anyway that I can call the AsyncTask before the app starts? because that would be really helpful too.
I don't have any adapters I am just using this for the AsyncTask:
// The definition of our task class
private class PostTask extends AsyncTask<String, Integer, String> {
private String postName;
private JSONObject jsonvar = new JSONObject();
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
this.postName = params[0];
String status = "";
List<NameValuePair> values = new ArrayList<NameValuePair>();
values.add( new BasicNameValuePair( "username", this.postName ) );
final AndroidHttpClient client = AndroidHttpClient.newInstance( "" );
HttpResponse response = HttpHelper.postResponse( client, Register.phpUrl, values );
String data = HttpHelper.getData( response );
try {
jsonvar = new JSONObject(data);
status=jsonvar.getString("status");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
client.close();
return status;
}
// #Override
// protected void onProgressUpdate(Integer... values) {
// super.onProgressUpdate(values);
// }
#Override
protected void onPostExecute(String status) {
String session = "", status_message = " ";
try {
status_message = jsonvar.getString("status_message");
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
super.onPostExecute(status);
}
}
}
As i can tell with information provided, supposing that what you read from your server is the image URL and obtain it in JSON format, what i would do is writing a listener to your AsyncTask, calling it in onPostExecute method, and loading it in your Activity using PicassoImagesLoader
Something like:
private class PostTask extends AsyncTask<String, Integer, String> {
public interface onLoadFinishedListener {
public void onLoadFinished(JSONObject response)
}
protected JSONObject onPostExecute(JSONObject response){
onLoadFinished(response);
}
}
And in your Activity:
public myActivity extends Activity implements PostTask.onLoadFinishedListener {
#Override
onLoadFinished(JSONObject response){
Picasso.with(this).load(response.getString("url")).into(imageView);
}
}
Something like this would help :)

Android generic Asynctask

I currently have multiple activity that needs to perform an asynctask for http post and I wish to make the asynctask as another class file so that the different activity can call the asynctask to perform the http post request and onPostExecute, call the method httpResult(result) in the activity that called the asynctask. I have tried to pass the activity in but I am unable to call the method in onPostExecute. How can I do that?
public class MyActivity extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_MyActivity);
//logic here...
AsyncHttpPost asyncHttpPost = new AsyncHttpPost("someContent", this, dialog);
JSONObject data = new JSONObject();
data.put("key", "value");
try {
asyncHttpPost.execute(data);
}
catch (Exception ex){
ex.printStackTrace();
}
}
public static void httpResult(String result) {
//this method has to get called by asynctask to make changes to the UI
}
}
AsyncHttpPost.java
public class AsyncHttpPost extends AsyncTask<JSONObject, String, String> {
String recvdjson;
String mData="";
private ProgressDialog dialog;
private Activity activity;
public AsyncHttpPost(String data, Activity activity, ProgressDialog dialog) {
mData = data;
this.activity = activity;
this.dialog = dialog;
}
protected void onPreExecute()
{
dialog.show();
}
#Override
protected String doInBackground(JSONObject... params) {
//logic to do http request
return "someStringResult";
}
protected void onPostExecute(String result) {
dialog.dismiss();
activity.httpResult(result); //This line gives me error : The method httpResult(String) is undefined for the type Activity
}
}
Create an Interface called HttpResponseImpl in a seperate file and add the required method httpResult
interface HttpResponseImpl{
public void httpResult(String result);
}
Now implement this interface by you Activity class
public class MyActivity extends Activity implements HttpResponseImpl{
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_MyActivity);
//logic here...
AsyncHttpPost asyncHttpPost = new AsyncHttpPost("someContent", this, dialog);
JSONObject data = new JSONObject();
data.put("key", "value");
try {
asyncHttpPost.execute(data);
}
catch (Exception ex){
ex.printStackTrace();
}
}
public void httpResult(String result){
//this method has to get called by asynctask to make changes to the UI
}
}
And your AsyncHttpPost class would be.
public class AsyncHttpPost extends AsyncTask<JSONObject, String, String> {
String recvdjson;
String mData="";
private ProgressDialog dialog;
private HttpResponseImpl httpResponseImpl;
public AsyncHttpPost(String data, HttpResponseImpl httpResponseImpl, ProgressDialog dialog) {
mData = data;
this.httpResponseImpl = httpResponseImpl;
this.dialog = dialog;
}
protected void onPreExecute()
{
dialog.show();
}
#Override
protected String doInBackground(JSONObject... params) {
//logic to do http request
return "someStringResult";
}
protected void onPostExecute(String result) {
dialog.dismiss();
httpResponseImpl.httpResult(result);
}
}
Implements this HttpResponseImpl interface with all you Activity class from which you want to do HttpRequest.
Generic AsyncTask Example
Call it like
new RetrieveFeedTask(new OnTaskFinished()
{
#Override
public void onFeedRetrieved(String feeds)
{
//do whatever you want to do with the feeds
}
}).execute("http://enterurlhere.com");
RetrieveFeedTask.class
class RetrieveFeedTask extends AsyncTask<String, Void, String>
{
String HTML_response= "";
OnTaskFinished onOurTaskFinished;
public RetrieveFeedTask(OnTaskFinished onTaskFinished)
{
onOurTaskFinished = onTaskFinished;
}
#Override
protected void onPreExecute()
{
super.onPreExecute();
}
#Override
protected String doInBackground(String... urls)
{
try
{
URL url = new URL(urls[0]); // enter your url here which to download
URLConnection conn = url.openConnection();
// open the stream and put it into BufferedReader
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String inputLine;
while ((inputLine = br.readLine()) != null)
{
// System.out.println(inputLine);
HTML_response += inputLine;
}
br.close();
System.out.println("Done");
}
catch (MalformedURLException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
return HTML_response;
}
#Override
protected void onPostExecute(String feed)
{
onOurTaskFinished.onFeedRetrieved(feed);
}
}
OnTaskFinished.java
public interface OnTaskFinished
{
public void onFeedRetrieved(String feeds);
}

The method findViewById(int) is undefined

I'm new to Android development and I'm trying to code a little app which allows me to grab an external JSON file and parse it. I got this to work, however it wont work if I try to execute it in the background as an AsyncTask. Eclipse gives me the error
The method findViewById(int) is undefined for the type LongOperation
in this line:
TextView txtView1 = (TextView)findViewById(R.id.TextView01);
Here is my code:
public class Main extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
new LongOperation().execute();
}
}
class LongOperation extends AsyncTask<String, Void, String> {
private final Context LongOperation = null;
#Override
protected String doInBackground(String... params) {
try {
URL json = new URL("http://www.corps-marchia.de/jsontest.php");
URLConnection tc = json.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(tc.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
JSONArray ja = new JSONArray(line);
JSONObject jo = (JSONObject) ja.get(0);
TextView txtView1 = (TextView)findViewById(R.id.TextView01);
txtView1.setText(jo.getString("text") + " - " + jo.getString("secondtest"));
}
} catch (MalformedURLException e) {
Toast.makeText(this.LongOperation, "Malformed URL Exception: " + e, Toast.LENGTH_LONG).show();
} catch (IOException e) {
Toast.makeText(this.LongOperation, "IO Exception: " + e, Toast.LENGTH_LONG).show();
} catch (JSONException e) {
Toast.makeText(this.LongOperation, "JSON Exception: " + e, Toast.LENGTH_LONG).show();
}
return null;
}
#Override
protected void onPostExecute(String result) {
}
protected void onPreExecute() {
}
#Override
protected void onProgressUpdate(Void... values) {
ProgressDialog pd = new ProgressDialog(LongOperation);
pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
pd.setMessage("Working...");
pd.setIndeterminate(true);
pd.setCancelable(false);
}
}
Any ideas on how to fix this?
Here is what you should do to make it work as you want. Use onPostExecude()
public class Main extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
new LongOperation(this).execute();
}
}
class LongOperation extends AsyncTask<String, Void, String> {
private Main longOperationContext = null;
public LongOperation(Main context) {
longOperationContext = context;
Log.v("LongOper", "Konstuktor");
}
#Override
protected String doInBackground(String... params) {
Log.v("doInBackground", "inside");
StringBuilder sb = new StringBuilder();
try {
URL json = new URL("http://www.corps-marchia.de/jsontest.php");
URLConnection tc = json.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(tc.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
JSONArray ja = new JSONArray(line);
JSONObject jo = (JSONObject) ja.get(0);
Log.v("line = ", "jo.getString() ="+jo.getString("text"));
sb.append(jo.getString("text") + " - " + jo.getString("secondtest")).append("\n");
}
} catch (MalformedURLException e) {
e.printStackTrace();
Log.v("Error", "URL exc");
} catch (IOException e) {
e.printStackTrace();
Log.v("ERROR", "IOEXECPTOIn");
} catch (JSONException e) {
e.printStackTrace();
Log.v("Error", "JsonException");
}
String result = sb.toString();
return result;
}
#Override
protected void onPostExecute(String result) {
Log.v("onPostExe", "result = "+result);
TextView txtView1 = (TextView)longOperationContext.findViewById(R.id.textView01);
txtView1.setText(result);
}
protected void onPreExecute() {
}
#Override
protected void onProgressUpdate(Void... values) {
ProgressDialog pd = new ProgressDialog(longOperationContext);
pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
pd.setMessage("Working...");
pd.setIndeterminate(true);
pd.setCancelable(false);
}
}
The implementation of AsyncTask in one of the other answers is flawed. The progress dialog is being created every time within publishProgress, and the reference to the dialog is not visible outside the method. Here is my attempt:
public class Main extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
new LongOperation().execute();
}
class LongOperation extends AsyncTask<String, Void, String> {
ProgressDialog pd = null;
TextView tv = null;
#Override
protected void onPreExecute(){
tv = Main.this.findViewById(R.id.textvewid);
pd = new ProgressDialog(Main.this);
pd.setMessage("Working...");
// setup rest of progress dialog
}
#Override
protected String doInBackground(String... params) {
//perform existing background task
return result;
}
#Override
protected void onPostExecute(String result){
pd.dismiss();
tv.setText(result);
}
}
}
You are trying to do something which won't work. First of all you are inside of a class that extends AsyncTask so you won't have that method available as it is a method of the class Activity.
The second problem is that you are trying to do UI stuff in a method that is not synchronized with the UI thread. That is nothing you would want to do.
Process your JSON response in the doInBackground method and pass the result to the onPostExecute method where you will be able to handle UI stuff as it is synchronized with the UI thread.
The current setup you have will not make it easier for you to handle what you are trying to do anyway. You could make your LongOperation class a private class of your Activity class and define the TextView as a instance member. Grab it off the layout using findViewById inside of your OnCreate and modify (set text or whatever) inside the onPostExecute method of your AsyncTask.
I hope it is somewhat clear what I meant.
findViewById is method in Activity class. You should pass instance of your activity to your LongOperation when you create it. Then use that instance to call findViewById.

Categories

Resources