Can't connect to php in Android Application - java

Now I'm working on RESTful API with php and try to connect to it from Android
But I can't connect because it's always catch IOException
here's my Android Code (OnReg is the method when clicked Register Button)
public void OnReg(View view)
{
str_email = et_email.getText().toString();
str_password = et_password.getText().toString();
str_fname = et_fname.getText().toString();
str_lname = et_lname.getText().toString();
type = "register";
BackgroundWorker backgroundWorker = new BackgroundWorker(this);
backgroundWorker.execute(type, str_email, str_password, str_fname, str_lname);
}
Here's the BackgroundWorker class
public class BackgroundWorker extends AsyncTask<String, Void, String>
{
Context context;
AlertDialog alertDialog;
BackgroundWorker(Context ctx)
{
context = ctx;
}
#Override
protected String doInBackground(String... params)
{
StringBuilder result = new StringBuilder();
String type = params[0];
BufferedWriter bufferedWriter = null;
BufferedReader bufferedReader = null;
String register_url = "http://192.168.1.9/register.php";
if(type.equals("register"))
{
try
{
//Create data to send to server
JSONObject dataToSend = new JSONObject();
dataToSend.put("email", params[1]);
dataToSend.put("password", params[2]);
dataToSend.put("fname", params[3]);
dataToSend.put("lname", params[4]);
//Initialize and config request, then connect to server
URL url = new URL(register_url);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true); //enable output (body data)
httpURLConnection.setRequestProperty("Content-Type", "application/json"); //set header
httpURLConnection.connect();
//Write data into server
OutputStream outputStream = httpURLConnection.getOutputStream();
bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream));
bufferedWriter.write(dataToSend.toString());
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
//Read data response from server
InputStream inputStream = httpURLConnection.getInputStream();
bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = bufferedReader.readLine()) != null)
{
result.append(line).append("\n");
}
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
}
catch (IOException e)
{
return "Network Error";
}
catch (JSONException e)
{
e.printStackTrace();
}
}
return result.toString();
}
#Override
protected void onPreExecute()
{
alertDialog = new AlertDialog.Builder(context).create();
alertDialog.setTitle("Status");
}
#Override
protected void onPostExecute(String result)
{
alertDialog.setMessage(result);
alertDialog.show();
}
Here's my PHP Code
<?php
$m = new MongoClient();
$db = $m -> ETESS;
$collection = $db -> members;
if($_SERVER['REQUEST_METHOD'] == 'POST')
{
$data = json_decode(file_get_contents("php://input"));
$email = $data->email;
$password = $data->password;
$fname = $data->fname;
$lname = $data->lname;
$encrypted_password = md5($password);
$document = array(
"email" => $email,
"password" => $encrypted_password,
"fname" => $fname,
"lname" => $lname
);
if($collection -> insert($document))
{
echo "Registered Successfully !";
$response["result"] = "success";
$response["message"] = "Registered Successfully !";
return json_encode($response);
}
else
{
$response["result"] = "failure";
$response["message"] = "Registered Failed";
return json_encode($response);
}
}
?>
I already added this in AndroidManifest.xml
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
with all of these code I always get "Network Error" when I clicked Register Button (I assume that it's catch IOException) but when I tried to send POST request by Advanced REST client, everything work perfectly.
Please kindly check my code if there are any mistake.
Thanks

Now I try to connect 192.168.1.9/register.php in browser in my mobile, and it's said
You don't have permission to access /register.php on this server.
I use wamp as web server
Thanks

Related

HttpURLconnection connection failure with non .com website

I have been trying to connect my android app to php server.I made a php server echo "Connection success" so that I could retrieve the same text and display it in Alertbox in my android application.I have a website with a .cf and the app shuts down every time I connect.
I checked my code found nothing wrong, then I tried a .com website, and the app was successfully able to retrieve the html form of whatever was displayed on the page.So is there something that prevents HttpURLconnection form connecting to non .com websites.
Here is the code.
public class BackgroundWorker extends AsyncTask<String,Void,String> {
Context context;
AlertDialog alertDialog;
BackgroundWorker (Context ctx) {
context = ctx;
}//takes context as an argument
#Override
protected String doInBackground(String... params) {
String type = params[0];
String login_url = "http://www.thejoint.cf/test.php";
if(type.equals("login")) {
try {
String user_name = params[1];
String password = params[2];
URL url = new URL(login_url);//what does the url object have
HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
OutputStream outputStream = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
String post_data = URLEncoder.encode("user_name","UTF-8")+"="+URLEncoder.encode(user_name,"UTF-8")+"&"
+URLEncoder.encode("password","UTF-8")+"="+URLEncoder.encode(password,"UTF-8");
bufferedWriter.write(post_data);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream,"iso-8859-1"));
String result="";
String line="";
while((line = bufferedReader.readLine())!= null) {
result+=line;
}
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
return result;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPreExecute() {
alertDialog = new AlertDialog.Builder(context).create();
alertDialog.setTitle("Login Status");
}
#Override
protected void onPostExecute(String result) {
alertDialog.setMessage(result);
Log.i("info",result);
alertDialog.show();
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
}
So is there something that prevents HttpURLconnection form connecting to non .com websites ?
you create a regex :
String expression = "[^"]+\.com" ;
and test if your url matches with it :
if(your_url.matches(expression)){
// your url end with .com , do what you want
}else{
// your url doesn't end with .com , do what you want
}

Unable to send data to server in Android

I'm new to Android. Don't know which part has gone wrong. The thing is I'm unable to send the data to the server in Android Studio.
This is the error I'm facing
Fatal error: Uncaught Error: Call to undefined function mysql_connect() in C:\xampp\htdocs\students\connection.php:6 Stack trace: #0 C:\xampp\htdocs\students\add_employee.php(2): include() #1 {main} thrown in C:\xampp\htdocs\students\connection.php on line 6
The code goes like this...
Main Activity
public class MainActivity extends AppCompatActivity {
Button b1;
EditText e1;
private ProgressDialog pDialog;
private JSONObject json;
private int success=0;
private HTTPURLConnection service;
private String strname ="";
//Initialize webservice URL
private String path = "http://localhost/student/add_employee.php";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b1 = (Button) findViewById(R.id.button);
e1 = (EditText) findViewById(R.id.editText9);
service=new HTTPURLConnection();
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!e1.getText().toString().equals("") ) {
strname = e1.getText().toString();
//Call WebService
new PostDataTOServer().execute();
} else {
Toast.makeText(getApplicationContext(), "Please Enter all fields", Toast.LENGTH_LONG).show();
}
Intent intent = new Intent(MainActivity.this, Student1.class);
startActivity(intent);
}
});
}
private class PostDataTOServer extends AsyncTask<Void, Void, Void> {
String response = "";
//Create hashmap Object to send parameters to web service
HashMap<String, String> postDataParams;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
postDataParams=new HashMap<String, String>();
postDataParams.put("name", strname);
//Call ServerData() method to call webservice and store result in response
response= service.ServerData(path,postDataParams);
try {
json = new JSONObject(response);
//Get Values from JSONobject
System.out.println("success=" + json.get("success"));
success = json.getInt("success");
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if (pDialog.isShowing())
pDialog.dismiss();
if(success==1) {
Toast.makeText(getApplicationContext(), "Employee Added successfully..!", Toast.LENGTH_LONG).show();
}
}
}
}
HTTPURLConnection
public class HTTPURLConnection {
String response="";
URL url;
public String ServerData(String path,HashMap<String, String> params) {
try {
url = new URL(path);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(15000);
conn.setConnectTimeout(15000);
conn.setRequestMethod("POST");
conn.setDoInput(true);
conn.setDoOutput(true);
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(os, "UTF-8"));
writer.write(getPostDataString(params));
writer.flush();
writer.close();
os.close();
int responseCode = conn.getResponseCode();
if (responseCode == HttpsURLConnection.HTTP_OK) {
String line;
BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
//Log.d("Output",br.toString());
while ((line = br.readLine()) != null) {
response += line;
Log.d("output lines", line);
}
} else {
response = "";
}
} catch (Exception e) {
e.printStackTrace();
}
return response;
}
private String getPostDataString(HashMap<String, String> params) throws UnsupportedEncodingException {
StringBuilder result = new StringBuilder();
boolean first = true;
for(Map.Entry<String, String> entry : params.entrySet()){
if (first)
first = false;
else
result.append("&");
result.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
result.append("=");
result.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
}
return result.toString();
}}
My PHP code
add_employee.php
<?php
include('connection.php');
$emp_name=$_POST["name"];
$success=0;
$status="Active";
$sql = "INSERT INTO `employee` (`emp_name`)
VALUES ('$emp_name')";
if(mysql_query($sql))
{
$success=1;
}
$response["success"]=$success;
die(json_encode($response));
mysql_close($con);
?>
connection.php
<?php
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(!$conn) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db('student');
?>

PHP and AlertDialog not in sync on Android

I'm currently building a simple login Android app using a tutorial on YouTube that fetches data from a database and lets the user login. However, when I click the login button, regardless of what the input is, it tells me that the login has been successful. Below is the Java code where the data is entered and the PHP code to connect to the database, every time login is clicked the AlertDialog will pop up saying 'Login successful'. I want it to display 'Login not successful' if the data the user enters is incorrect, can somebody show me how? Thanks
public class BackgroundWorker extends AsyncTask<String, Void, String> {
Context context;
AlertDialog alertDialog;
BackgroundWorker (Context ctx){
context = ctx;
}
#Override
protected String doInBackground(String... params) {
String type = params[0];
String login_url = "";
if (type.equals("Login")) {
try {
String userName = params[1];
String password = params[2];
URL url = new URL(login_url);
HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
OutputStream outputStream = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
String post_data = URLEncoder.encode("userName", "UTF-8")+"="+URLEncoder.encode(userName, "utf-8")+"&"
+URLEncoder.encode("password", "UTF-8")+"="+URLEncoder.encode(password, "utf-8");
bufferedWriter.write(post_data);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream,"iso-8859-1"));
String result ="";
String line ="";
while ((line = bufferedReader.readLine()) != null){
result += line;
}
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
return result;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPreExecute() {
alertDialog = new AlertDialog.Builder(context).create();
alertDialog.setTitle("Login status: ");
}
#Override
protected void onPostExecute(String result) {
alertDialog.setMessage(result);
alertDialog.show();
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
}
====
<?php
require "conn.php";
$userName = $_POST["userName"];
$password = $_POST["password"];
$mysql_qry = "select * from database where userName like '$userName' and password like '$password';";
$result = mysqli_query($conn, $mysql_qry);
if(mysqli_num_rows($result) > 0) {
echo "Successful login";
}
else{
echo "Login not successful";
}
In your conn.php file
$dbname = "";
$username = "";
$password = "";
$server = "";
This should not be empty.
Fill it with appropriate data

How to prevent duplicate entry in registration activity with "Username already taken"

I would like to include a code such that, when a user registers a username that has already been used in my app, he/she will get a toast saying "Username is already taken".
Register.java
public class Register extends AppCompatActivity {
EditText regEmail, regPassword;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
regEmail = (EditText)findViewById(R.id.reg_email);
regPassword = (EditText)findViewById(R.id.reg_password);
}
public void OnReg(View view) {
String strEmail = regEmail.getText().toString();
String strPassword = regPassword.getText().toString();
String type = "register";
BackgroundWorker backgroundWorker = new BackgroundWorker(this);
backgroundWorker.execute(type, strEmail, strPassword);
}}
BackgroundWorker.java
public class BackgroundWorker extends AsyncTask<String,Void,String> {
Context context;
AlertDialog alertDialog;
BackgroundWorker (Context ctx){
context = ctx;
}
#Override
protected String doInBackground(String... params) {
String type = params[0];
String login_url = "http://10.93.22.231/login.php";
String register_url = "http://10.93.22.231/register.php";
if (type.equals("login")){
try {
String email = params[1];
String password = params[2];
URL url = new URL(login_url);
HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
OutputStream outputStream = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
String post_data = URLEncoder.encode("email","UTF-8")+"="+URLEncoder.encode(email,"UTF-8")+"&"
+URLEncoder.encode("password","UTF-8")+"="+URLEncoder.encode(password,"UTF-8");
bufferedWriter.write(post_data);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "iso-8859-1"));
String result = "";
String line = "";
while ((line = bufferedReader.readLine()) != null) {
result += line;
}
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
return result;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} else if (type.equals("register")){
try {
String regEmail = params[1];
String regPassword = params[2];
URL url = new URL(register_url);
HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
OutputStream outputStream = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
String post_data = URLEncoder.encode("email","UTF-8")+"="+URLEncoder.encode(regEmail,"UTF-8")+"&"
+URLEncoder.encode("password","UTF-8")+"="+URLEncoder.encode(regPassword,"UTF-8");
bufferedWriter.write(post_data);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "iso-8859-1"));
String result = "";
String line = "";
while ((line = bufferedReader.readLine()) != null) {
result += line;
}
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
return result;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPreExecute() {
alertDialog = new AlertDialog.Builder(context).create();
alertDialog.setTitle("Login Status");
}
#Override
protected void onPostExecute(String result) {
alertDialog.setMessage(result);
if (result.contains("success")) {
Intent intent = new Intent(context, MainActivity.class);
context.startActivity(intent);
} else {
alertDialog.show();
}
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
}
Register.php
<?php
require "conn.php";
$email = $_POST["email"];
$password = $_POST["password"];
$mysql_qry = "INSERT INTO users (email, password) VALUES ('$email','$password')";
if($conn->query($mysql_qry) === TRUE){
echo "Insert successful";
} else {
echo "Insert failed, please try again.";
}
$conn->close();
?>
Toast.makeText(YourActivtyOrContext,"Username Taken", Toast.LENGTH_LONG).show();
on Post execute you can do some thing like this
also at the server level if the username already exists you should not save the record instead of that you should pass the value that username already exists
#Override
protected void onPostExecute(String result) {
if (result.contains("success")) {
Intent intent = new Intent(context, MainActivity.class);
context.startActivity(intent);
} else {
Toast.makeText(context,result, Toast.LENGTH_LONG).show();
}
}
Hey please check this code, maybe it can solve your problem. This is simple code.
if (ConnectivityDetector.isConnectingToInternet(RegisterActivity.this)) {
JSONObject jsonObjectInput = new JSONObject();
jsonObjectInput.put(WebField.REGISTER_USER.REQUEST_USER_NAME,
edtUserName.getText().toString());
String mode = "RegisterUser";
new GetJsonWithCallBack(RegisterActivity.this, jsonObjectInput,
1, mode, new OnUpdateListener() {
#Override
public void onUpdateComplete(JSONObject jsonObject,
boolean isSuccess) {
if (isSuccess) {
try {
if (jsonObject != null) {
if (jsonObject.has("userDetail")) {
JSONObject jsonUserDetails = jsonObject.getJSONObject("userDetail");
RegisterData regData = new RegisterData();
regData.setUserName(jsonUserDetails.getString(WebField.REGISTER_USER.RESPONSE_USER_NAME));
SessionManager.saveData(RegisterActivity.this, regData);
finish();
}
}
} catch (Exception e) {
e.printStackTrace();
}
} else {
if (jsonObject != null) {
try {
String Status = jsonObject.getString("status");
String message = jsonObject.getString("message");
if (message.equalsIgnoreCase("User already Exists")) {
GlobalMethod.showAlert(RegisterActivity.this, "User name already exists..!!");
} else if (message.equalsIgnoreCase("Email id already Exists")) {
GlobalMethod.showAlert(RegisterActivity.this, "Email id already exists..!!");
} else if (message.equalsIgnoreCase("Mobile no already Exists")) {
GlobalMethod.showAlert(RegisterActivity.this, "Mobile no already exists..!!");
} else {
GlobalMethod.showAlert(RegisterActivity.this, jsonObject.getString("message"));
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
}
}
}
}).execute();
} else {
AlertDialogUtility.showInternetAlert(RegisterActivity.this);
}
} catch (Exception e) {
e.printStackTrace();
}
try this way
#Override
protected void onPostExecute(String result) {
alertDialog.setMessage(result);
if (result.contains("success")) {
JSONObject json= new JSONObject(result);
if(json.has("message"){
String message=json.getString("message");
Toast.makeText(ctx,message,Toast.LENGTH_SHORT).show();
}
Intent intent = new Intent(context, MainActivity.class);
context.startActivity(intent);
} else {
alertDialog.show();
}
}
UPDATE
User validation query
$mysql_qry="SELECT * FROM users WHERE email='$email'";
if($conn->query($mysql_qry) === TRUE){
}else{}

How to insert data into MySQL Server using ArrayAdapter (Java)?

I am new in android development, I want to insert call log details in MySQL database, here I have created simple ArrayAdapter that's not getting set in listview and second thing is, how to insert data in MySQL server.
Here is my java code
public class MainActivity extends Activity {
ListView listView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.lv);
getCallDetails();
}
private void getCallDetails()
{
StringBuffer sb = new StringBuffer();
String strOrder = android.provider.CallLog.Calls.DATE + " DESC";
Cursor managedCursor = managedQuery(CallLog.Calls.CONTENT_URI, null,null, null, strOrder);
int number1 = managedCursor.getColumnIndex(CallLog.Calls.NUMBER);
int type1 = managedCursor.getColumnIndex(CallLog.Calls.TYPE);
int duration1 = managedCursor.getColumnIndex(CallLog.Calls.DURATION);
sb.append("Call Log :");
while (managedCursor.moveToNext())
{
final String number = managedCursor.getString(number1);
final String type2 = managedCursor.getString(type1);
final String date = managedCursor.getString(managedCursor.getColumnIndexOrThrow("date")).toString();
java.util.Date date1 = new java.util.Date(Long.valueOf(date));
final String duration = managedCursor.getString(duration1);
String type = null;
final String fDate = date1.toString();
int callcode = Integer.parseInt(type2);
switch (callcode)
{
case CallLog.Calls.OUTGOING_TYPE:
type = "Outgoing";
break;
case CallLog.Calls.INCOMING_TYPE:
type = "Incoming";
break;
case CallLog.Calls.MISSED_TYPE:
type = "Missed";
break;
}
List<DataBean> DataBeanList = new ArrayList<DataBean>();
DataBean dataBean = new DataBean(number, type, fDate, duration);
DataBeanList.add(dataBean);
Log.d("tag", DataBeanList.toString());
}
managedCursor.close();
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,android.R.id.text1);
listView.setAdapter(arrayAdapter);
}
}
Here is my php script.........
<?php
//Importing our db connection script
require_once('connect.php');
if($_SERVER['REQUEST_METHOD']=='POST'){
//Getting values
$number = $_POST['number'];
$duration = $_POST['duration'];
$type = $_POST['type'];
$time = $_POST['time'];
//Creating an sql query
$sql = "INSERT INTO call_detail (number,duration,type,time) VALUES ('$number','$duration','$type','$time')";
//Executing query to database
if(mysqli_query($con,$sql)){
echo 'Entry Added Successfully';
}else{
echo 'Could Not Add Entry';
}
//Closing the database
mysqli_close($con);
}
Well i am using this method to upload data from Android to MySQL Database. First of all you need an AsyncTask to communicate with the .php file and send the data. So i would suggest to try this:
public class MyInsertDataTask extends AsyncTask<String, Void, Boolean> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(YourActivity.this);
pDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
pDialog.setIndeterminate(true);
pDialog.setMessage("Data Processing");
pDialog.setCancelable(false);
pDialog.setInverseBackgroundForced(true);
pDialog.show();
}
#Override
protected Boolean doInBackground(String... params) {
try {
URL url = new URL(params[0]);
HttpURLConnection urlConnection =(HttpURLConnection) url.openConnection();
urlConnection.setRequestProperty("Accept-Encoding", "application/json");
urlConnection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
urlConnection.setRequestMethod("POST");
urlConnection.setDoInput(true);
urlConnection.setDoOutput(true);
urlConnection.connect();
setupDataToDB();
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(urlConnection.getOutputStream());
outputStreamWriter.write(dataToWrite.toString());
Log.e("Data To Write", dataToWrite.toString());
outputStreamWriter.flush();
outputStreamWriter.close();
int responseCode = urlConnection.getResponseCode();
Log.e("Response Code ", String.valueOf(responseCode));
if (responseCode == 200){
InputStream inputStream = new BufferedInputStream(urlConnection.getInputStream());
StringBuilder jsonResult = inputStreamToString(inputStream, YourActivity.this);
JSONObject jsonResponse = new JSONObject(jsonResult.toString());
Log.e("Data From JSON", jsonResponse.toString());
return true;
}else{
InputStream inputStream = new BufferedInputStream(urlConnection.getErrorStream());
Log.e("ERROR STREAM", inputStream.toString());
return false;
}
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
#Override
protected void onPostExecute(Boolean aVoid) {
super.onPostExecute(aVoid);
pDialog.dismiss();
if (aVoid){
Toast.makeText(YourActivity.this, "Data Sent", Toast.LENGTH_LONG).show();
YourActivity.this.finish();
}else{
Toast.makeText(YourActivity.this, "There was a problemm sending the data. Please try again", Toast.LENGTH_LONG).show();
}
}
}
private void setupDataToDB() {
JSONObject dataToWrite = new JSONObject();
try {
dataToWrite.put("number", numberStringFromJava);
dataToWrite.put("duration", durationStringFromJava);
dataToWrite.put("type", typeStringFromJava);
dataToWrite.put("time", timeStringFromJava);
} catch (JSONException e) {
e.printStackTrace();
}
}
and then your InputStreamToString method:
public StringBuilder inputStreamToString(InputStream is, Activity activity) {
String rLine;
StringBuilder answer = new StringBuilder();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
try {
while ((rLine = rd.readLine()) != null) {
answer.append(rLine);
}
} catch (Exception e) {
activity.finish();
}
return answer;
}
And this should insert the data if everything is correct. You have to execute it like this:
new MyInsertDataTask().execute("Your_php_file_path");
Hope it helps!!!
Watch these videos and learn how to insert data into online phpmyadmin server using your android app. For this, get a free web hosting server from 000webhost for creating a database online to store data and then can retrieve data online.
Simple and Interesting way to learn how to store data online on a web server.
https://www.youtube.com/watch?v=k3O3CY75ITY
This is the first part of the video.

Categories