I try to execute an AsyncTask like this
private static final String REQUESTED_URL = "//my url";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.earthquake_activity);
EarthQuakeAsyncTask task = new EarthQuakeAsyncTask();
task.execute(REQUESTED_URL); //this is where the error is
}
but Android Studio said that it cannot resolve method execute(String). I'm having a tutorial from Udacity, their sample is pretty much similar
/** URL for earthquake data from the USGS dataset */
private static final String USGS_REQUEST_URL =
"//url";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
EarthquakeAsyncTask task = new EarthquakeAsyncTask();
task.execute(USGS_REQUEST_URL); //it works
}
Can someone tell me why this possibly occurs?
Edit: this is my EarthQuakeAsyncTask class:
private class EarthQuakeAsyncTask extends AsyncTask<URL,Void,ArrayList<EarthQuake>> {
#Override
protected ArrayList<EarthQuake> doInBackground(URL... urls) {
if(urls.length==0||urls[0]== null){
return null;
}
// Create URL object
URL url = createUrl(REQUESTED_URL);
try {
jsonResponse = makeHttpRequest(url);
} catch (IOException e) {
// TODO Handle the IOException
}
ArrayList<EarthQuake> earthquake = QueryUtils.extractEarthquakes(jsonResponse);
return earthquake;
}
#Override
protected void onPostExecute(ArrayList<EarthQuake> earthquake) {
if (earthquake == null) {
return;
}
updateUi();
}
private URL createUrl(String stringUrl) {
URL url;
try {
url = new URL(stringUrl);
} catch (MalformedURLException exception) {
Log.e(LOG_TAG, "Error with creating URL", exception);
return null;
}
return url;
}
private String makeHttpRequest(URL url) throws IOException {
// If the URL is null, then return early.
if (url == null) {
return jsonResponse;
}
HttpURLConnection urlConnection = null;
InputStream inputStream = null;
try {
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setReadTimeout(10000 /* milliseconds */);
urlConnection.setConnectTimeout(15000 /* milliseconds */);
urlConnection.setRequestMethod("GET");
urlConnection.connect();
// If the request was successful (response code 200),
// then read the input stream and parse the response.
if (urlConnection.getResponseCode() == 200) {
inputStream = urlConnection.getInputStream();
jsonResponse = readFromStream(inputStream);
} else {
Log.e(LOG_TAG, "Error response code: " + urlConnection.getResponseCode());
}
} catch (IOException e) {
Log.e(LOG_TAG, "Problem retrieving the earthquake JSON results.", e);
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
if (inputStream != null) {
inputStream.close();
}
}
return jsonResponse;
}
private String readFromStream(InputStream inputStream) throws IOException {
StringBuilder output = new StringBuilder();
if (inputStream != null) {
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, Charset.forName("UTF-8"));
BufferedReader reader = new BufferedReader(inputStreamReader);
String line = reader.readLine();
while (line != null) {
output.append(line);
line = reader.readLine();
}
}
return output.toString();
}
}
}
Your class signature suggests that you are expecting a URL type as parameter, but you are passing a String type in the execute() method. All you need to do is to change your class signature to expect a String as in the one in this code.
private class EarthQuakeAsyncTask extends AsyncTask<String,Void,ArrayList<EarthQuake>> {
#Override
protected ArrayList<EarthQuake> doInBackground(String... urls) {
if(urls.length==0||urls[0]== null){
return null;
}
// Create a URL object from the String passed to the execute method
URL url = createUrl(urls[0]);
try {
jsonResponse = makeHttpRequest(url);
} catch (IOException e) {
// TODO Handle the IOException
}
ArrayList<EarthQuake> earthquake = QueryUtils.extractEarthquakes(jsonResponse);
return earthquake;
}
#Override
protected void onPostExecute(ArrayList<EarthQuake> earthquake) {
if (earthquake == null) {
return;
}
updateUi();
}
private URL createUrl(String stringUrl) {
URL url;
try {
url = new URL(stringUrl);
} catch (MalformedURLException exception) {
Log.e(LOG_TAG, "Error with creating URL", exception);
return null;
}
return url;
}
private String makeHttpRequest(URL url) throws IOException {
// If the URL is null, then return early.
if (url == null) {
return jsonResponse;
}
HttpURLConnection urlConnection = null;
InputStream inputStream = null;
try {
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setReadTimeout(10000 /* milliseconds */);
urlConnection.setConnectTimeout(15000 /* milliseconds */);
urlConnection.setRequestMethod("GET");
urlConnection.connect();
// If the request was successful (response code 200),
// then read the input stream and parse the response.
if (urlConnection.getResponseCode() == 200) {
inputStream = urlConnection.getInputStream();
jsonResponse = readFromStream(inputStream);
} else {
Log.e(LOG_TAG, "Error response code: " + urlConnection.getResponseCode());
}
} catch (IOException e) {
Log.e(LOG_TAG, "Problem retrieving the earthquake JSON results.", e);
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
if (inputStream != null) {
inputStream.close();
}
}
return jsonResponse;
}
private String readFromStream(InputStream inputStream) throws IOException {
StringBuilder output = new StringBuilder();
if (inputStream != null) {
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, Charset.forName("UTF-8"));
BufferedReader reader = new BufferedReader(inputStreamReader);
String line = reader.readLine();
while (line != null) {
output.append(line);
line = reader.readLine();
}
}
return output.toString();
}
}
}
That is because your AsyncTask class isn't defined in a manner to handle the execute method with a String parameter. Let me explain myself.
The AsyncTask class you develop will look like this:
private class MyAsyncTask extends AsyncTask<TYPE1, TYPE2, TYPE3> {
protected TYPE3 doInBackground(TYPE1... type1_variables) {
// Do some long process here..
return variable_of_type_TYPE3;
}
protected void onPostExecute(TYPE3 result) {
// Do something here
}
}
So for you to call task.execute(REQUESTED_URL); you'd need to implement your AsyncTask class correctly.
For example it might look like this:
private class EarthQuakeAsyncTask extends AsyncTask<String, Void, Void> {
...
}
Related
I try to create synchronized threads, but I always get the following error: android.os.NetworkOnMainThreadException.
I've read more posts, but they don't work for me.
Below I write the code blocks that do not work for me:
1.
final SyncApp syncJob = new SyncApp();
Thread t = new Thread (new Runnable () {
#Override
public void run () {
synchronized (syncJob) {
String s = syncJob.insert (newJobs, GlobalVariables.URL_LOCALHOST + "jobs");
txtState.setText (s);
}}});
}
});
t.Start ();
// t.run ();
2.
myClass.runOnUiThread(new Runnable() {
public void run() {...}
})
3.
Running code in main thread from another thread
SyncApp:
public class SyncApp {
synchronized public String insert(List<Jobs> job, String... params) {
URL url = null;
HttpURLConnection conn = null;
try {
url = new URL(params[0]);
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");
conn.setDoInput(true);
conn.setDoOutput(true);
String str = new Gson().toJson(job);
byte[] outputInBytes = str.getBytes();
OutputStream os = conn.getOutputStream();
os.write( outputInBytes );
os.flush();
int responseCode=conn.getResponseCode();
String response = null;
if (responseCode == HttpsURLConnection.HTTP_OK) {
String line;
BufferedReader br=new BufferedReader(new InputStreamReader(conn.getInputStream()));
while ((line=br.readLine()) != null) {
response+=line;
}
}
else {
response=conn.getResponseMessage();
}
return response;
} catch (Exception e) {
e.printStackTrace();
} finally {
conn.disconnect();
}
return null;
}
}
I need to call a thread, wait for the answer and call another thread. Their answers I must use them in the activity
I need to call a thread, wait for the answer and call another thread.
Their answers I must use them in the activity
Example using async tasks to accomplish objective.
In this code, let A be your activity which needs to call a thread,
wait for the answer and call another thread. Customize as needed.
Since you never wait in UI threads, callbacks are used to accomplish synchronization.
Let A be your activity class:
public class A extends Activity {
// some method in activity where you launch a background thread (B)
// which then completes and invokes callback which then creates and launches
// a background thread (C) which then completes and invokes a callback.
//
// In callback C, you are on the UI thread.
protected void someMethod() {
new B(new B.CallbackB() {
public void result(Object o) {
new C(new C.CallbackC() {
public void result(Object o, Object answerFromB) {
// OK - C is now done and we are on UI thread!
// 'o' is answer from C
// 'answerFromB' also provided
}
}, o).execute(new Object());
}
).execute(new Object());
}
}
Define a class B:
public class B extends AsyncTask<Object, Void, Object> {
public static interface CallbackB {
void result(Object o);
}
private CallbackB cb;
public B (CallbackB cb) {
this.cb = cb;
}
protected Object doInBackground(Object... params) {
// do work and return an answer.
return new Object();
}
protected void onPostExecute(Object result) {
if (cb != null) {
cb.result(result);
}
}
}
Define a class C:
public class C extends AsyncTask<Object, Void, Object> {
public static interface CallbackC {
void result(Object o, Object answerFromB);
}
private CallbackC cb;
private Object answerFromB;
public C (CallbackC cb, Object answerFromB) {
this.cb = cb;
this.answerFromB = answerFromB;
}
protected Object doInBackground(Object... params) {
// do work and return an answer.
return new Object();
}
protected void onPostExecute(Object result) {
if (cb != null) {
cb.result(result, answerFromB);
}
}
}
For reference:
https://stackoverflow.com/a/9963705/2711811
My solution is:
public class Sync extends AppCompatActivity {
...
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sync_server);
dao = new DAO(this);
txtState = findViewById(R.id.txt_log);
btnSincro = findViewById(R.id.btn_sincro);
btnSincro.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
countCall = 0;
callFlow();
}
});
btnHome = findViewById(R.id.btn_home);
btnHome.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(SyncServerActivity.this, MainActivity.class);
startActivity(intent);
}
});
}
private void callFlow() {
switch (countCall) {
case 0:
templates = toTemplate("url");
break;
case 1:
jobs = toJobs("url");
break;
case 2:
job = ... //select item
res = sendJobs(jobs, "url");
break;
default:
runOnUiThread(new Runnable() {
#Override
public void run() {
btnSincro.setEnabled(true);
txtState.append("\n\nEND");
}
});
}
}
private void nextStep() {
setText(txtState, "\nSync \n" + countCall + "/3");
countCall++;
callFlow();
}
private void setText(final TextView text, final String value) {
runOnUiThread(new Runnable() {
#Override
public void run() {
text.setText(value);
}
});
}
public List<Templates> toTemplate(final String... params) {
final List<Templates> list = new ArrayList<>();
Thread t = new Thread(new Runnable() {
#Override
public void run() {
URL url = null;
BufferedReader reader = null;
HttpURLConnection connection = null;
try {
url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
int responseCode = connection.getResponseCode();
String response = null;
if (responseCode == HttpsURLConnection.HTTP_OK) {
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
String finalJson = buffer.toString();
JSONObject parentObject = new JSONObject(finalJson);
JSONArray parentArray = parentObject.getJSONArray("data");
for (int i = 0; i < parentArray.length(); i++) {
Templates item = new Gson().fromJson(parentArray.get(i).toString(), Templates.class);
list.add(item);
}
} else {
response = connection.getResponseMessage();
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} finally {
if (connection != null)
connection.disconnect();
try {
if (reader != null)
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
nextStep(); //call next Thread
}
}
});
t.start();
return list;
}
public List<Jobs> toJobs(final String... params) {
final List<Jobs> list = new ArrayList<>();
Thread t = new Thread(new Runnable() {
#Override
public void run() {
URL url = null;
BufferedReader reader = null;
HttpURLConnection connection = null;
try {
url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
int responseCode = connection.getResponseCode();
String response = null;
if (responseCode == HttpsURLConnection.HTTP_OK) {
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
String finalJson = buffer.toString();
JSONObject parentObject = new JSONObject(finalJson);
JSONArray parentArray = parentObject.getJSONArray("data");
for (int i = 0; i < parentArray.length(); i++) {
Jobs item = new Gson().fromJson(parentArray.get(i).toString(), Jobs.class);
list.add(item);
}
} else {
response = connection.getResponseMessage();
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} finally {
if (connection != null)
connection.disconnect();
try {
if (reader != null)
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
nextStep();
}
}
});
t.start();
return list;
}
public Boolean sendJobs(final List<Jobs> job, final String... params) {
final Boolean[] result = {false};
Thread t = new Thread(new Runnable() {
#Override
public void run() {
URL url = null;
HttpURLConnection conn = null;
try {
url = new URL(params[0]);
conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json");
conn.setDoInput(true);
conn.setDoOutput(true);
String str = new Gson().toJson(job);
Log.d(TAG, str);
byte[] outputInBytes = str.getBytes();
OutputStream os = conn.getOutputStream();
os.write(outputInBytes);
os.flush();
int responseCode = conn.getResponseCode();
String response = null;
if (responseCode == HttpsURLConnection.HTTP_OK) {
String line;
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
while ((line = br.readLine()) != null) {
response += line;
}
result[0] = true;
} else {
response = conn.getResponseMessage();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
conn.disconnect();
nextStep();
}
}
});
t.start();
return result[0];
}
}
Whenever a thread ends, it calls the nextStep() method, which starts the next trhead.
when calling
new AsyncFeed(strurl).execute();
after this its able to call constructor of AsyncFeed but not able to execute doInBackground(). while debugging i found out it calls constructor and then simply returns back to the calling statement making a nullpointer exception in later code
public class HttpHandler {
public HttpHandler() {
}
URL url;
HttpURLConnection httpURLConnection = null;
InputStream inputStream;
BufferedReader bufferedReader = null;
StringBuffer stringBuffer;
String strurl;
public String getJsonString(String strurl){
new AsyncFeed(strurl).execute();
return String.valueOf(stringBuffer);
}
class AsyncFeed extends AsyncTask<String,Void,String>{
String urlStr;
public AsyncFeed(String urlStr) {
this.urlStr=urlStr;
}
#Override
protected String doInBackground(String... strings) {
try {
url = new URL(urlStr);
httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.connect();
inputStream = httpURLConnection.getInputStream();
bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String line;
stringBuffer = new StringBuffer();
while ((line=bufferedReader.readLine()) != null){
stringBuffer.append(line);
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if(bufferedReader !=null)
try {
bufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
}
httpURLConnection.disconnect();
}
return null;
}
If you think that stringBuffer is null, it's because function public String getJsonString(String strurl) returns String value of uninitialized stringBuffer before AsyncFeed is completed. You should use something like this:
public void loadJsonString(String strurl){
new AsyncFeed(strurl).execute();
//return String.valueOf(stringBuffer);
}
class AsyncFeed extends AsyncTask<Void,Void,Void>{
String urlStr;
public AsyncFeed(String urlStr) {
this.urlStr=urlStr;
}
#Override
protected String doInBackground(Void... records) {
try {
url = new URL(urlStr);
httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.connect();
inputStream = httpURLConnection.getInputStream();
bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String line;
stringBuffer = new StringBuffer();
while ((line=bufferedReader.readLine()) != null){
stringBuffer.append(line);
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if(bufferedReader !=null)
try {
bufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
}
httpURLConnection.disconnect();
}
return null;
}
#Override
protected void onPreExecute() {
//f.e. show progress dialog
}
#Override
protected void onPostExecute(Void result) {
//now you have initialized stringBuffer so do what you want with it
//hide progress dialog
//print String value of stringBuffer initialized in doInBackground
System.out.print(String.valueOf(stringBuffer));
}
)
There are more options to do that but it's hard to write exactly what you need without seeing more of your code or specify your question, so if you have some
questions to me just write comment :) or read more here Android Developers - AsyncTask
EDIT
Okay I understand, try do it like this, the idea is just pass calling object into the async task and from there in onPostExecute() will be updated data
in ClassA and continue with what you need
public class ClassA{
String url;
String jsonObjectString;
//instead of getJsonString(url) call this and after async task will finish
//it calls updateDataFromAsync() so you will have data loaded and you can continue work with it in doSomethingAfterAsync()
private void loadData(){
//pass the calling object into the async task
new HttpHandler(this).startLoadJsonString(url);
}
//this will async taks call in onPostExecute()
public void updateDataFromAsync(String s){
jsonObjectString = s;
doSomethingAfterAsync();
}
private doSomethingAfterAsync(){
}
}
public class HttpHandler {
URL url;
HttpURLConnection httpURLConnection = null;
InputStream inputStream;
BufferedReader bufferedReader = null;
StringBuffer stringBuffer;
String strurl;
ClassA classA;
public HttpHandler(ClassA classA) {
this.classA = classA;
}
public void startLoadJsonString(String strurl){
new AsyncFeed(strurl).execute();
}
private class AsyncFeed extends AsyncTask<Void,Void,Void>{
String urlStr;
public AsyncFeed(String urlStr) {
this.urlStr=urlStr;
}
#Override
protected String doInBackground(Void... records) {
try {
url = new URL(urlStr);
httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.connect();
inputStream = httpURLConnection.getInputStream();
bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String line;
stringBuffer = new StringBuffer();
while ((line=bufferedReader.readLine()) != null){
stringBuffer.append(line);
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if(bufferedReader !=null)
try {
bufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
}
httpURLConnection.disconnect();
}
return null;
}
#Override
protected void onPreExecute() {
//f.e. show progress dialog
}
#Override
protected void onPostExecute(Void result) {
//now you have initialized stringBuffer so do what you want with it
//hide progress dialog
//call updateDataFromAsync from ClassA class and continue there
classA.updateDataFromAsync(String.valueOf(stringBuffer));
}
)
In here the code with BufferedReaderand line = reader.readLine() works
public class WeatherService extends AsyncTask<TaskParams, Void, String> {
private WeatherServiceCallback callback;
private Exception exception;
public WeatherService(WeatherServiceCallback callback) {
this.callback = callback;
}
#Override
protected String doInBackground(TaskParams... params) {
try {
URL url = new URL("http://api.openweathermap.org/data/2.5/weather?lat=" +
params[0].getLat() + "&lon=" + params[0].getLon() +
"&units=" + TaskParams.getUnits() +
"&type=" + TaskParams.getAccuracy() + "&lang=" + TaskParams.getLanguage() +
"&appid=10660a09a9fb335d72f576f7aa1bbe5b");
URLConnection connection = url.openConnection();
InputStream inputStream = connection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder builder = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
builder.append(line);
}
return builder.toString();
} catch (MalformedURLException e) {
exception = e;
} catch (IOException e) {
exception = e;
}
return null;
}
#Override
protected void onPostExecute(String s)
{
if (s == null && exception != null)
{
callback.serviceFailure(exception);
return;
}
try
{
JSONObject data = new JSONObject(s);
Parameters parameters = new Parameters();
parameters.poopulate(data);
callback.serviceSuccess(parameters);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
I copy-pasted code to other class since it has very similar functionality and now for no reason I'm getting NullPointerException in while ((line = reader.readLine()) != null) and I have no idea why since as I said it's copy-pasted (I only changed URL and object returned if serivce succeeds)
public class PollutionService extends AsyncTask<TaskParams, Void, String>
{
private PollutionServiceCallback callback;
private Exception exception;
private URLConnection connection;
private InputStream inputStream;
private InputStreamReader streamReader;
private BufferedReader reader;
public PollutionService(PollutionServiceCallback callback) {
this.callback = callback;
}
#Override
protected String doInBackground(TaskParams... params) {
try
{
URL url = new URL("http://api.openweathermap.org/pollution/v1/co/" + params[0].getLat() +
"," + params[0].getLon() + "/current.json?&appid=10660a09a9fb335d72f576f7aa1bbe5b");
try
{
connection = url.openConnection();
}
catch (IOException e)
{
exception = new Exception("Connection error");
}
try
{
inputStream = connection.getInputStream();
}
catch (IOException e)
{
exception = new Exception("Input stream error");
}
try
{
streamReader = new InputStreamReader(inputStream);
}
catch (NullPointerException e)
{
exception = new Exception("Input stream reader error");
}
try
{
reader = new BufferedReader(streamReader);
}
catch (NullPointerException e)
{
exception = new Exception("Buffered reader error");
}
StringBuilder builder = new StringBuilder();
String line;
try
{
while ((line = reader.readLine()) != null)
{
builder.append(line);
}
}
catch (IOException e)
{
exception = e;
}
return builder.toString();
}
catch (MalformedURLException e)
{
exception = e;
}
return null;
}
#Override
protected void onPostExecute(String s)
{
if (s == null && exception != null)
{
callback.pollutionServiceFailure(exception);
return;
}
try
{
JSONObject data = new JSONObject(s);
PollutionParameters parameters = new PollutionParameters();
parameters.poopulate(data);
callback.pollutionServiceSuccess(parameters);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
Any clue?
EDIT
This is rewritten code for PollutionActivity. Callback function serviceFailure prints now the URL address on my phone's screen
public class PollutionService extends AsyncTask<TaskParams, Void, String>
{
private PollutionServiceCallback callback;
private Exception exception;
public PollutionService(PollutionServiceCallback callback) {
this.callback = callback;
}
#Override
protected String doInBackground(TaskParams... params) {
try
{
URL url = new URL("http://api.openweathermap.org/pollution/v1/co/" + params[0].getLat() +
"," + params[0].getLon() + "/current.json?&appid=10660a09a9fb335d72f576f7aa1bbe5b");
URLConnection connection = url.openConnection();
InputStream inputStream = connection.getInputStream();
InputStreamReader streamReader = new InputStreamReader(inputStream);
BufferedReader reader = new BufferedReader(streamReader);
StringBuilder builder = new StringBuilder();
String line;
try
{
while ((line = reader.readLine()) != null)
{
builder.append(line);
}
}
catch (IOException e)
{
exception = e;
}
return builder.toString();
}
catch (MalformedURLException e)
{
exception = e;
}
catch (IOException e)
{
exception = e;
}
return null;
}
#Override
protected void onPostExecute(String s)
{
if (s == null && exception != null)
{
callback.pollutionServiceFailure(exception);
return;
}
try
{
JSONObject data = new JSONObject(s);
PollutionParameters parameters = new PollutionParameters();
parameters.poopulate(data);
callback.pollutionServiceSuccess(parameters);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
Debugging showed me that code jumps to exception after
InputStream inputStream = connection.getInputStream();
If you are getting NPE for reader then it means that reader is not getting initialized and going null.Your code is getting crash at line 23 and 89. So I believe that the problem is right at the start somewhere and not at the point itself, may be some object is going null like connection.Since line number is not displayed here.Check null pointer for every object like if (connection!=null). Since the initial data is coming null,maybe input stream or some other data,hence your reader object is not getting initialized.Also check if you are getting value for every object in debug.
I am trying to get my webview to show a page that is only accesible after i am logged in. but whatever i try i cant get past the login url.
How can i open/show the SEND_VISUM_URL after i login.
this is what i have so far:
String LOGIN_URL = "http://10.35.50.125/BCS/index.php?module=";
String SEND_VISUM_URL = "http://10.35.50.1/BCS/index.php?module=ScanVisa&Action=save";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
webView = (WebView)findViewById(R.id.webviewer);
webView.loadUrl(LOGIN_URL);
cookieManager = new CookieManager();
Button login = (Button) findViewById(R.id.PostData);
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
new loginTask().execute(getLoginData());
} catch (Exception ex) {
ex.printStackTrace();
}
}
});
}
public class loginTask extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... params) {
String loginData = params[0];
String text = "";
BufferedReader reader = null;
// Send data
try {
// Defined URL where to send data
URL login_url = new URL(LOGIN_URL);
// getting cookies:
URLConnection conn = login_url.openConnection();
conn.connect();
// setting cookies
cookieManager.storeCookies(conn);
cookieManager.setCookies(login_url.openConnection());
cookiestring = cookieManager.toString();
Log.d("Cookie in logintask:", cookiestring);
conn.getContent();
conn.setDoOutput(true);
conn.setConnectTimeout(3000);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
try {
wr.write(loginData); //post
wr.flush();
} catch (Exception e) {
e.printStackTrace();
}
// Get the server response
reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
if (line.length() > 0) {
sb.append(line + "\n");
if (line == null) {
continue;
}
}
}
text = sb.toString();
} catch (Exception ex) {
ex.printStackTrace();
} finally {
try {
if (reader != null) reader.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
return text;
}
protected void onPostExecute(String line) {
if (!line.contains("I107")) { //I107 is an error code that is returend when a login failed
Toast.makeText(getBaseContext(), "Login succesfull", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getBaseContext(), "Login failed", Toast.LENGTH_LONG).show();
}
}
}
public void setCookies(URLConnection conn) throws IOException {
// let's determine the domain and path to retrieve the appropriate cookies
URL url = conn.getURL();
String domain = getDomainFromHost(url.getHost());
String path = url.getPath();
Map domainStore = (Map)store.get(domain);
if (domainStore == null) return;
StringBuffer cookieStringBuffer = new StringBuffer();
Iterator cookieNames = domainStore.keySet().iterator();
while(cookieNames.hasNext()) {
String cookieName = (String)cookieNames.next();
Map cookie = (Map)domainStore.get(cookieName);
// check cookie to ensure path matches and cookie is not expired
// if all is cool, add cookie to header string
if (comparePaths((String)cookie.get(PATH), path) && isNotExpired((String)cookie.get(EXPIRES))) {
cookieStringBuffer.append(cookieName);
cookieStringBuffer.append("=");
cookieStringBuffer.append((String)cookie.get(cookieName));
if (cookieNames.hasNext()) cookieStringBuffer.append(SET_COOKIE_SEPARATOR);
}
}
try {
conn.setRequestProperty(COOKIE, cookieStringBuffer.toString());
} catch (java.lang.IllegalStateException ise) {
IOException ioe = new IOException("Illegal State! Cookies cannot be set on a URLConnection that is already connected. "
+ "Only call setCookies(java.net.URLConnection) AFTER calling java.net.URLConnection.connect().");
throw ioe;
}
}
any help would be greatly appreciated!
I have been working on ListView and ArrayAdapter. Now I got Stuck while making change in my ArrayAdapter.
I'm using an AsyncTack to update the UI element i.e. ListView, an adapter to the ListView is set in onCreate() method initially, but I'm about to change the array adapter in onPostExecute() method of AsyncTask.
Here is the code bellow
ListView mListView = (ListView)findViewById(R.id.dataListView);
vAdapter = new ArrayAdapter(getActivity(), R.layout.list_item_data,strings);
mLisstView.setAdapter(vAdapter);
AsyncTask
public class getDataFromServer extends AsyncTask<String,Void,String[]>{
public getDataFromServer() {
super();
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String[] doInBackground(String... parm) {
// These two need to be declared outside the try/catch
// so that they can be closed in the finally block.
if(parm.length == 0){
return null;
}
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
// Will contain the raw JSON response as a string.
String getJsonStr = null;
try {
final String FORECAST_BASE_URL="http://myUrlToServer?";
final String QUERY_PARAM ="query";
final String FORMAT_PARAM ="mode";
final String UNITS_PARAM ="units";
Uri baseUri = Uri.parse(FORECAST_BASE_URL).buildUpon()
.appendQueryParameter(QUERY_PARAM,parm[0])
.appendQueryParameter(FORMAT_PARAM, format)
.appendQueryParameter(UNITS_PARAM,units)
.build();
Log.v("build Url: ",baseUri.toString());
URL url = new URL(baseUri.toString());
// Create the request and open the connection
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
// Read the input stream into a String
InputStream inputStream = urlConnection.getInputStream();
StringBuffer buffer = new StringBuffer();
if (inputStream == null) {
// Nothing to do.
return null;
}
reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
buffer.append(line + "\n");
}
if (buffer.length() == 0) {
// Stream was empty. No point in parsing.
return null;
}
getJsonStr = buffer.toString();
} catch (IOException e) {
return null;
} finally{
if (urlConnection != null) {
urlConnection.disconnect();
}
if (reader != null) {
try {
reader.close();
} catch (final IOException e) {
Log.e("Found in trouble", "Error closing stream", e);
}
}
}
try {
return getWeatherDataFromJson(getJsonStr,numDays);
}catch(JSONException ex){
ex.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String[] strings) {
super.onPostExecute(strings);
for(String s : strings)
Log.v("# onPostExecute",s);
vAdapter = new ArrayAdapter(getActivity(), R.layout.list_item_data,strings);
vAdapter.notifyDataSetChanged();
/*if(strings != null){
vAdapter.clear();
for(String dayForecast : strings){
vAdapter.add(dayForecast);
}
}*/
}
}
NOTE: the commented code in onPostExecute() method is also correct by means of logic but generating exception as UnsupportedOperationException while vAdapter.clear()
You can do this way:
onPostExecute() should looks like below:
#Override
protected void onPostExecute(String[] strings) {
super.onPostExecute(strings);
for(String s : strings)
Log.v("# onPostExecute",s);
vAdapter.clear();
vAdapter.addAll(strings);
vAdapter.notifyDataSetChanged();
}
That's it.
finally I found the solution.
I have used array while creating adapter in onCreate() method and trying to clear the adapter as vAdapter.clear() which is not possible. so to do this I just change the array with the List
at onCreate() method
String[] mArray = {"element1","element2",.....};
List<String> mList = new ArrayList<String>(Arrays.asList(mArray));
vAdapter = new ArrayAdappter(getActivity(),R.layout.list_item_data,mList);
at onPostExecute() method
vAdapter.clear();
vAdapter.addAll(strings);
thank you to all.