Android Studio MySql Connection
I am trying to connect Android Studio to a MySQL Database on a WAMP Server. The Database is set up and called happyplanet. The connection via php is working but on the andorid side there are some errors.
I have a Check Networker Status class:
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
public class CheckNetworkStatus {
public static boolean isNetworkAvailable(Context context) {
ConnectivityManager connectivityManager
= (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
}
A Jason Parser:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.ProtocolException;
import java.net.URL;
import java.util.Map;
import org.json.JSONException;
import org.json.JSONObject;
import android.net.Uri;
import android.util.Log;
public class HttpJasonParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
HttpURLConnection urlConnection = null;
// function get json from url
// by making HTTP POST or GET method
public JSONObject makeHttpRequest(String url, String method,
Map<String, String> params) {
try {
Uri.Builder builder = new Uri.Builder();
URL urlObj;
String encodedParams = "";
if (params != null) {
for (Map.Entry<String, String> entry : params.entrySet()) {
builder.appendQueryParameter(entry.getKey(), entry.getValue());
}
}
if (builder.build().getEncodedQuery() != null) {
encodedParams = builder.build().getEncodedQuery();
}
if ("GET".equals(method)) {
url = url + "?" + encodedParams;
urlObj = new URL(url);
urlConnection = (HttpURLConnection) urlObj.openConnection();
urlConnection.setRequestMethod(method);
} else {
urlObj = new URL(url);
urlConnection = (HttpURLConnection) urlObj.openConnection();
urlConnection.setRequestMethod(method);
urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
urlConnection.setRequestProperty("Content-Length", String.valueOf(encodedParams.getBytes().length));
urlConnection.getOutputStream().write(encodedParams.getBytes());
}
urlConnection.connect();
is = urlConnection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
sb.append(line + "n");
}
is.close();
json = sb.toString();
jObj = new JSONObject(json);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
} catch (Exception e) {
Log.e("Exception", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
My Main Activity:
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// add new product button
Button addNewBtn = (Button) findViewById(R.id.addNewBtn);
addNewBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//Check for network connectivity
if (CheckNetworkStatus.isNetworkAvailable(getApplicationContext())) {
Intent i = new Intent(getApplicationContext(),
AddProductActivity.class);
startActivity(i);
} else {
//Display error message if not connected to internet
Toast.makeText(MainActivity.this,
"Unable to connect to internet",
Toast.LENGTH_LONG).show();
}
}
});
}
}
And my class to add products:
import android.app.ProgressDialog;
import android.content.Intent;
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.Toast;
import com.example.julia.produkte.helper.CheckNetworkStatus;
import com.example.julia.produkte.helper.HttpJasonParser;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Map;
public class AddProductActivity extends AppCompatActivity {
private static final String KEY_SUCCESS = "success";
private static final String KEY_PRODUCT_NAME = "name";
private static final String KEY_PREIS = "preis";
private static final String KEY_STRECKE = "strecke";
private static final String BASE_URL = "http://xxx-myIP/happyplanet/";
private static String STRING_EMPTY = "";
private EditText productNameEditText;
private EditText priceEditText;
private EditText distanceEditText;
private String productName;
private String price;
private String distance;
private Button addButton;
private int success;
private ProgressDialog pDialog;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_product);
productNameEditText = (EditText) findViewById(R.id.txtProductNameAdd);
priceEditText = (EditText) findViewById(R.id.txtPriceAdd);
distanceEditText = (EditText) findViewById(R.id.txtDistanceAdd);
addButton = (Button) findViewById(R.id.btnAdd);
addButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (CheckNetworkStatus.isNetworkAvailable(getApplicationContext())) {
addProduct();
} else {
Toast.makeText(AddProductActivity.this,
"Unable to connect to internet",
Toast.LENGTH_LONG).show();
}
}
});
}
/**
* Checks whether all files are filled. If so then calls AddMovieAsyncTask.
* Otherwise displays Toast message informing one or more fields left empty
*/
private void addProduct() {
if (!STRING_EMPTY.equals(productNameEditText.getText().toString()) &&
!STRING_EMPTY.equals(priceEditText.getText().toString()) &&
!STRING_EMPTY.equals(distanceEditText.getText().toString())) {
productName = productNameEditText.getText().toString();
price = priceEditText.getText().toString();
distance = distanceEditText.getText().toString();
new AddProductAsyncTask().execute();
} else {
Toast.makeText(AddProductActivity.this,
"One or more fields left empty!",
Toast.LENGTH_LONG).show();
}
}
/**
* AsyncTask for adding a movie
*/
private class AddProductAsyncTask extends AsyncTask<String, String, String> {
@Override
protected void onPreExecute() {
super.onPreExecute();
//Display proggress bar
pDialog = new ProgressDialog(AddProductActivity.this);
pDialog.setMessage("Adding Movie. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
@Override
protected String doInBackground(String... params) {
HttpJasonParser httpJsonParser = new HttpJasonParser();
Map<String, String> httpParams = new HashMap<>();
//Populating request parameters
httpParams.put(KEY_PRODUCT_NAME, productName);
httpParams.put(KEY_PREIS, price);
httpParams.put(KEY_STRECKE, distance);
JSONObject jsonObject = httpJsonParser.makeHttpRequest(
BASE_URL + "add_product.php", "POST", httpParams);
try {
success = jsonObject.getInt(KEY_SUCCESS);
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String result) {
pDialog.dismiss();
runOnUiThread(new Runnable() {
public void run() {
if (success == 1) {
//Display success message
Toast.makeText(AddProductActivity.this,
"Movie Added", Toast.LENGTH_LONG).show();
Intent i = getIntent();
//send result code 20 to notify about movie update
setResult(20, i);
//Finish ths activity and go back to listing activity
finish();
} else {
Toast.makeText(AddProductActivity.this,
"Some error occurred while adding movie",
Toast.LENGTH_LONG).show();
}
}
});
}
}
}
Whenever I run my app the message "some error occured while adding the movie" prints out.
I have modified the manifests and I just cannot find my mistake.
Any help would be really appreciated! I know it is a lot to read, but I am really stuck :/
java android mysql database-connection
add a comment |
I am trying to connect Android Studio to a MySQL Database on a WAMP Server. The Database is set up and called happyplanet. The connection via php is working but on the andorid side there are some errors.
I have a Check Networker Status class:
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
public class CheckNetworkStatus {
public static boolean isNetworkAvailable(Context context) {
ConnectivityManager connectivityManager
= (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
}
A Jason Parser:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.ProtocolException;
import java.net.URL;
import java.util.Map;
import org.json.JSONException;
import org.json.JSONObject;
import android.net.Uri;
import android.util.Log;
public class HttpJasonParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
HttpURLConnection urlConnection = null;
// function get json from url
// by making HTTP POST or GET method
public JSONObject makeHttpRequest(String url, String method,
Map<String, String> params) {
try {
Uri.Builder builder = new Uri.Builder();
URL urlObj;
String encodedParams = "";
if (params != null) {
for (Map.Entry<String, String> entry : params.entrySet()) {
builder.appendQueryParameter(entry.getKey(), entry.getValue());
}
}
if (builder.build().getEncodedQuery() != null) {
encodedParams = builder.build().getEncodedQuery();
}
if ("GET".equals(method)) {
url = url + "?" + encodedParams;
urlObj = new URL(url);
urlConnection = (HttpURLConnection) urlObj.openConnection();
urlConnection.setRequestMethod(method);
} else {
urlObj = new URL(url);
urlConnection = (HttpURLConnection) urlObj.openConnection();
urlConnection.setRequestMethod(method);
urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
urlConnection.setRequestProperty("Content-Length", String.valueOf(encodedParams.getBytes().length));
urlConnection.getOutputStream().write(encodedParams.getBytes());
}
urlConnection.connect();
is = urlConnection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
sb.append(line + "n");
}
is.close();
json = sb.toString();
jObj = new JSONObject(json);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
} catch (Exception e) {
Log.e("Exception", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
My Main Activity:
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// add new product button
Button addNewBtn = (Button) findViewById(R.id.addNewBtn);
addNewBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//Check for network connectivity
if (CheckNetworkStatus.isNetworkAvailable(getApplicationContext())) {
Intent i = new Intent(getApplicationContext(),
AddProductActivity.class);
startActivity(i);
} else {
//Display error message if not connected to internet
Toast.makeText(MainActivity.this,
"Unable to connect to internet",
Toast.LENGTH_LONG).show();
}
}
});
}
}
And my class to add products:
import android.app.ProgressDialog;
import android.content.Intent;
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.Toast;
import com.example.julia.produkte.helper.CheckNetworkStatus;
import com.example.julia.produkte.helper.HttpJasonParser;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Map;
public class AddProductActivity extends AppCompatActivity {
private static final String KEY_SUCCESS = "success";
private static final String KEY_PRODUCT_NAME = "name";
private static final String KEY_PREIS = "preis";
private static final String KEY_STRECKE = "strecke";
private static final String BASE_URL = "http://xxx-myIP/happyplanet/";
private static String STRING_EMPTY = "";
private EditText productNameEditText;
private EditText priceEditText;
private EditText distanceEditText;
private String productName;
private String price;
private String distance;
private Button addButton;
private int success;
private ProgressDialog pDialog;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_product);
productNameEditText = (EditText) findViewById(R.id.txtProductNameAdd);
priceEditText = (EditText) findViewById(R.id.txtPriceAdd);
distanceEditText = (EditText) findViewById(R.id.txtDistanceAdd);
addButton = (Button) findViewById(R.id.btnAdd);
addButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (CheckNetworkStatus.isNetworkAvailable(getApplicationContext())) {
addProduct();
} else {
Toast.makeText(AddProductActivity.this,
"Unable to connect to internet",
Toast.LENGTH_LONG).show();
}
}
});
}
/**
* Checks whether all files are filled. If so then calls AddMovieAsyncTask.
* Otherwise displays Toast message informing one or more fields left empty
*/
private void addProduct() {
if (!STRING_EMPTY.equals(productNameEditText.getText().toString()) &&
!STRING_EMPTY.equals(priceEditText.getText().toString()) &&
!STRING_EMPTY.equals(distanceEditText.getText().toString())) {
productName = productNameEditText.getText().toString();
price = priceEditText.getText().toString();
distance = distanceEditText.getText().toString();
new AddProductAsyncTask().execute();
} else {
Toast.makeText(AddProductActivity.this,
"One or more fields left empty!",
Toast.LENGTH_LONG).show();
}
}
/**
* AsyncTask for adding a movie
*/
private class AddProductAsyncTask extends AsyncTask<String, String, String> {
@Override
protected void onPreExecute() {
super.onPreExecute();
//Display proggress bar
pDialog = new ProgressDialog(AddProductActivity.this);
pDialog.setMessage("Adding Movie. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
@Override
protected String doInBackground(String... params) {
HttpJasonParser httpJsonParser = new HttpJasonParser();
Map<String, String> httpParams = new HashMap<>();
//Populating request parameters
httpParams.put(KEY_PRODUCT_NAME, productName);
httpParams.put(KEY_PREIS, price);
httpParams.put(KEY_STRECKE, distance);
JSONObject jsonObject = httpJsonParser.makeHttpRequest(
BASE_URL + "add_product.php", "POST", httpParams);
try {
success = jsonObject.getInt(KEY_SUCCESS);
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String result) {
pDialog.dismiss();
runOnUiThread(new Runnable() {
public void run() {
if (success == 1) {
//Display success message
Toast.makeText(AddProductActivity.this,
"Movie Added", Toast.LENGTH_LONG).show();
Intent i = getIntent();
//send result code 20 to notify about movie update
setResult(20, i);
//Finish ths activity and go back to listing activity
finish();
} else {
Toast.makeText(AddProductActivity.this,
"Some error occurred while adding movie",
Toast.LENGTH_LONG).show();
}
}
});
}
}
}
Whenever I run my app the message "some error occured while adding the movie" prints out.
I have modified the manifests and I just cannot find my mistake.
Any help would be really appreciated! I know it is a lot to read, but I am really stuck :/
java android mysql database-connection
add a comment |
I am trying to connect Android Studio to a MySQL Database on a WAMP Server. The Database is set up and called happyplanet. The connection via php is working but on the andorid side there are some errors.
I have a Check Networker Status class:
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
public class CheckNetworkStatus {
public static boolean isNetworkAvailable(Context context) {
ConnectivityManager connectivityManager
= (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
}
A Jason Parser:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.ProtocolException;
import java.net.URL;
import java.util.Map;
import org.json.JSONException;
import org.json.JSONObject;
import android.net.Uri;
import android.util.Log;
public class HttpJasonParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
HttpURLConnection urlConnection = null;
// function get json from url
// by making HTTP POST or GET method
public JSONObject makeHttpRequest(String url, String method,
Map<String, String> params) {
try {
Uri.Builder builder = new Uri.Builder();
URL urlObj;
String encodedParams = "";
if (params != null) {
for (Map.Entry<String, String> entry : params.entrySet()) {
builder.appendQueryParameter(entry.getKey(), entry.getValue());
}
}
if (builder.build().getEncodedQuery() != null) {
encodedParams = builder.build().getEncodedQuery();
}
if ("GET".equals(method)) {
url = url + "?" + encodedParams;
urlObj = new URL(url);
urlConnection = (HttpURLConnection) urlObj.openConnection();
urlConnection.setRequestMethod(method);
} else {
urlObj = new URL(url);
urlConnection = (HttpURLConnection) urlObj.openConnection();
urlConnection.setRequestMethod(method);
urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
urlConnection.setRequestProperty("Content-Length", String.valueOf(encodedParams.getBytes().length));
urlConnection.getOutputStream().write(encodedParams.getBytes());
}
urlConnection.connect();
is = urlConnection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
sb.append(line + "n");
}
is.close();
json = sb.toString();
jObj = new JSONObject(json);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
} catch (Exception e) {
Log.e("Exception", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
My Main Activity:
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// add new product button
Button addNewBtn = (Button) findViewById(R.id.addNewBtn);
addNewBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//Check for network connectivity
if (CheckNetworkStatus.isNetworkAvailable(getApplicationContext())) {
Intent i = new Intent(getApplicationContext(),
AddProductActivity.class);
startActivity(i);
} else {
//Display error message if not connected to internet
Toast.makeText(MainActivity.this,
"Unable to connect to internet",
Toast.LENGTH_LONG).show();
}
}
});
}
}
And my class to add products:
import android.app.ProgressDialog;
import android.content.Intent;
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.Toast;
import com.example.julia.produkte.helper.CheckNetworkStatus;
import com.example.julia.produkte.helper.HttpJasonParser;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Map;
public class AddProductActivity extends AppCompatActivity {
private static final String KEY_SUCCESS = "success";
private static final String KEY_PRODUCT_NAME = "name";
private static final String KEY_PREIS = "preis";
private static final String KEY_STRECKE = "strecke";
private static final String BASE_URL = "http://xxx-myIP/happyplanet/";
private static String STRING_EMPTY = "";
private EditText productNameEditText;
private EditText priceEditText;
private EditText distanceEditText;
private String productName;
private String price;
private String distance;
private Button addButton;
private int success;
private ProgressDialog pDialog;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_product);
productNameEditText = (EditText) findViewById(R.id.txtProductNameAdd);
priceEditText = (EditText) findViewById(R.id.txtPriceAdd);
distanceEditText = (EditText) findViewById(R.id.txtDistanceAdd);
addButton = (Button) findViewById(R.id.btnAdd);
addButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (CheckNetworkStatus.isNetworkAvailable(getApplicationContext())) {
addProduct();
} else {
Toast.makeText(AddProductActivity.this,
"Unable to connect to internet",
Toast.LENGTH_LONG).show();
}
}
});
}
/**
* Checks whether all files are filled. If so then calls AddMovieAsyncTask.
* Otherwise displays Toast message informing one or more fields left empty
*/
private void addProduct() {
if (!STRING_EMPTY.equals(productNameEditText.getText().toString()) &&
!STRING_EMPTY.equals(priceEditText.getText().toString()) &&
!STRING_EMPTY.equals(distanceEditText.getText().toString())) {
productName = productNameEditText.getText().toString();
price = priceEditText.getText().toString();
distance = distanceEditText.getText().toString();
new AddProductAsyncTask().execute();
} else {
Toast.makeText(AddProductActivity.this,
"One or more fields left empty!",
Toast.LENGTH_LONG).show();
}
}
/**
* AsyncTask for adding a movie
*/
private class AddProductAsyncTask extends AsyncTask<String, String, String> {
@Override
protected void onPreExecute() {
super.onPreExecute();
//Display proggress bar
pDialog = new ProgressDialog(AddProductActivity.this);
pDialog.setMessage("Adding Movie. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
@Override
protected String doInBackground(String... params) {
HttpJasonParser httpJsonParser = new HttpJasonParser();
Map<String, String> httpParams = new HashMap<>();
//Populating request parameters
httpParams.put(KEY_PRODUCT_NAME, productName);
httpParams.put(KEY_PREIS, price);
httpParams.put(KEY_STRECKE, distance);
JSONObject jsonObject = httpJsonParser.makeHttpRequest(
BASE_URL + "add_product.php", "POST", httpParams);
try {
success = jsonObject.getInt(KEY_SUCCESS);
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String result) {
pDialog.dismiss();
runOnUiThread(new Runnable() {
public void run() {
if (success == 1) {
//Display success message
Toast.makeText(AddProductActivity.this,
"Movie Added", Toast.LENGTH_LONG).show();
Intent i = getIntent();
//send result code 20 to notify about movie update
setResult(20, i);
//Finish ths activity and go back to listing activity
finish();
} else {
Toast.makeText(AddProductActivity.this,
"Some error occurred while adding movie",
Toast.LENGTH_LONG).show();
}
}
});
}
}
}
Whenever I run my app the message "some error occured while adding the movie" prints out.
I have modified the manifests and I just cannot find my mistake.
Any help would be really appreciated! I know it is a lot to read, but I am really stuck :/
java android mysql database-connection
I am trying to connect Android Studio to a MySQL Database on a WAMP Server. The Database is set up and called happyplanet. The connection via php is working but on the andorid side there are some errors.
I have a Check Networker Status class:
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
public class CheckNetworkStatus {
public static boolean isNetworkAvailable(Context context) {
ConnectivityManager connectivityManager
= (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
}
A Jason Parser:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.ProtocolException;
import java.net.URL;
import java.util.Map;
import org.json.JSONException;
import org.json.JSONObject;
import android.net.Uri;
import android.util.Log;
public class HttpJasonParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
HttpURLConnection urlConnection = null;
// function get json from url
// by making HTTP POST or GET method
public JSONObject makeHttpRequest(String url, String method,
Map<String, String> params) {
try {
Uri.Builder builder = new Uri.Builder();
URL urlObj;
String encodedParams = "";
if (params != null) {
for (Map.Entry<String, String> entry : params.entrySet()) {
builder.appendQueryParameter(entry.getKey(), entry.getValue());
}
}
if (builder.build().getEncodedQuery() != null) {
encodedParams = builder.build().getEncodedQuery();
}
if ("GET".equals(method)) {
url = url + "?" + encodedParams;
urlObj = new URL(url);
urlConnection = (HttpURLConnection) urlObj.openConnection();
urlConnection.setRequestMethod(method);
} else {
urlObj = new URL(url);
urlConnection = (HttpURLConnection) urlObj.openConnection();
urlConnection.setRequestMethod(method);
urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
urlConnection.setRequestProperty("Content-Length", String.valueOf(encodedParams.getBytes().length));
urlConnection.getOutputStream().write(encodedParams.getBytes());
}
urlConnection.connect();
is = urlConnection.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
sb.append(line + "n");
}
is.close();
json = sb.toString();
jObj = new JSONObject(json);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
} catch (Exception e) {
Log.e("Exception", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
My Main Activity:
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// add new product button
Button addNewBtn = (Button) findViewById(R.id.addNewBtn);
addNewBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//Check for network connectivity
if (CheckNetworkStatus.isNetworkAvailable(getApplicationContext())) {
Intent i = new Intent(getApplicationContext(),
AddProductActivity.class);
startActivity(i);
} else {
//Display error message if not connected to internet
Toast.makeText(MainActivity.this,
"Unable to connect to internet",
Toast.LENGTH_LONG).show();
}
}
});
}
}
And my class to add products:
import android.app.ProgressDialog;
import android.content.Intent;
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.Toast;
import com.example.julia.produkte.helper.CheckNetworkStatus;
import com.example.julia.produkte.helper.HttpJasonParser;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Map;
public class AddProductActivity extends AppCompatActivity {
private static final String KEY_SUCCESS = "success";
private static final String KEY_PRODUCT_NAME = "name";
private static final String KEY_PREIS = "preis";
private static final String KEY_STRECKE = "strecke";
private static final String BASE_URL = "http://xxx-myIP/happyplanet/";
private static String STRING_EMPTY = "";
private EditText productNameEditText;
private EditText priceEditText;
private EditText distanceEditText;
private String productName;
private String price;
private String distance;
private Button addButton;
private int success;
private ProgressDialog pDialog;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_product);
productNameEditText = (EditText) findViewById(R.id.txtProductNameAdd);
priceEditText = (EditText) findViewById(R.id.txtPriceAdd);
distanceEditText = (EditText) findViewById(R.id.txtDistanceAdd);
addButton = (Button) findViewById(R.id.btnAdd);
addButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (CheckNetworkStatus.isNetworkAvailable(getApplicationContext())) {
addProduct();
} else {
Toast.makeText(AddProductActivity.this,
"Unable to connect to internet",
Toast.LENGTH_LONG).show();
}
}
});
}
/**
* Checks whether all files are filled. If so then calls AddMovieAsyncTask.
* Otherwise displays Toast message informing one or more fields left empty
*/
private void addProduct() {
if (!STRING_EMPTY.equals(productNameEditText.getText().toString()) &&
!STRING_EMPTY.equals(priceEditText.getText().toString()) &&
!STRING_EMPTY.equals(distanceEditText.getText().toString())) {
productName = productNameEditText.getText().toString();
price = priceEditText.getText().toString();
distance = distanceEditText.getText().toString();
new AddProductAsyncTask().execute();
} else {
Toast.makeText(AddProductActivity.this,
"One or more fields left empty!",
Toast.LENGTH_LONG).show();
}
}
/**
* AsyncTask for adding a movie
*/
private class AddProductAsyncTask extends AsyncTask<String, String, String> {
@Override
protected void onPreExecute() {
super.onPreExecute();
//Display proggress bar
pDialog = new ProgressDialog(AddProductActivity.this);
pDialog.setMessage("Adding Movie. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
@Override
protected String doInBackground(String... params) {
HttpJasonParser httpJsonParser = new HttpJasonParser();
Map<String, String> httpParams = new HashMap<>();
//Populating request parameters
httpParams.put(KEY_PRODUCT_NAME, productName);
httpParams.put(KEY_PREIS, price);
httpParams.put(KEY_STRECKE, distance);
JSONObject jsonObject = httpJsonParser.makeHttpRequest(
BASE_URL + "add_product.php", "POST", httpParams);
try {
success = jsonObject.getInt(KEY_SUCCESS);
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String result) {
pDialog.dismiss();
runOnUiThread(new Runnable() {
public void run() {
if (success == 1) {
//Display success message
Toast.makeText(AddProductActivity.this,
"Movie Added", Toast.LENGTH_LONG).show();
Intent i = getIntent();
//send result code 20 to notify about movie update
setResult(20, i);
//Finish ths activity and go back to listing activity
finish();
} else {
Toast.makeText(AddProductActivity.this,
"Some error occurred while adding movie",
Toast.LENGTH_LONG).show();
}
}
});
}
}
}
Whenever I run my app the message "some error occured while adding the movie" prints out.
I have modified the manifests and I just cannot find my mistake.
Any help would be really appreciated! I know it is a lot to read, but I am really stuck :/
java android mysql database-connection
java android mysql database-connection
asked Nov 24 '18 at 14:49
JimandJhonnyJimandJhonny
94
94
add a comment |
add a comment |
0
active
oldest
votes
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53459340%2fandroid-studio-mysql-connection%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
0
active
oldest
votes
0
active
oldest
votes
active
oldest
votes
active
oldest
votes
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53459340%2fandroid-studio-mysql-connection%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown