I understand the point of the android.os.NetworkOnMainThreadException that targets HoneyComb devices but the following code throws the same exception:
class MakeRequest extends AsyncTask<String,Integer,Void>
{
#Override
protected Void doInBackground(String... params) {
DefaultHttpClient cli = new DefaultHttpClient();
try {
String url = params[0].replace(" ", "%20");
HttpResponse resp = cli.execute(new HttpGet(url));
BufferedReader read = new BufferedReader(new InputStreamReader(resp.getEntity().getContent()));
String tmp = "",rezultat = "";
setResult("");
while ((tmp = read.readLine()) != null)
{
rezultat = rezultat + tmp;
}
setResult(rezultat);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
setResult("");
return null;
}
return null;
}
//Sample call
HttpRequester cc = new HttpRequester();
MakeRequest test = cc.new MakeRequest();
test.doInBackground(url);
try this.
new MakeRequest().execute(url);
Related
I'm using Asynctask to pass the parameters of API. The Asynctask executing but the String Response in Asynctask PostExecute giving me a null for a device with SDK 23 and below. But when the device is equal or higher to SDK24(Nougat), it works perfectly and the data are being sent to the API however when the SDK is 23 and lower data are not being sent to API. Does anyone encounter this problem? Please enlighten me what I miss in my code or I do wrong code. Massive thank you.
private class sendToServerOfficial extends AsyncTask<String,Void,String> {
int statusCodeone;
String convert_txt_et_username = et_username.getText().toString();
String convert_txt_content = et_content.getText().toString();
#Override
protected String doInBackground(String... strings) {
try {
urlURL = new URL("http://www.testingsite.com/api/sendServer?/ip="+getIPAddress+"&phone_num="+getMobilePhoneNumber+"&user_text="+convert_txt_et_username+"&content_text="+convert_txt_content);
HttpURLConnection httpURLConnection = (HttpURLConnection) urlURL.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setRequestProperty("Content-Type","UTF-8");
httpURLConnection.connect();
statusCodeone = httpURLConnection.getResponseCode();
if (statusCodeone == 200) {
InputStream it = new BufferedInputStream(httpURLConnection.getInputStream());
InputStreamReader read = new InputStreamReader(it);
BufferedReader buff = new BufferedReader(read);
StringBuilder dta = new StringBuilder();
String chunks;
while ((chunks = buff.readLine()) != null) {
dta.append(chunks);
}
buff.close();
read.close();
return dta.toString();
}
}
catch (ProtocolException e) { e.printStackTrace(); }
catch (MalformedURLException e) { e.printStackTrace(); }
catch (IOException e) { e.printStackTrace(); }
return null;
}
#Override
protected void onPostExecute(String response) {
Toast.makeText(MainActivity.this, response + "Form is submitted already" + urlURL, Toast.LENGTH_LONG).show();
txt_inputURL.setEnabled(true);
btnClick.setClickable(true);
txt_inputURL.getText().clear();
}
}
The main problem is I'm unable to return two value help. i have tried lot of time but no success. And guys I'm new to this so please write your answer with respect to my code thanks in advance.
Here's my code
public class calculate extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
try {
uss = getJson("http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.xchange%20where%20pair%20in%20(%22INRUSD%22)&format=json&diagnostics=true&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&callback=");
JSONObject usjObj;
usjObj = new JSONObject(uss);
usResult = usjObj.getJSONObject("query").getJSONObject("results").getJSONObject("rate").getString("Rate");
eurr = getJson("http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.xchange%20where%20pair%20in%20(%22INREUR%22)&format=json&diagnostics=true&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&callback=");
JSONObject eurjObj;
eurjObj = new JSONObject(eurr);
eurResult = eurjObj.getJSONObject("query").getJSONObject("results").getJSONObject("rate").getString("Rate");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return eurResult + usResult;
////PROBLEM IS HERE ACTUALLY I DON'T KNOW HOW TO RETURN TWO OR MORE VALUE/////"
}
#Override
protected void onPostExecute(String usResult) {
valueus = Double.parseDouble(usResult);
inputus = lengthvalue * valueus;
us.setText("" + inputus);
valueeur = Double.parseDouble(eurResult);
inputeur = lengthvalue * valueeur;
eur.setText("" + inputeur);
}
}
public String getJson(String url) throws ClientProtocolException, IOException {
StringBuilder build = new StringBuilder();
HttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
HttpResponse response = client.execute(httpGet);
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(content));
String con;
while ((con = reader.readLine()) != null) {
build.append(con);
}
return build.toString();
}
}
You should not try to cram everything into a String. There are better data structures to hold multiple values: array, Vector, List, etc. Declare your AsyntTask as:
public class calculate extends AsyncTask<String, String, String[]>
and then your doInBackgorund method would be something like this:
#Override
protected String doInBackground(String... params) {
String[] result = new String[numResults];
...
result[0] = usjObj.getJSONObject("query").getJSONObject("results").getJSONObject("rate").getString("Rate");
...
result[1] = usjObj.getJSONObject("query").getJSONObject("results").getJSONObject("rate").getString("Rate");
...
return result;
}
And finally your onPostExecute would be
#Override
protected void onPostExecute(String[] usResult) {
...
}
I would like to retrieve the contents of my variable "$content" in my activity.
But I don't know how to use the return value of my doinbackground.
Can you help me ?
thank you in advance
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String restURL = "https://proxyepn-test.epnbn.net/wsapi/epn";
RestOperation test = new RestOperation();
test.execute(restURL);
}
private class RestOperation extends AsyncTask<String, Void, String> {
//final HttpClient httpClient = new DefaultHttpClient();
String content;
String error;
ProgressDialog progressDialog = new ProgressDialog(MainActivity.this);
String data = "";
TextView serverDataReceived = (TextView)findViewById(R.id.serverDataReceived);
TextView showParsedJSON = (TextView) findViewById(R.id.showParsedJSON);
// EditText userinput = (EditText) findViewById(R.id.userinput);
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog.setTitle("Please wait ...");
progressDialog.show();
}
#Override
protected String doInBackground(String... params) {
BufferedReader br = null;
URL url;
try {
url = new URL(params[0]);
URLConnection connection = url.openConnection();
connection.setDoOutput(true);
OutputStreamWriter outputStreamWr = new OutputStreamWriter(connection.getOutputStream());
outputStreamWr.write(data);
outputStreamWr.flush();
br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
while((line = br.readLine())!=null) {
sb.append(line);
sb.append(System.getProperty("line.separator"));
}
content = sb.toString();
} catch (MalformedURLException e) {
error = e.getMessage();
e.printStackTrace();
} catch (IOException e) {
error = e.getMessage();
e.printStackTrace();
} finally {
try {
br.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return content;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
progressDialog.dismiss();
if(error!=null) {
serverDataReceived.setText("Error " + error);
} else {
serverDataReceived.setText(content);
String output = "";
JSONObject jsonResponse;
try {
jsonResponse = new JSONObject(content);
JSONArray jsonArray = jsonResponse.names();
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject child = jsonArray.getJSONObject(i);
String name = child.getString("name");
String number = child.getString("number");
String time = child.getString("date_added");
output = "Name = " + name + System.getProperty("line.separator") + number + System.getProperty("line.separator") + time;
output += System.getProperty("line.separator");
Log.i("content",content);
}
showParsedJSON.setVisibility(View.INVISIBLE);
showParsedJSON.setText(output);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
You can directly call to the method which exist in activity, from onPostExecute method of asynctask by passing "content" value.
#Override
protected void onPostExecute(String content) {
Activity.yourMethod(content);
}
If you want to return the value from asynctask you can use
content = test.execute(url).get();
but it is not a good practice of asynctask, because it is working as serial execution. So it is not fulfill the use of asynctask for palatalization.Because get() will block the UI thread.
I've tried searching the internet for solution unfortunately I could not find the answer. I tried using try catch to catch error exception but still it won't work.
Here's my code. I have private class LoginTask
private class LoginTask extends AsyncTask<String,String,JSONObject> {
private String[] privateCredentials;
private String privateRequest;
private String errorMessage = "";
//initialize all here
//constructor
LoginTask(String[] credentials,String request) {
this.privateRequest = request;
this.privateCredentials = credentials;
}
#Override
protected void onPostExecute(JSONObject result) {
super.onPostExecute(result);
if(this.privateRequest=="login"){
try {
String response = result.getString("status");
if(response.equals("ok")){
onLoginSuccess(result.getString("username"),result.getString("full_name"),result.getInt("user_id"));
}else{
onLoginFails();
}
} catch (JSONException e) {
if(errorMessage!=""){
Toast ts;
ts = Toast.makeText(LoginActivity.this,errorMessage,Toast.LENGTH_LONG);
ts.show();
}
//e.printStackTrace();
}
}
}
#Override
protected JSONObject doInBackground(String... params) {
String result = "";
JSONObject resultObj = null;
HttpURLConnection con = null;
BufferedReader br = null;
JSONObject cred = new JSONObject();
if(this.privateRequest=="login"){
try {
cred.put("username", this.privateCredentials[0]);
cred.put("password", this.privateCredentials[1]);
URL url = new URL(params[0]);
con = (HttpURLConnection) url.openConnection();
;
con.setDoOutput(true);
con.setDoInput(true);
con.setRequestProperty("Content-Type", "application/json");
con.setRequestProperty("Accept", "application/json");
con.setRequestMethod("POST");
con.connect();
OutputStream outputStream = con.getOutputStream();
outputStream.write(cred.toString().getBytes());
InputStream stream = con.getInputStream();
br = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = br.readLine()) != null) {
buffer.append(line);
}
//get the result
JSONObject jsonObj = new JSONObject(buffer.toString());
resultObj = jsonObj;
// return buffer.toString();
}catch (JSONException e) {
errorMessage = e.getMessage();
final String error = e.getMessage();
//e.printStackTrace();
runOnUiThread(new Runnable(){
public void run() {
//ErrorDialog(e.getMessage());
Toast ts;
ts = Toast.makeText(LoginActivity.this,error,Toast.LENGTH_LONG);
ts.show();
}
});
} catch (ProtocolException e) {
errorMessage = e.getMessage();
final String error = e.getMessage();
//e.printStackTrace();
runOnUiThread(new Runnable(){
public void run() {
//ErrorDialog(e.getMessage());
Toast ts;
ts = Toast.makeText(LoginActivity.this,error,Toast.LENGTH_LONG);
ts.show();
}
});
//e.printStackTrace();
} catch (IOException e) {
errorMessage = e.getMessage();
final String error = e.getMessage();
//e.printStackTrace();
runOnUiThread(new Runnable(){
public void run() {
//ErrorDialog(e.getMessage());
Toast ts;
ts = Toast.makeText(LoginActivity.this,error,Toast.LENGTH_LONG);
ts.show();
}
});
//e.printStackTrace();
} finally {
if(con!=null) {
con.disconnect();
}
}
return resultObj;
}
return null;
}
}
And here's my event listener code in the login activity.
//when clicking the login button
loginBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//do now the login process
userText.setVisibility(view.INVISIBLE);
passwordText.setVisibility(view.INVISIBLE);
tvRegister.setVisibility(view.INVISIBLE);
umlogo.setVisibility(view.INVISIBLE);
//set textviews to invisible
/* tv[0].setVisibility(view.INVISIBLE);
tv[1].setVisibility(view.INVISIBLE);*/
//set also the button to invisible
loginBtn.setVisibility(view.INVISIBLE);
//set visible the progress bar
pb.setVisibility(view.VISIBLE);
//set now the user login credentials
credentials[0] = userText.getText().toString();
credentials[1] = passwordText.getText().toString();
loginTask = new LoginTask(credentials,"login");
//loginTask.execute("http://10.0.2.2/sampleRequest.php");
//loginTask.execute("http://10.0.2.2/motorpool_june_2016_laravel/public/mobile/login");
loginTask.execute("http://128.199.105.49/mobile/login");
//SessionHolder.login(credentials, la);
}
});
However it is still not working. Please help. :(
You can't compare Strings with == in java. You must write it like below:
if(this.privateRequest.equals("login")){
== tests for reference equality (whether they are the same object)
I require a GET reequest from my own server to be extracted from the web and then displayed on screen with a TextView.
I have set up a GET Request.
public class GetMethodEx {
public String getInternetData() throws Exception{
BufferedReader in = null;
String data = null;
try
{
HttpClient client = new DefaultHttpClient();
URI website = new URI("http://www.mybringback.com");
HttpGet request = new HttpGet();
request.setURI(website);
HttpResponse response = client.execute(request);
in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String l = "";
String nl = System.getProperty("line.separator");
while ((l = in.readLine()) !=null){
sb.append(l + nl);
}
in.close();
data = sb.toString();
return data;
} finally{
if (in != null){
try{
in.close();
return data;
}catch (Exception e){
e.printStackTrace();
}
}
}
}
}
And I have set up on my main thread to extract the information and display it in a text view.
public class Home extends Activity {
TextView httpStuff;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.httpexample);
httpStuff = (TextView) findViewById(R.id.tvhttp);
GetMethodEx test = new GetMethodEx();
String returned;
try {
returned = test.getInternetData();
httpStuff.setText(returned);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
However, the Textview doesnt seem to change?
Can someone help me please.
Change your code using AsyncTask if you want to make any network operation from Ui Thread as:
public class Home extends Activity {
TextView httpStuff;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.httpexample);
httpStuff = (TextView) findViewById(R.id.tvhttp);
new LongOperation().execute("");
}
private class LongOperation extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
GetMethodEx test = new GetMethodEx();
String returned;
try {
returned = test.getInternetData();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return returned;
}
#Override
protected void onPostExecute(String result) {
// Update Ui here
httpStuff.setText(result);
}
}
}
Android OS > = 3.0
does not allow NetworkRequest on main UI thread.
Use AsyncTask to call webrequest.