Reputation: 1744
I have a link where I'm providing 2 parameters and a php server side script is executing a query and writing them to my databae.
The problem is that in this specific case, it seems that I can't connect to teh url.
Here is my button xml file:
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:includeFontPadding="@+id/btnSubmit"
android:text="@string/btnSubmit"
android:onClick="submitNewJ"
/>
Here is my click "listener":
public void submitNewJ(View view){
new submitJ().execute();
}
And here is the submitJ
code:
public class submitJ extends AsyncTask<Void, Integer, Void>{
@Override
protected Void doInBackground(Void... params) {
try{
String encodedName = URLEncoder.encode(Name,"UTF-8");
String encodedBody = URLEncoder.encode(Body,"UTF-8");
URL url = new URL("http://site123.com/android/J/sJ.php?Name="+encodedName+"&Body="+encodedBody);
URLConnection urlConnection = url.openConnection();
@SuppressWarnings("unused")
InputStream in = urlConnection.getInputStream();
}catch(Exception e){
e.printStackTrace();
}
return null;
}
}
And here is how I'm getting the strings:
EditText jN;
EditText jB;
String Name = "";
String Body = "";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new_joke);
jN = (EditText)findViewById(R.id.newName);
jB = (EditText)findViewById(R.id.newBody);
Name = jN.getText().toString();
Body = jB.getText().toString();
}
It seems that the connection is not working here(even when I'm using the same code in otehr activities). Where am I mistaking? I know that I'm missing something super small, but I'm not able to spot it.
P.s. My service and link are 100% tested and working.
Upvotes: 1
Views: 64
Reputation: 744
The site you have in the example is probabbly for reference reasons, but mind that if it is using https
protocol and you're reffering to a http
, you will not get redirected to the correct link.
Everything in your code seems fine to me.
Just make sure that you're using the correct protocol.
Upvotes: 1
Reputation: 29670
You need to move these lines from onCreate()
method to doInBackground()
method,
Name = jN.getText().toString();
Body = jB.getText().toString();
put them inside the doInBackground() method like below,
public class submitJ extends AsyncTask<Void, Integer, Void>{
@Override
protected Void doInBackground(Void... params) {
try{
String Name = jN.getText().toString(); // move here and delete from the class
String Body = jB.getText().toString();
String encodedName = URLEncoder.encode(Name,"UTF-8");
String encodedBody = URLEncoder.encode(Body,"UTF-8");
URL url = new URL("http://site123.com/android/J/sJ.php?Name="+encodedName+"&Body="+encodedBody);
URLConnection urlConnection = url.openConnection();
@SuppressWarnings("unused")
InputStream in = urlConnection.getInputStream();
}catch(Exception e){
e.printStackTrace();
}
return null;
}
}
Upvotes: 1