at android.os.AsyncTask$3.done(AsyncTask.java:300) - java

i have a problem with a java code for Android. I will send a httpsRequest and i get back an JSON file. but i get a Error and i dont know why. I hope you can help me.
this is the LogCat what i get:
05-27 10:14:34.779: E/AndroidRuntime(24498): java.lang.RuntimeException: An error occured while executing doInBackground()
05-27 10:14:34.779: E/AndroidRuntime(24498): at android.os.AsyncTask$3.done(AsyncTask.java:300)
05-27 10:14:34.779: E/AndroidRuntime(24498): at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
05-27 10:14:34.779: E/AndroidRuntime(24498): at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
05-27 10:14:34.779: E/AndroidRuntime(24498): at java.util.concurrent.FutureTask.run(FutureTask.java:242)
05-27 10:14:34.779: E/AndroidRuntime(24498): at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
05-27 10:14:34.779: E/AndroidRuntime(24498): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
05-27 10:14:34.779: E/AndroidRuntime(24498): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
05-27 10:14:34.779: E/AndroidRuntime(24498): at java.lang.Thread.run(Thread.java:818)
05-27 10:14:34.779: E/AndroidRuntime(24498): Caused by: java.lang.IllegalArgumentException: HostnameVerifier is null
05-27 10:14:34.779: E/AndroidRuntime(24498): at javax.net.ssl.HttpsURLConnection.setDefaultHostnameVerifier(HttpsURLConnection.java:128)
05-27 10:14:34.779: E/AndroidRuntime(24498): at com.example.test.JSONTaskRegistrieren.doInBackground(JSONTaskRegistrieren.java:33)
05-27 10:14:34.779: E/AndroidRuntime(24498): at com.example.test.JSONTaskRegistrieren.doInBackground(JSONTaskRegistrieren.java:1)
05-27 10:14:34.779: E/AndroidRuntime(24498): at android.os.AsyncTask$2.call(AsyncTask.java:288)
05-27 10:14:34.779: E/AndroidRuntime(24498): at java.util.concurrent.FutureTask.run(FutureTask.java:237)
05-27 10:14:34.779: E/AndroidRuntime(24498): ... 4 more
My Code is
package com.example.test;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import org.json.JSONException;
import org.json.JSONObject;
import android.os.AsyncTask;
public class JSONTaskRegistrieren extends AsyncTask<String, String, String>{
private static final HostnameVerifier HostnameVerifier = null;
#Override
protected String doInBackground(String...params){
String Servicepass;
String SecretToken;
BufferedReader reader = null;
URL url;
try{
url = new URL(params[0]);
HttpsURLConnection.setDefaultHostnameVerifier(HostnameVerifier);
new NullHostnameVerifier();
HttpsURLConnection con = (HttpsURLConnection)url.openConnection();
con.setRequestMethod("GET");
con.setRequestProperty("Accept", "application/json");
con.setRequestProperty("WWSVC-REQID", "1");
InputStream stream = con.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String output;
while ((output = reader.readLine()) != null){
buffer.append(output);
}
String finalJson = buffer.toString();
//System.out.println(buffer.toString());
JSONObject parentObject = new JSONObject(finalJson);
JSONObject servicepassobjekt = parentObject.getJSONObject("SERVICEPASS");
//System.out.println(servicepassobjekt.toString());
StringBuffer finalBufferedData = new StringBuffer();
JSONObject finalObject = servicepassobjekt;
Servicepass = finalObject.getString("PASSID");
SecretToken = finalObject.getString("APPID");
return finalBufferedData.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result){
super.onPostExecute(result);
System.out.println(result);
}
}
and this is my Mainclass where i start the Request:
package com.example.test;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import javax.net.ssl.HttpsURLConnection;
import org.json.JSONArray;
import org.json.JSONObject;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import android.app.Activity;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button1 = (Button) findViewById(R.id.button1);
button1.setOnClickListener(new View.OnClickListener() {
#SuppressWarnings("unused")
public void onClick(View v) {
// ServiceURL
String ServiceURL = "https://192.168.0.64";
// Hersteller Hash
String HHash = "fa9b0dec3776ba123eba3049ec9f398h754";
// AppHash
String HAHash = "d20439ab3eabf9ebc3fae2c89b4869ai967";
// AppID
int AppID = 1;
new JSONTaskRegistrieren().execute(ServiceURL + "/WWSVC/WWSERVICE/REGISTER/"+HHash+"/"+HAHash+"/"+AppID+"/");
}});
}
}
Thank you very much for the help.

