Reputation: 41
I am creating an Android app and I have implemented a client server using a WAMP server. I have created my php file, the server is running and a simple version of my php file was inserting data successfully into my mysql database. In my app I have included an AsyncTask
java file in order to insert my data. I am sure my url string is wrong and that's why it is printing the following error:
java.net.ConnectException: failed to connect to localhost/127.0.0.1 (port 80): connect failed: ECONNREFUSED (Connection refused)
I am testing my app on a Samsung S4 so no emulator replies to change my ip string to 10.0.2.2. I have used localhost, 127.0.0.1 and my IP adress which I found by running ipconfig in cmd...nothing works and it is printing the same error. I read 15-20 similar questions and I still don't know what to do.
Internet permission exists on my manifest and my phone is connected via Wi-Fi in my router. (I also tried with my phones 4G and this did not work either).
Below you can find my code:
import android.content.Context;
import android.os.AsyncTask;
import android.widget.Toast;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
public class BackgroundTask extends AsyncTask<String, Void, String>
{
Context ctx;
BackgroundTask(Context ctx)
{
this.ctx = ctx;
}
@Override
protected void onPreExecute()
{
super.onPreExecute();
}
@Override
protected String doInBackground(String... params)
{
String create_url = "http://217.137.144.65/myapp/create.php";
String method = params[0];
if(method.equals("create"))
{
String name = params[1];
try
{
URL url = new URL(create_url);
HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
OutputStream OS = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(OS,"UTF-8"));
String data = URLEncoder.encode("exCatName","UTF-8") + "=" + URLEncoder.encode(name,"UTF-8");
bufferedWriter.write(data);
bufferedWriter.flush();
bufferedWriter.close();
OS.close();
InputStream IS = httpURLConnection.getInputStream();
IS.close();
return "Category Created Successfully";
}
catch (MalformedURLException e)
{
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
@Override
protected void onProgressUpdate(Void... values)
{
super.onProgressUpdate(values);
}
@Override
protected void onPostExecute(String result)
{
Toast.makeText(ctx, result, Toast.LENGTH_LONG).show();
}
}
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
public class CreateNewCategoryActivity extends Activity
{
private ImageView backImageView, saveImageView;
private EditText nameEditText;
String categoryName;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create_new_category);
backImageView = (ImageView)findViewById(R.id.backImageView);
saveImageView = (ImageView)findViewById(R.id.saveImageView);
nameEditText = (EditText)findViewById(R.id.nameEditText);
backImageView.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
backMethod();
}
});
saveImageView.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
createNewCategoryMethod();
}
});
}
public void createNewCategoryMethod()
{
categoryName = nameEditText.getText().toString();
String method = "create";
BackgroundTask backgroundTask = new BackgroundTask(this);
backgroundTask.execute(method, categoryName);
finish();
}
public void backMethod()
{
//startActivity(new Intent(getApplicationContext(), BalanceActivity.class));
finish();
}
}
php file:
<?php
require "init.php";
$exCategories_ID = "1";
$exCatName = $_POST["name"];
$sql_query = "insert into Expense_Categories values
('$exCategories_ID','$exCatName');";
if(mysqli_query($con,$sql_query))
{
echo "<h3>Data Insertion Success...</h3>";
}
else
{
echo "Data insertion error...".mysqli_error($con);
}
?>
Upvotes: 2
Views: 18304
Reputation: 2184
To access localhost
you should use local IPv4 + server PORT for localhost
.
How to get this IPv4: https://www.whatismybrowser.com/detect/what-is-my-local-ip-address
KOTLIN async request:
private val client = OkHttpClient()
fun run() {
val request = Request.Builder()
.url("http://192.168.0.104:5000/api/post/latest")
.build()
client.newCall(request).enqueue(object : Callback {
override fun onFailure(call: Call, e: IOException) {
e.printStackTrace()
}
override fun onResponse(call: Call, response: Response) {
response.use {
if (!response.isSuccessful) throw IOException("Unexpected code $response")
for ((name, value) in response.headers) {
println("$name: $value")
}
println(response.body!!.string())
}
}
})
}
Install OkHttp: https://square.github.io/okhttp/
Upvotes: 0
Reputation: 9150
java.net.ConnectException: failed to connect to localhost/127.0.0.1 (port 80): connect failed: ECONNREFUSED (Connection refused)
String create_url = "http://localhost/myapp/create.php";
is wrong, the correct one is
String create_url = "http://192.168.0.3/myapp/create.php";
being 192.168.0.3
the local ip of your pc (server)
Upvotes: 2
Reputation: 29168
I got same type of problem. My PC contains MySQL
installed and Then I have installed WAMP
. Then the problem is occured. WAMP containing mysql port number and my PC's MySQL are conflicting.
So you can uninstall your PC's MySQL first and restart and use WAMP's MySQL. Then the problem will be solved.
Upvotes: 1