I'm new to Android and after a long time I finally manage to create a database using PHP scripts and MySQL.
While I'm using the Android Studio emulator I do succeed sending data to the database but when I run the application on my device I failed to do so.
I don't get any error and the app keeps running (not crushing) but the database doesn't get the data.
This is the doInbackground method in my BackgroundTask class:
#Override
// send info to MySQL DB
// it gets 4 parameters - the first if the opertaion should be "register" and the others are
// user info (name,pass,gender)
protected String doInBackground(String... params) {
// the ip is default for localhost
String reg_url = "http://**MyIP**/webapp/register.php";
String login_url = "http://**MyIP**/webapp/login.php";
String method = params[0];
if (Objects.equals(method, "register")){
String userName = params[1];
String userPass = params[2];
String gender = params[3];
try {
URL url = new URL(reg_url);
// run the register php script.
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
OutputStream OS = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(OS, "UTF-8"));
// applied the "userName,"userPass" and "gender" that I define in the POST (at the register.php)
// the info the user typed.
String data = URLEncoder.encode("userName", "UTF-8") + "=" + URLEncoder.encode(userName,"UTF-8") + "&" +
URLEncoder.encode("userPass", "UTF-8") + "=" +URLEncoder.encode(userPass,"UTF-8") + "&" +
URLEncoder.encode("gender", "UTF-8") + "=" +URLEncoder.encode(gender,"UTF-8");
// write the data to server
bufferedWriter.write(data);
bufferedWriter.flush();
bufferedWriter.close();
OS.close();
InputStream IS = httpURLConnection.getInputStream();
IS.close();
return "Registration Successs";
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
you want to do setting of the wampp server in your pc. i will give a URL for doing your work. please any query ask for it.
http://androidcss.com/android/test-android-app-php-localhost-wamp/
Connect your PC and android device to same wifi network.
If your running on windows enter ipconfig on cmd and if it is ubuntu run ifconfig on terminal to get ip address
it'll be like 192.168.0.*. If **MyIP** and IP Address which you've got are same then ignore it.
Be Sure that you've given permissions to access internet in manifest file.
Related
I am trying to submit data from Android to my php server. However all the answers seem to use the deprecated apache http library. I do not want to use that, and when I tried it didn't work.
Right now it it does not seem to do anything. It seems to connect to the web server, but the server does not write any data. If I just visit the url with the browser, it will write to a file.
The php code is
<?php
// get the "message" variable from the post request
// this is the data coming from the Android app
$message=$_POST["message"];
// specify the file where we will save the contents of the variable message
$filename="androidmessages.html";
// write (append) the data to the file
file_put_contents($filename,$message."<br />",FILE_APPEND);
// load the contents of the file to a variable
$androidmessages=file_get_contents($filename);
// display the contents of the variable (which has the contents of the file)
echo $androidmessages;
?>
Then in Android studio, I am putting all of the code after a button press
loginButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
loadingProgressBar.setVisibility(View.VISIBLE);
loginViewModel.login(usernameEditText.getText().toString(),
passwordEditText.getText().toString());
System.out.println("This is a test");
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
try {
//Your code goes here
URL url = null;
OutputStream out = null;
String urlString = "https://mywebsite.net/php_script.php";
String data = "HelloWorld"; //data to post
try {
url = new URL(urlString);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("POST");
urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
urlConnection.setDoOutput(true);
out = new BufferedOutputStream(urlConnection.getOutputStream());
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(out, "UTF-8"));
writer.write(data);
writer.flush();
writer.close();
out.close();
urlConnection.connect();
} catch (IOException e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
}
});
thread.start();
}
});
}
Your PHP code is looking for a variable in $_POST called "message"
$message=$_POST["message"];
However in your Android code your just writing your message data to the http request body.
I suggest looking into Volley which is an HTTP library, and allows for easily making HTTP requests. This answer might also be of help.
You can use JSON and Volley for this!
<?php
$data = json_decode(file_get_contents('php://input'), true);
$filename="androidmessages.html";
file_put_contents($filename,$data["message"]."<br />",FILE_APPEND);
$reponse = array("message" => $androidmessages=file_get_contents($filename));
echo json_encode($reponse);
?>
and this in android (Kotlin):
private fun sendHtmlRequest(view: View){
val jsonobj = JSONObject()
var url = "https://URL.php"
jsonobj.put("message", "test message")
val que = Volley.newRequestQueue(context)
val req = JsonObjectRequest(Request.Method.POST, url, jsonobj,
Response.Listener { response: JSONObject ->
val messageResponse = response.getString("message")
println("response: $messageResponse")
}, Response.ErrorListener{
println("Error")
}
)
que.add(req)
}
I'm having troubles with encoding text from Android EditText when sending it with JSON to PHP script.
First in Android I get the text from EditText element.
String s = editText.getText().toString();
then I post it throught HttpURLConnection to PHP script
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
conn.setRequestProperty("Accept", "application/json");
conn.setDoOutput(true);
conn.setDoInput(true);
JSONObject jsonParam = new JSONObject().put("mystring", s);
DataOutputStream os = new DataOutputStream(conn.getOutputStream());
os.writeBytes(jsonParam.toString());
os.flush();
os.close();
then I parse the JSON in PHP script:
$data = json_decode(utf8_decode(file_get_contents('php://input')), true);
Everything works fine, but when I try to send some text with diacritics it seems that nothing is send and var_dump($data) is null. Is there something wrong with the formating or what could be the problem?
Thanks for help.
EDIT
Elsunhoty answer works but I have to use urldecode() in PHP
you can try to trim Your Text First
String s = editText.getText().toString();
s = s.trim();
and then Encode the Text
String encodeText= "";
try {
encodeText= URLEncoder.encode(s,"utf-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
I made a php application at the following url: http://localhost/index.php/registration/returnItemJson to return this valid json:
{"name":"test","price":30,"description":"is this working"}
In my android studio app, I am trying to read it with this:
URL url = new URL(strings[0]);
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setDoInput(true);
connection.setDoOutput(true);
connection.connect();
int response = connection.getResponseCode();
Log.d("TAG", "Response code "+response);
StringBuilder result = new StringBuilder();
reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String line;
while(null != (line = reader.readLine())){
result.append(line).append("\n");
}
But I am getting an IO exception by connection.GetInputStream().
It works ok when I do this with some other url that returns json, but not with localhost.
Use 10.0.2.2 instead to access your local host. Read more here
I try post json from Android client to PHP server but failed, server cannot receive any data, I don't see what's wrong with it, so I need help, thanks a lot.
this is Android client kernel code:
String result;
String encoding="UTF-8";
String params="{\"name\":\"123\",\"pass\":\"456\"}";
try {
byte[] data=params.getBytes(encoding);
URL urls=new URL(url);
HttpURLConnection conn=(HttpURLConnection) urls.openConnection();
conn.setRequestMethod("POST");
conn.setDoOutput(true);
conn.setRequestProperty("Content-Type", "application/x-javascript; charset="+ encoding);
conn.setRequestProperty("Content-Length", String.valueOf(data.length));
conn.setReadTimeout(4000);
OutputStream outStream = conn.getOutputStream();
outStream.write(data);
outStream.flush();
outStream.close();
BufferedReader bfread=new BufferedReader(new InputStreamReader(conn.getInputStream()));
String str;
StringBuffer resb=new StringBuffer();
while ((str=bfread.readLine())!=null)
{
resb.append(str);
}
result=resb.toString();
and this is server code:
<?php
$data = file_get_contents('php://input');
if(empty($data))
{
echo "no post data";
}
else
{
print_r($data);
}
?>
android client get the message from server and print on screen, they always show "no post data", obviously client visit server successful, but server not received any data. Then I write a test HTML page to post the data with form, it works. I don't know why.
We are trying to send a large JSON object (with 100+ key value pairs) from an android app to server using following code.
URL url = new URL(urlString);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
JSONObject dt = new JSONObject();
try {
dt.put("test", "test");
} catch (JSONException e) {
e.printStackTrace();
}
urlConnection.setDoOutput(true);
// is output buffer writter
urlConnection.setRequestMethod("POST");
urlConnection.setRequestProperty("Content-Type", "application/json");
urlConnection.setRequestProperty("Accept", "application/json");
//set headers and method
Writer writer = new BufferedWriter(new OutputStreamWriter(urlConnection.getOutputStream(), "UTF-8"));
writer.write(String.valueOf(dt));
// json data
writer.close();
and in server side PHP,
$data = json_decode(file_get_contents('php://input'));
echo (string) $data;
But it returns blank value, how can we pass the JSON object from android app to server?
EDIT: We able to get the raw data without decoding by file_get_contents('php://input') as {"test1":1234567890,"test2":"test"} but when using json_decode it returns blank value. We also tried with returning data withUTF-8 encoded format which sends data as %7B%22test1%22%3A1234567890%2C%22test2%22%3A%22test%22%7D in raw format but it also unable to decode. BTW, json_last_error() returns 4.