The piece to look for is the last Caused by: section of a stacktrace. In your case a IllegalArgumentException: HostnameVerifier is null which is caused by your code at com.example.test.JSONTaskRegistrieren.doInBackground(JSONTaskRegistrieren.java:33) (it's the first line mentioning your code)
From this you should find that the offending line of code is
HttpsURLConnection.setDefaultHostnameVerifier(HostnameVerifier);
and that the state of the HostnameVerifier variable at that point in time is null. When you check where assignments to that variable happen you see that the only time you assign something to it is at initialization time.
private static final HostnameVerifier HostnameVerifier = null;
Change that to
private static final HostnameVerifier HostnameVerifier = new NullHostnameVerifier();
and remove the line that did new NullHostnameVerifier();. It's creating a verifier and throws it away immediately since it's not stored in a variable.

HttpsURLConnection.setDefaultHostnameVerifier(HostnameVerifier);
HostnameVerifier argument sent here is null, as globally declared!
What is this statement for?
new NullHostnameVerifier();
Did you want to do HostnameVerfier = new NullHostnameVerifier();?

I think this variable is the cause
private static final HostnameVerifier HostnameVerifier = null;
you should use the following
url = new URL(params[0]);
HttpsURLConnection.setDefaultHostnameVerifier(url);

Related

I am creating an app for my drone, not working UDP

I am creating app that sends joystick data via UDP to my ESP32 at 192.168.4.1:1234 and whenever i try to send any data it crashes.
Crash Log:
2022-09-06 17:22:38.864 15388-15388/com.example.drnecontroller E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.drnecontroller, PID: 15388
android.os.NetworkOnMainThreadException
at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1668)
at java.net.Inet6AddressImpl.lookupHostByName(Inet6AddressImpl.java:115)
at java.net.Inet6AddressImpl.lookupAllHostAddr(Inet6AddressImpl.java:103)
at java.net.InetAddress.getByName(InetAddress.java:1106)
at com.example.drnecontroller.MainActivity.lambda$onCreate$0(MainActivity.java:44)
at com.example.drnecontroller.MainActivity$$ExternalSyntheticLambda0.onClick(Unknown Source:2)
at android.view.View.performClick(View.java:7441)
at com.google.android.material.button.MaterialButton.performClick(MaterialButton.java:1119)
at android.view.View.performClickInternal(View.java:7418)
at android.view.View.access$3700(View.java:835)
at android.view.View$PerformClick.run(View.java:28676)
at android.os.Handler.handleCallback(Handler.java:938)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loopOnce(Looper.java:201)
at android.os.Looper.loop(Looper.java:288)
at android.app.ActivityThread.main(ActivityThread.java:7839)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:548)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1003)
2022-09-06 17:22:38.911 393-393/? E/BpTransactionCompletedListener: Failed to transact (-32)
Client script:
package com.example.drnecontroller;
import androidx.appcompat.app.AppCompatActivity;
import android.annotation.SuppressLint;
import android.os.Bundle;
import android.widget.Button;
import android.widget.TextView;
import java.io.IOException;
import java.net.DatagramSocket;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.SocketException;
public class MainActivity extends AppCompatActivity {
#SuppressLint("SetTextI18n")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = (Button) findViewById(R.id.SubmitButton);
TextView IPAddrShow = (TextView) findViewById(R.id.IPAddressShow);
button.setOnClickListener(view -> {
try {
int port = 1234;
byte[] MSG;
DatagramSocket datagramSocket = new DatagramSocket();
InetAddress IP = InetAddress.getByName("localhost");
MSG = "HELLO".getBytes();
DatagramPacket datagramPacket = new DatagramPacket(MSG, MSG.length,IP,port);
datagramSocket.send(datagramPacket);
IPAddrShow.setText("Sent");
} catch(IOException e){
e.printStackTrace();
}
});
}
}
On android, you cannot use network from the UI thread.
All you have to do is to send your data from an other thread. I recommend using an executor.
For example by wrapping your code in a Runnable :
ExecutorService executor= Executors.newFixedThreadPool(1);
executor.submit(yourRunnable);

I keep getting a nullpointer exception with my JSON Object Calls

