ANDROID+MYSQL+PHP DATA ACESS - android

I am trying to access data from localhost MYSql database.i am using XAMP for PHP. First i created a index.php file.which is saved in C:\xampp\htdocs\sample\index.php.my android code is saved in C:\Documents and Settings\SUHAIL\workspace\PHPMYSQL.while i running android on emulator data from the database is not accessed.(there is no compiation error) .My complete code is given below.
index.php(DB name:temp
Table Name: table1)
enter code here
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<body>
<?php
$con=mysqli_connect("localhost","root","","temp");
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$username = $_GET['username'];
$password = $_GET['password'];
$result = mysqli_query($con,"SELECT roll FROM table1 where username='$username' and password='$password'");
$row = mysqli_fetch_array($result);
$data = $row[0];
if($data){
echo $data;
}
mysqli_close($con);
?>
</body>
</html>
---------------------------------------------------------------------
SignActyivity.java
---------------------------------------------------------------------
package com.example.phpmysql;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URI;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
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.content.Context;
import android.os.AsyncTask;
import android.widget.TextView;
public class SigninActivity extends AsyncTask<String,Void,String>{
private TextView statusField,roleField;
public Context context;
private int byGetOrPost = 0;
//flag 0 means get and 1 means post.(By default it is get.)
public SigninActivity(Context context,TextView statusField,
TextView roleField,int flag) {
this.context = context;
this.statusField = statusField;
this.roleField = roleField;
byGetOrPost = flag;
}
protected void onPreExecute(){
}
#Override
protected String doInBackground(String... arg0) {
if(byGetOrPost == 0){ //means by Get Method
try{
String username = (String)arg0[0];
String password = (String)arg0[1];
String link = "http://10.0.2.2/sample/login.php?username="
+username+"&password="+password;
//public URL url = new URL(link);
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet();
request.setURI(new URI(link));
HttpResponse response = client.execute(request);
BufferedReader in = new BufferedReader
(new InputStreamReader(response.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String line="";
while ((line = in.readLine()) != null) {
sb.append(line);
break;
}
in.close();
return sb.toString();
}catch(Exception e){
return new String("Exception: " + e.getMessage());
}
}
else{
try{
String username = (String)arg0[0];
String password = (String)arg0[1];
String link="http://10.0.2.2/sample/index.php";
String data = URLEncoder.encode("username", "UTF-8")
+ "=" + URLEncoder.encode(username, "UTF-8");
data += "&" + URLEncoder.encode("password", "UTF-8")
+ "=" + URLEncoder.encode(password, "UTF-8");
URL url = new URL(link);
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter
(conn.getOutputStream());
wr.write( data );
wr.flush();
BufferedReader reader = new BufferedReader
(new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
// Read Server Response
while((line = reader.readLine()) != null)
{
sb.append(line);
break;
}
return sb.toString();
}catch(Exception e){
return new String("Exception: " + e.getMessage());
}
}
}
#Override
protected void onPostExecute(String result){
this.statusField.setText("Login Successful jjjj");
this.roleField.setText(result);
}
}
-------------------------------------------------------------------------------------------
MainActivity.java
--------------------------------------------------------------------------------------------
package com.example.phpmysql;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends Activity {
private EditText usernameField,passwordField;
private TextView status,role,method;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
usernameField = (EditText)findViewById(R.id.editText1);
passwordField = (EditText)findViewById(R.id.editText2);
status = (TextView)findViewById(R.id.textView6);
role = (TextView)findViewById(R.id.textView7);
method = (TextView)findViewById(R.id.textView9);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public void login(View view){
String username = usernameField.getText().toString();
String password = passwordField.getText().toString();
method.setText("Get Method");
new SigninActivity(this,status,role,0).execute(username,password);
}
public void loginPost(View view){
String username = usernameField.getText().toString();
String password = passwordField.getText().toString();
method.setText("Post Method");
new SigninActivity(this,status,role,1).execute(username,password);
}
}

I can't think of any good reason to do what you are doing, but your issue is as follows -
Localhost refers to the local device, on your pc, it is your pc... and on android... it is your android device.
Even if you are running on an emulator, that emulator is set to act like a real device, it does not know about the rest of your computer. What you will need to do is set up a proper web service and access your database that way, or use an sqlite db on the device properly
Also one more note, I can see youre a noob, but it's best to post only the parts of your code that you think are causing an issue, plus any errors they log. Only add other parts if people ask you to - nobody wants to spend ages trying to figure out your mess of code, especially if it looks like you havent even tried to fix/narrow down the issue yourself

Related

How Can I Open Another Activity based on The Username and Password I Retrieve from MySQL using PHP?

How can I open another activity in Android Studio after confirming username and password in my MySQL using PHP script?
I was trying to use HTTP but couldn't because of my SDK version(28). So, now I'm trying to use URL to connect.
This is my code so far.
package com.example.myapp;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
public class Sign extends AppCompatActivity {
//Connector Variables
private static final String jsonurl = "http://192.168.1.2/login2.php";
private static TextView Info = null, Info2 = null, jSON;
String username;
String password;
String usern[], userp[];
int counter = 4;
EditText pas;
EditText usr;
Button create_account;
String ConnectionResult = "";
Boolean isSuccess = false;
private Button login;
private Context text;
private View view;
private String LoginSMessage = "Login successful";
String success = "succesful";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate( savedInstanceState );
setContentView( R.layout.activity_sign );
Button login = findViewById( R.id.btnLogin );
usr = ( EditText ) findViewById( R.id.etUsername );
pas = ( EditText ) findViewById( R.id.etPassword );
Info = ( TextView ) findViewById( R.id.tvInfo );
jSON = ( TextView ) findViewById( R.id.tvJSON );
Button create_account = findViewById( R.id.btnCreate );
login.setOnClickListener( new View.OnClickListener() {
#Override
public void onClick(View v) {
username = usr.getText().toString();
password = pas.getText().toString();
String type = "login2";
GetJSON json = new GetJSON(this);
json.execute(type, username, password);
}
});
}
class GetJSON extends AsyncTask<String, Void, String> {
public GetJSON(Object o) {
}
protected String doInBackground(String... params) {
String type = params[0];
String login_url = "http://192.168.1.2/login2.php";
BufferedReader bufferedReader = null;
if (type.equals( "login2" )) {
try {
String user_name = params[1];
String password = params[2];
URL url = new URL( login_url );
HttpURLConnection con = ( HttpURLConnection )
url.openConnection();
con.setRequestMethod( "POST" );
con.setDoOutput( true );
con.setDoInput( true );
OutputStream outputStream = con.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 = con.getInputStream();
bufferedReader = new BufferedReader( new
InputStreamReader( inputStream, "iso-8859-1" ) );
StringBuilder sb = new StringBuilder();
//bufferedReader = new BufferedReader( new
InputStreamReader( con.getInputStream() ) );
String json;
while ((json = bufferedReader.readLine()) != null) {
sb.append( json + "\n" );
}
return sb.toString().trim();
} catch (Exception e) {
return null;
}
}
return null;
}
#Override
protected void onPostExecute(String s){
super.onPostExecute( s );
jSON.setText(s);
Log.d("CREATION", "Execution is done"+s);
}
}
I expect my code to be able to open another activity after confirming username and password in MySQL.
You can write following PHP script on your server:
$con=mysqli_connect("localhost","uname","pass","dbname");
if (mysqli_connect_errno($con)) {
echo "Error in connection : " . mysqli_connect_error();
}
$uname= $_POST['username'];
$pass= $_POST['password'];
$result = mysqli_query($con,"SELECT * FROM tableName where uname='$uname' and pass='$pass'");
$row = mysqli_fetch_array($result);
$data = $row[0];
if($data){
echo "Login success";
}
mysqli_close($con);
Now in your android app you can have a simple if condition
#Override
protected void onPostExecute(String s){
super.onPostExecute( s );
jSON.setText(s);
Log.d("CREATION", "Execution is done"+s);
if(s!=null){
Intent i = new Intent(your_current_activity_name.this,your_next_activity_name.class);
startActivity(i);
}else{
Toast.makeText(getApplicationContext(), "Login credentials wrong", Toast.LENGTH_LONG).show();
}
}

Android studio problems login validation

So I've been cracking my brain with this issues. I'm trying to validate if the an user credentials on a app connected to mysql are valid. The thing is that wherever I try to compare the result of the query with a string all I get is the else statement.
Here's the Fragment for the Login
package com.example.pablorjd.CheckThisOut;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class Login extends AppCompatActivity {
EditText etUsername;
EditText etPassword;
Button btnLogin;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
etUsername = (EditText)findViewById(R.id.etUsername);
etPassword = (EditText)findViewById(R.id.etPassword);
btnLogin = (Button)findViewById(R.id.btnLogin);
}
public void onLogin(View view){
String username = etUsername.getText().toString();
String password = etPassword.getText().toString();
String type = "login";
BackgroundWorker backgroundWorker = new BackgroundWorker(this);
backgroundWorker.execute(type,username,password);
}
}
I'm using a background class to make the connection to mysql
package com.example.pablorjd.CheckThisOut;
import android.app.AlertDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
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 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.20.13.31/checkthisout/login.php";
if (type.equals("login")){
try {
String user_name = 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("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, "UTF-8"));
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() {
}
#Override
protected void onPostExecute(String result) {
if (result.equals("true")){
Toast.makeText(context, "If is working", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(context,result, Toast.LENGTH_SHORT).show();
}
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
}
I know the DB connections is working because I'm actually receiving the message that I set on the php file.
All I know is that for some reason the if statement is not working for this.
please if someone could shed a light for me that'd be great.
OK so, for some reason, the validation just wouldn't take the string comparison and instead jumped to the else statement showing in this case a Toast. What I had to do was to modify the string given to me by the php file so it would be just a number (0 or 1 in this case). then I parsed the string into an int and the if worked like a charm.
This is the resulting code
#Override
protected void onPostExecute(String result) {
int val = Integer.parseInt(result.replaceAll("[\\D]",""));
if (val == 0){
Intent intent = new Intent(context,MainActivity.class);
context.startActivity(intent);
Toast.makeText(context,"Login exitoso",Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(context,"Login erroneo",Toast.LENGTH_SHORT).show();
}
}
I still don't know why the if statement wouldn't work with strings.

Class 'SigninActivity' must either be declared abstract or implement abstract method 'doInBackground(Params...)' in 'AsyncTask'

Main Activity :
package com.example.phpmysql;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends Activity {
private EditText usernameField,passwordField;
private TextView status,role,method;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
usernameField = (EditText)findViewById(R.id.editText1);
passwordField = (EditText)findViewById(R.id.editText2);
status = (TextView)findViewById(R.id.textView6);
role = (TextView)findViewById(R.id.textView7);
method = (TextView)findViewById(R.id.textView9);
}
public void login(View view){
String username = usernameField.getText().toString();
String password = passwordField.getText().toString();
method.setText("Get Method");
new SigninActivity(this,status,role,0).execute(username,password);
}
public void loginPost(View view){
String username = usernameField.getText().toString();
String password = passwordField.getText().toString();
method.setText("Post Method");
new SigninActivity(this,status,role,1).execute(username,password);
}
}
SigninActivity:
package com.example.phpmysql;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URI;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
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.content.Context;
import android.os.AsyncTask;
import android.widget.TextView;
public class SigninActivity extends AsyncTask{
private TextView statusField,roleField;
private Context context;
private int byGetOrPost = 0;
//flag 0 means get and 1 means post.(By default it is get.)
public SigninActivity(Context context,TextView statusField,TextView
roleField,int flag) {
this.context = context;
this.statusField = statusField;
this.roleField = roleField;
byGetOrPost = flag;
}
protected void onPreExecute(){
}
#Override
protected String doInBackground(String... arg0) {
if(byGetOrPost == 0){ //means by Get Method
try{
String username = (String)arg0[0];
String password = (String)arg0[1];
String link = "http://myphpmysqlweb.hostei.com/login.php?username="+username+"& password="+password;
URL url = new URL(link);
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet();
request.setURI(new URI(link));
HttpResponse response = client.execute(request);
BufferedReader in = new BufferedReader(new
InputStreamReader(response.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String line="";
while ((line = in.readLine()) != null) {
sb.append(line);
break;
}
in.close();
return sb.toString();
} catch(Exception e){
return new String("Exception: " + e.getMessage());
}
} else{
try{
String username = (String)arg0[0];
String password = (String)arg0[1];
String link="http://myphpmysqlweb.hostei.com/loginpost.php";
String data = URLEncoder.encode("username", "UTF-8") + "=" +
URLEncoder.encode(username, "UTF-8");
data += "&" + URLEncoder.encode("password", "UTF-8") + "=" +
URLEncoder.encode(password, "UTF-8");
URL url = new URL(link);
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write( data );
wr.flush();
BufferedReader reader = new BufferedReader(new
InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
// Read Server Response
while((line = reader.readLine()) != null) {
sb.append(line);
break;
}
return sb.toString();
} catch(Exception e){
return new String("Exception: " + e.getMessage());
}
}
}
#Override
protected void onPostExecute(String result){
this.statusField.setText("Login Successful");
this.roleField.setText(result);
}
}
The public class SigninActivity extends AsyncTask is shown in red underline saying Class SigninActivity must either be declared abstract or implement abstract method doInBackground(Params...) in AsyncTask?
I tried adding the doInBackground but it says that it is never used?
I tried making it adbstract but then i could not call the class from mainactivity
You need to provide the generic parameters as
public class SigninActivity extends AsyncTask<String, Void, String>
otherwise the parameter type will be of raw-type and signature won't match

get JSON Array from local server in android 6.0 with HttpURLConnection

I am trying to get a JSON Array from this local server for five days:
localhost/match_picture/service.php?action=read
and i can't do it !!
I search it in google and read too many documentations !
here is my code:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class WebService {
public static String readUrl(String server_url) {
BufferedReader bufferedReader = null;
try {
URL url = new URL(server_url);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
StringBuilder sb = new StringBuilder();
bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));
String json;
while ((json = bufferedReader.readLine()) != null) {
sb.append(json+"\n");
}
return sb.toString();
}catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
and it's Main_Activity:
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
public class Activity_main extends AppCompatActivity {
private ArrayList<StructAcount> netAcount = new ArrayList<StructAcount>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String result= WebService.readUrl("http://localhast/match_picture/service.php?action=read");
if (result != null) {
try {
JSONArray tasks = new JSONArray(result);
for (int i=0; i<tasks.length(); i++) {
StructAcount acount= new StructAcount();
JSONObject object = tasks.getJSONObject(i);
acount.id = object.getLong("user_id");
acount.name = object.getString("user_name");
acount.email = object.getString("user_email");
netAcount.add(acount);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
for (StructAcount acount: netAcount) {
Toast.makeText(Activity_main.this, "username: " + acount.name + "\n" + "useremail: " + acount.email , Toast.LENGTH_SHORT).show();
}
}
}
it is runing on emulator and crashes in this line:
bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));
and i dont know why ...
I am Searching for five days!!!!
I can do it with HttpClient
but i want to be update
I saw a vidoe in youtube that create a class in Main_Activity extends AsyncTask and make connenction in doInBackground(String... params). I try that and that works correcly. but because I want to do it in anoder class (WebService) and I dont know how can i sent result to Main_Activity , I remove that class extended from AsyncTask.
thank's for your help
sorry for my poor english
You have a NetworkOnMainThreadException to begin with.
And your app crashes.
Google how to solve it.

Android - posting data from Android SQLite DB to MySQL DB on localhost server

I'm doing some assignment, and I need to enable sync of SQLite DB data to MySQL DB on localhost server. On button click, data from SQLite needs to be "gathered", converted to JSON and sent to localhost MySQL DB and inserted there. I made Activity that handles that job, made some PHP according to academy example, and have wamp server running where I made database in which data needs to be stored.
On my localhost database is named employes_db , and table within is named employes.
Here is the code from android studio which I made:
package com.EmDatabase;
import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class DataSyncManager extends Activity {
Database db;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.sync_options);
db = new Database(this);
db.getWritableDatabase();
}
public void syncToServer(View v) throws JSONException {
List<Employe> employes = db.selectAll();
JSONObject objEmployes = new JSONObject();
JSONArray employesData = new JSONArray();
for (Employe employe : employes) {
int id = employe.getId();
String name = employe.getName();
String surname = employe.getSurname();
int age = employe.getAge();
String company = employe.getCompany();
String wtype = employe.getWorktype();
JSONObject empData = new JSONObject();
empData.put("id", id);
empData.put("name", name);
empData.put("surname", surname);
empData.put("age", age);
empData.put("company", company);
empData.put("worktype", wtype);
employesData.put(empData);
}
objEmployes.put("all_employes", employesData);
String result = objEmployes.toString();
System.out.println(result);
UploadJsonStringTask task = new UploadJsonStringTask();
task.execute(
new String[] { "http://10.0.2.2/employes_db/register.php", result}
);
}
public void syncFromServer(View v) {
}
private class UploadJsonStringTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
String response = "";
Map<String,String> queries = new HashMap<String, String>(1);
queries.put("all_employes", params[1]);
try {
response += postHttpContent(params[0],queries);
} catch (IOException e) {
Log.e("error", e.toString());
}
return response;
}
#Override
protected void onPostExecute(String result) {
Toast.makeText(getApplicationContext(), result, Toast.LENGTH_LONG).show();
}
public String postHttpContent(String urlString, Map<String, String> queries) throws IOException {
String response = "";
URL url = new URL(urlString);
HttpURLConnection httpConnection = (HttpURLConnection) url.openConnection();
httpConnection.setDoInput(true);
httpConnection.setDoOutput(true);
httpConnection.setUseCaches(false);
httpConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
String postData = "";
for (String key : queries.keySet()) {
postData += "&" + key + "=" + queries.get(key);
}
postData = postData.substring(1);
DataOutputStream postOut = new DataOutputStream(httpConnection.getOutputStream());
postOut.writeBytes(postData);
postOut.flush();
postOut.close();
int responseCode = httpConnection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
String line;
BufferedReader br = new BufferedReader(new InputStreamReader(httpConnection.getInputStream()));
while ((line = br.readLine()) != null) {
response += line;
}
} else {
response = "";
throw new IOException();
}
return response + " *** Uploaded!";
}
}
public void goBack(View v) {
Intent in= new Intent(DataSyncManager.this,MainActivity.class);
startActivity(in);
}
}
And here is the PHP file I made and inserted into wampserver/www/employes_db (register.php):
<?php
$id = 0;
$name = "";
$surname = "";
$age = 0;
$company = "";
$worktype = "";
$conn = new mysqli("localhost","root","","employes_db");
$conn->query("insert into employes values (null,'".$_POST['id']."','".$_POST['name']."','".$_POST['surname']."','".$_POST['age']."','".$_POST['company']."','".$_POST['worktype']."')");
if(!$conn->error) echo "{status:0}"; else echo "{status:-1}";
?>
When I launch app, insert one row in SQLite database, than hit sync button, and I open "localhost/employes_db/register.php" I get "errors" -> Notice: Undefined index: id in C:\wamp64\www\employes_db\register.php on line 9 <- And same error for rest of columns(name,surname,age,company,wtype).
May someone help, where is my mistake?
Undefined index: id means $_POST['id'] does not exist. The first mistake is that you use $_POST to retrieve data, use $_GET instead. The second one is that to retrieve the data using $_GET you've to access your URL like this: localhost/register.php?id=myID.
In your case you are sending the data via HTTPPost so just use file_get_contents('php://input') to get your JSON string, decode the JSON data (json_decode($myJSONString)) you are receiving and send it to your second database.
EDIT
If i understood your problem correctly you could do it like this:
// get all employees from your first database and write them into a JSONArray
List<Employe> employes = db.selectAll();
JSONObject objEmployes = new JSONObject();
JSONArray employesData = new JSONArray();
for (Employe employe : employes) {
int id = employe.getId();
String name = employe.getName();
String surname = employe.getSurname();
int age = employe.getAge();
String company = employe.getCompany();
String wtype = employe.getWorktype();
JSONObject empData = new JSONObject();
empData.put("id", id);
empData.put("name", name);
empData.put("surname", surname);
empData.put("age", age);
empData.put("company", company);
empData.put("worktype", wtype);
employesData.put(empData);
}
// open connection
URL url = new URL("yourUrl.com/yourPhpScript.php");
url.openConnection();
// send JSONArray to your second database
String dataToSend = employesData.toString();
OutputStream os = urlConnection.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
writer.write(dataToSend);
writer.flush();
writer.close();
PHP Script:
<?php
// connect to database
$link = mysqli_connect($hostname, $username, $password);
mysqli_select_db($link, "myDatabase");
// get the JSONArray the app sends
$contents = file_get_contents('php://input');
$jsonArray = json_decode($contents, true);
$jsonCount = count($jsonArray);
for ($i = 0; $i < $jsonCount; $i++) {
$item = $jsonArray[$i];
$itemName = utf8_decode($item['name']);
// parse the other json attributes here like the one above
$query = "INSERT INTO employees VALUES('$itemName', 'addOtherValuesHere...')";
mysqli_query($link, $query);
}

Categories

Resources