For some reason I keep getting a nullpointer exception with my double parsing. AFter further inquiry there seems to be some issue with my JSON Objects but I have no clue what the issue is.I am pulling JSON data form openweathermap api. I scuessfully pulled and printed the data into the log.i, however when I try to access with the JSONObject I am getting an error. Please help.
Code:
package com.anuraagy.myweather;
import android.app.Activity;
import android.app.ActionBar;
import android.app.Fragment;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.*;
import android.content.*;
import android.os.Build;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
public class MyActivity extends Activity {
private String s;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
if (savedInstanceState == null) {
getFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment())
.commit();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.my, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
private JSONObject myObject,mainObject,nameObject;
private ImageView myImage;
private TextView titleText;
private String hello,weatherName,max_temp,min_temp;
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_my, container, false);
RequestTask task = new RequestTask();
task.execute(new String[]{"http://api.openweathermap.org/data/2.5/weather?q=Ashburn&APPID=970bf0e4978dae293b065f8f2830ba58"});
return rootView;
}
public class RequestTask extends AsyncTask<String, String, String> {
private TextView myView;
private String s;
#Override
protected String doInBackground(String... uri) {
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response;
String responseString = null;
try {
response = httpclient.execute(new HttpGet(uri[0]));
StatusLine statusLine = response.getStatusLine();
if (statusLine.getStatusCode() == HttpStatus.SC_OK) {
ByteArrayOutputStream out = new ByteArrayOutputStream();
response.getEntity().writeTo(out);
out.close();
responseString = out.toString();
} else {
//Closes the connection.
response.getEntity().getContent().close();
throw new IOException(statusLine.getReasonPhrase());
}
} catch (ClientProtocolException e) {
//TODO Handle problems..
} catch (IOException e) {
//TODO Handle problems..
}
Log.i("", responseString);
return responseString;
}
#Override
protected void onPostExecute(String result){
Log.i("","hello");
super.onPostExecute(result);
try {
myObject = new JSONObject(result);
nameObject = myObject.getJSONObject("weather");
weatherName = nameObject.getString("main");
mainObject = myObject.getJSONObject("main");
Log.i("Wather Name",weatherName);
Log.i("mainObject",mainObject.toString());
hello = mainObject.getString("temp");
max_temp = mainObject.getString("temp_max");
min_temp = mainObject.getString("temp_min");
} catch(JSONException jsonException){
}
double f = Double.parseDouble(hello);
double max = Double.parseDouble(max_temp);
double min = Double.parseDouble(min_temp);
double realMax = (max - 273)* 1.8 + 32;
double realMin = (min - 273)* 1.8 + 32;
double realTemp = (max - 273)* 1.8 + 32;
int myMax = (int)realMax;
int myMin = (int)realMin;
int myWeather = (int)realTemp;
titleText = (TextView)getActivity().findViewById(R.id.textView3);
String fe = titleText.getText().toString();
fe.replace("definetly",weatherName);
myView = (TextView)getActivity().findViewById(R.id.textView);
// if()
// {
//
// }
// else
// {
//
// }
myImage = (ImageView)getActivity().findViewById(R.id.imageView);
myImage.setImageResource(R.drawable.clearnight);
String weather = myWeather + "";
myView.setText(weather + (char) 0x00B0 +"F");
// //Do anything with response..
}
}
}
}
Error:
10-16 10:01:26.398 664-664/com.anuraagy.myweather E/Trace﹕ error opening trace file: No such file or directory (2)
10-16 10:01:35.058 664-668/com.anuraagy.myweather D/dalvikvm﹕ GC_CONCURRENT freed 75K, 2% free 11112K/11335K, paused 17ms+3ms, total 312ms
10-16 10:01:35.058 664-664/com.anuraagy.myweather D/dalvikvm﹕ WAIT_FOR_CONCURRENT_GC blocked 282ms
10-16 10:01:35.498 664-664/com.anuraagy.myweather D/gralloc_goldfish﹕ Emulator without GPU emulation detected.
10-16 10:01:38.388 664-680/com.anuraagy.myweather I/﹕ {"coord":{"lon":-77.49,"lat":39.04},"sys":{"type":1,"id":2856,"message":0.0194,"country":"US","sunrise":1413458470,"sunset":1413498574},"weather":[{"id":701,"main":"Mist","description":"mist","icon":"50d"},{"id":721,"main":"Haze","description":"haze","icon":"50d"},{"id":741,"main":"Fog","description":"fog","icon":"50d"}],"base":"cmc stations","main":{"temp":288.03,"pressure":1008,"humidity":100,"temp_min":286.15,"temp_max":290.15},"wind":{"speed":2.86,"deg":261.502},"clouds":{"all":90},"dt":1413468071,"id":4744870,"name":"Ashburn","cod":200}
10-16 10:01:38.398 664-664/com.anuraagy.myweather I/﹕ hello
10-16 10:01:38.438 664-664/com.anuraagy.myweather D/AndroidRuntime﹕ Shutting down VM
10-16 10:01:38.438 664-664/com.anuraagy.myweather W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0x40a13300)
10-16 10:01:38.448 664-664/com.anuraagy.myweather E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.NullPointerException
at java.lang.StringToReal.parseDouble(StringToReal.java:244)
at java.lang.Double.parseDouble(Double.java:295)
at com.anuraagy.myweather.MyActivity$PlaceholderFragment$RequestTask.onPostExecute(MyActivity.java:141)
at com.anuraagy.myweather.MyActivity$PlaceholderFragment$RequestTask.onPostExecute(MyActivity.java:91)
at android.os.AsyncTask.finish(AsyncTask.java:631)
at android.os.AsyncTask.access$600(AsyncTask.java:177)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:644)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4745)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
Be careful - "weather" is a JSONArray, not a JSONObject. The NullPointerException is likely due to that.
Try instead using myObject.getJSONArray("weather"), and from there iterate through the JSONObjects inside.
See here for more information on that last part: Accessing members of items in a JSONArray with Java
It looks like myObject doesn't have item named "temp", so:
- on line 133 you set hello to null
- on line 141 you pass that null to Double.parseDouble()
- get your exception because class Double can't digest null
That's it!
Check it in the debugger, but I'm almost sure - according to your stack trace

Line -> JSONArray jArray=new JSONArray(result); giving nullpointer exception

package com.example.fyptrialapp;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONObject;
import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.StrictMode;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
public class SearchByName extends Activity{
HttpPost httppost;
StringBuffer buffer;
HttpResponse response;
HttpClient httpclient;
InputStream inputStream=null;
Intent i;
//public static final String recipes[]=new String[]{"Almond-Sheera","Bhel","Bread-Pizzas","Carrot-Pickle","Carrot-Relish"};
String recipes[];
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.search_recipe);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
Button b2=(Button)findViewById(R.id.bSearchByName);
try{
httpclient = new DefaultHttpClient();
httppost = new HttpPost("http://10.0.2.2/fypTrial2/searchByName.php");
response = httpclient.execute(httppost); // Execute HTTP Post Request
inputStream = response.getEntity().getContent();
String result=null;
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line=null;
while((line=reader.readLine())!= null){
sb.append(line+"\n");
}
inputStream.close();
result=sb.toString();
JSONArray jArray=new JSONArray(result);// this statment gives error
for(int i=0;i<jArray.length();i++){
JSONObject json=jArray.getJSONObject(i);
recipes[i]=json.getString("name");
}
}
catch(Exception e){
Log.e("log_tag3", "Error convering result"+e.toString());
}
ArrayAdapter<String> ac=new ArrayAdapter<String>(this,android.R.layout.simple_dropdown_item_1line,recipes);
AutoCompleteTextView tv=(AutoCompleteTextView) findViewById(R.id.autoCompleteTextView2);
tv.setAdapter(ac);
b2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i=new Intent("com.example.practice.Search_Result");
startActivity(i);
}
});
}
}
ERROR
java.nullpointerexception. Error converting result variable.And the
fatal main error
If i want to use ASnk task how should i write it.
JSON syntax never starts as an array. It could be that it starts with { followed by [, but never straight to [. This is why trying to convert your results to JSONArray will not work. You should therefor try to get the object first, then the array elements.
JSONObject jo = new JSONObject(result);
JSONArray jArray = jo.getJSONArray("keyIdentifyer");
If you dont have the array key identifyer, you could try to iterate or get the first element. See this post answear on iterations when no keys are present.
You should indeed use AsyncTask for the networking part. Your app probably already crashes with a NetworkOnMainThread error follow this link for the usasge of AsyncTask.
But that besides, you are providing to little code to point to a reason for the NullPointerException. You should always check if an object is not null if it may occur it is.
try{
//your code
}catch(NullPointerException ex){
ex.printStackTrace();
}

Android not sending mail

I am creating a application which gets the input from edit text and sends a mail acording to the information.I am using Http post to do this i want to communicate with the Php script to send the mail please have a look at my code..
Php script
<?php
$name = $_POST['name'];
$to = $_POST['to'];
$from = $_POST['from'];
$subject = $_POST['subject'];
$message = "From: ".$name."\r\n";
$message .= $_POST['message'];
$headers = "From:" . $from;
mail($to,$subject,$message,$headers);
?>
my Activity:
package dolphin.developers.com;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import dolphin.devlopers.com.R;
public class misc1 extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.eamilspoof);
EditText textw =(EditText) findViewById(R.id.editText1);
final String strd = textw.getText().toString();
EditText textw3 =(EditText) findViewById(R.id.editText2);
final String strd3 = textw3.getText().toString();
EditText textw3d =(EditText) findViewById(R.id.editText3d);
final String strd3d = textw3d.getText().toString();
EditText textw3dd =(EditText) findViewById(R.id.editText3);
final String name = textw3d.getText().toString();
EditText textw3df =(EditText) findViewById(R.id.editText4);
final String subject = textw3d.getText().toString();
Button pds = (Button)findViewById(R.id.button1d);
pds.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
String site = "www.dolphin123.net78.net/mailer.php";
String namer1 = name;
String to = strd;
String from = strd3;
String subject1 = subject;
String message = strd3d;
String content = "";
try
{
/* Sends data through a HTTP POST request */
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(site);
List <NameValuePair> params = new ArrayList <NameValuePair> ();
params.add(new BasicNameValuePair("name", namer1));
params.add(new BasicNameValuePair("to", to));
params.add(new BasicNameValuePair("from", from));
params.add(new BasicNameValuePair("subject", subject1));
params.add(new BasicNameValuePair("message", message));
httpPost.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
/* Reads the server response */
HttpResponse response = httpClient.execute(httpPost);
InputStream in = response.getEntity().getContent();
StringBuffer sb = new StringBuffer();
int chr;
while ((chr = in.read()) != -1)
{
sb.append((char) chr);
}
content = sb.toString();
in.close();
/* If there is a response, display it */
if (!content.equals(""))
{
Log.i("HTTP Response", content);
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
});
};
}
}
Logcat :
08-10 17:55:20.405: W/System.err(12988): java.lang.IllegalStateException: Target host must not be null, or set in parameters. scheme=null, host=null, path=www.dolphin123.net78.net/mailer.php
08-10 17:55:20.405: W/System.err(12988): at org.apache.http.impl.client.DefaultRequestDirector.determineRoute(DefaultRequestDirector.java:591)
08-10 17:55:20.405: W/System.err(12988): at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:293)
08-10 17:55:20.405: W/System.err(12988): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:670)
08-10 17:55:20.405: W/System.err(12988): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:509)
08-10 17:55:20.410: W/System.err(12988): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
08-10 17:55:20.410: W/System.err(12988): at dolphin.developers.com.misc1$1.onClick(misc1.java:87)
08-10 17:55:20.410: W/System.err(12988): at android.view.View.performClick(View.java:4211)
08-10 17:55:20.410: W/System.err(12988): at android.view.View$PerformClick.run(View.java:17267)
08-10 17:55:20.410: W/System.err(12988): at android.os.Handler.handleCallback(Handler.java:615)
08-10 17:55:20.410: W/System.err(12988): at android.os.Handler.dispatchMessage(Handler.java:92)
new Log:
08-05 13:08:17.365: D/SntpClient(73): request time failed: java.net.SocketException: Address family not supported by protocol
Prepend the protocol to the String representation of your URI.
So it should be: "http://www.dolphin123.net78.net/mailer.php"
You can your url with above url with prepend http://

Having trouble connecting to webservice through android

I am currently having trouble connecting to my webservice on android. I am using a Jetty web service and building it using ANT. On my laptop it works perfectly and displays items from my database. However it won't seem to connect on my Android application. Attached is the code and LOGCAT report.
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import android.app.Activity;
import android.os.Bundle;
import android.widget.EditText;
import android.widget.TextView;
public class Android2Servlet extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dbtest);
TextView txtresp = (TextView)findViewById(R.id.servlet_response);
String url = "http://(MY LAPTOPS IP):8085/DB";
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet(url);
try{
System.out.println("About to execute");
HttpResponse response = client.execute(request);
String helpedResp=HttpUnpack.request(response);
System.out.println(helpedResp);
txtresp.setText(helpedResp);
System.out.println(response);
}catch(Exception ex){
txtresp.setText("Failed!");
ex.printStackTrace();
}
} }
The HTTP Unpack File
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.apache.http.HttpResponse;
public class HttpUnpack {
public static String request(HttpResponse response){
String result = "";
try{ InputStream in = response.getEntity().getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder str = new StringBuilder();
String line = null;
while((line = reader.readLine()) != null){
str.append(line + "\n");
}
in.close();
result = str.toString();
}catch(Exception ex){
result = "Error retrieving response";
}
return result;
}
}
The HTTP Unpack and the Android2Servlet do not cause any errors, however the text box only returns "Failed!".
LOGCAT file
W/System.err(1282): android.os.NetworkOnMainThreadException
W/System.err(1282): at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1099)
W/System.err(1282): at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:84)
W/System.err(1282): at libcore.io.IoBridge.connectErrno(IoBridge.java:127)
W/System.err(1282): at libcore.io.IoBridge.connect(IoBridge.java:112)
W/System.err(1282): at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:192)
W/System.err(1282): at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:459)
W/System.err(1282): at java.net.Socket.connect(Socket.java:842)
W/System.err(1282): at org.apache.http.conn.scheme.PlainSocketFactory.connectSocket(PlainSocketFactory.java:119)
W/System.err(1282): at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:144)
W/System.err(1282): at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
W/System.err(1282): at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
W/System.err(1282): at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
W/System.err(1282): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
W/System.err(1282): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
W/System.err(1282): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
W/System.err(1282): at myFood.myFood.Android2Servlet.onCreate(Android2Servlet.java:24)
W/System.err(1282): at android.app.Activity.performCreate(Activity.java:4465)
W/System.err(1282): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)
W/System.err(1282): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1920)
W/System.err(1282): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1981)
W/System.err(1282): at android.app.ActivityThread.access$600(ActivityThread.java:123)
W/System.err(1282): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1147)
W/System.err(1282): at android.os.Handler.dispatchMessage(Handler.java:99)
W/System.err(1282): at android.os.Looper.loop(Looper.java:137)
W/System.err(1282): at android.app.ActivityThread.main(ActivityThread.java:4424)
W/System.err(1282): at java.lang.reflect.Method.invokeNative(Native Method)
W/System.err(1282): at java.lang.reflect.Method.invoke(Method.java:511)
W/System.err(1282): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
W/System.err(1282): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
W/System.err(1282): at dalvik.system.NativeStart.main(Native Method)
Any response would be greatly helpful.
Regards.
EDIT:
I have now removed the network access and put it in another Java class. And called it form another class. And it is still returning the same errors. Any other advice?
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
public class androidconnectors {
public static final String main(String args[]) throws Exception {
String txtresp = "";
try{
String url = "http://(LAPTOPS IP):8085/Hello";
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet(url);
System.out.println("About to execute");
HttpResponse response = client.execute(request);
String helpedResp=HttpUnpack.request(response); // Http Unpack is not part of
System.out.println(helpedResp); // of HttpClient library
txtresp =(helpedResp);
System.out.println(response);
}catch(Exception ex){
ex.printStackTrace();
}
return txtresp;
}
}
And the android class.
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class Settings extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dbtest);
Button mybutton = (Button) findViewById(R.id.buttonpress);
mybutton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
TextView txtresp = (TextView)findViewById(R.id.servlet_response);
String[] args = null;
try {
String x = androidconnectors.main(args);
txtresp.setText(x);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
txtresp.setText("Failed");
}
}
});
}
}
It would seem, based on a quick google search, that since Honeycomb you are not supposed to execute network access on your app's main thread (to improve responsiveness).
Create another thread for network access as suggested here.
You can't do Network Operations on the UI Thread better use AsyncTask/Service/IntentService
NetworkOnMainThreadException
The exception that is thrown when an application attempts to perform a
networking operation on its main thread.(Since API 11)
To resovled StrictMode issue you need to use below code in your activity -
static{
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}

Categories