how to connect android to mysql? - java

Please help me , I am trying to connect my android app to mysql database in localhost through connection in php and json array, but i cant figure out what is the problem , i cant view the data from database.
Here is my files.
Connection.php
<?php
$db_con = mysqli_connect('localhost', 'root', '', 'android') or die ("connection error");;
$query = "SELECT * FROM product";
$results = mysqli_query($db_con, $query) or die ("query error");;
while($row = mysqli_fetch_assoc($results)){
$output[]=$row;
}
echo json_encode($output);
?>
and this the android java "MainActivity.java" :
public class MainActivity extends ActionBarActivity {
TextView viewItem;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_main);
viewItem = (TextView) findViewById(R.id.itemView);
// Button btnViewItems = (Button) findViewById(R.id.btnViewItems);
getData();
}
public void getData() {
String results = "";
InputStream isr = null;
// Http post
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(
"http://10.0.2.2:8080/android/Connection.php");
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
} catch (Exception e) {
Log.e("log-tag", "Error in http connection" + e.toString());
viewItem.setText("Cannot connect to database");
}
// Converting response to string
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
isr, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
isr.close();
results = sb.toString();
} catch (Exception e) {
Log.e("log-tag", "Error Converting string" + e.toString());
viewItem.setText("Cannot convert string");
}
// prase jason data
try {
String s = "";
JSONArray jArray = new JSONArray(results);
for (int i = 0; i < jArray.length(); i++) {
JSONObject jOb = jArray.getJSONObject(i);
s = s + jOb.getString("id") + " || " + jOb.getString("name")
+ " || " + jOb.getString("cost") + "\n\n";
}
viewItem.setText(s);
} catch (Exception e) {
Log.e("log-tag", "prasing json data" + e.toString());
viewItem.setText("cannot prase json data");
}
}
}
and the out keep saying : "cannot prase json data".
here is the log error :
E/log-tag(1904): Error in http connectionandroid.os.NetworkOnMainThreadException
E/log-tag(1904): Error Converting stringjava.lang.NullPointerException: lock == null
E/log-tag(1904): prasing json dataorg.json.JSONException: End of input at character 0 of
thanks

You need to run HTTP requests on different thread instead on main thread. Android API does not allow running HTTP requests on main thread. Try using Runnable() to run http request asynchronously on separate thread.

Related

Get Json data from the Url below(Url returns json data)

This is the URL which returns me the json object Link.
Now I need to get the json data to my code. When I try to access the link I get the html script. How do I get the json data from the above URL to my code. Here is my code.
class task extends AsyncTask<String, String, Void>
{
private ProgressDialog progressDialog = new
`ProgressDialog(MainActivity.this);`
InputStream is = null ;
String result = "";
protected void onPreExecute() {
progressDialog.setMessage("Fetching data...");
progressDialog.show();
progressDialog.setOnCancelListener(new OnCancelListener() {
#Override
public void onCancel(DialogInterface arg0) {
task.this.cancel(true);
}
});
}
#Override
protected Void doInBackground(String... params) {
String url_select1 = "http://andpermission.byethost5.com/PermissionList.php";
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url_select1);
ArrayList<NameValuePair> param = new ArrayList<NameValuePair>();
try {
httpPost.setEntity(new UrlEncodedFormEntity(param));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
//read content
is = httpEntity.getContent();
} catch (Exception e) {
Log.e("log_tag", "Error in http connection "+e.toString());
//Toast.makeText(MainActivity.this, "Please Try Again", Toast.LENGTH_LONG).show();
}
try {
BufferedReader br = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = "";
while((line=br.readLine())!=null)
{
sb.append(line+"\n");
}
is.close();
result=sb.toString();
} catch (Exception e) {
// TODO: handle exception
Log.e("log_tag", "Error converting result "+e.toString());
}
return null;
}
protected void onPostExecute(Void v) {
// ambil data dari Json database
try {
JSONArray Jarray = new JSONArray(result);
for(int i=0;i<Jarray.length();i++)
{
JSONObject Jasonobject = null;
//text_1 = (TextView)findViewById(R.id.txt1);
Jasonobject = Jarray.getJSONObject(i);
//get an output on the screen
//String id = Jasonobject.getString("id");
String name = Jasonobject.getString("name");
String db_detail="";
if(et.getText().toString().equalsIgnoreCase(name)) {
db_detail = Jasonobject.getString("detail");
text.setText(db_detail);
break;
}
//text_1.append(id+"\t\t"+name+"\t\t"+password+"\t\t"+"\n");
}
this.progressDialog.dismiss();
} catch (Exception e) {
// TODO: handle exception
Log.e("log_tag", "Error parsing data "+e.toString());
}
}
}
Using string builder I append the content and I find only the java script and I don't find the json data. How to I get the json data from the above URL.
In string "Result" in my code I get the below output.
<html>
<body>
<script type="text/javascript" src="/aes.js"></script>
<script>
function toNumbers(d) {
var e = [];
d.replace(/(..)/g, function(d) {
e.push(parseInt(d, 16))
});
return e
}
function toHex() {
for (var d = [], d = 1 == arguments.length && arguments[0].constructor == Array ? arguments[0] : arguments, e = "", f = 0; f < d.length; f++) e += (16 > d[f] ? "0" : "") + d[f].toString(16);
return e.toLowerCase()
}
var a = toNumbers("f655ba9d09a112d4968c63579db590b4"),
b = toNumbers("98344c2eee86c3994890592585b49f80"),
c = toNumbers("b8eeb5e790c4a5395d01cde6b8230fdd");
document.cookie = "__test=" + toHex(slowAES.decrypt(c, 2, a, b)) + "; expires=Thu, 31-Dec-37 23:55:55 GMT; path=/";
location.href = "http://andpermission.byethost5.com/PermissionList.php?ckattempt=1";
</script>
<noscript>This site requires Javascript to work, please enable Javascript in your browser or use a browser with Javascript support</noscript>
How do I get only the json data from the URL instead the java script.
Try the full URL: http://andpermission.byethost5.com/PermissionList.php?ckattempt=1.
And also make sure you are using GET instead of POST, because that's what the URL refers to.
Here a good example: http://www.learn2crack.com/2013/10/android-json-parsing-url-example.html
On the other hand, there are some libraries like Aquery, Okhttp and Volley, that do this job very good.

Grabbing JSON content with Java

Here is a sample of my json_encode in PHP:
print(json_encode($row));
leads to {"AverageRating":"4.3"} which is good.
But in Java, I can not seem to grab this 4.3 value. Here it is (for an Android project) I have edited non-relevant data.
public class Rate extends ListActivity {
JSONArray jArray;
String result = null;
InputStream is = null;
StringBuilder sb = null;
String Item, Ratings, Review, starAvg;
RatingBar ratingsBar;
ArrayList<NameValuePair> param;
public void onCreate(Bundle savedInstanceState) {
starAvg = "0"; // Sets to 0 in case there are no ratings yet.
new starRatingTask().execute();
ratingsBar = (RatingBar) findViewById(R.id.theRatingBar);
class starRatingTask extends AsyncTask<String, String, Void> {
InputStream is = null;
String result = "";
#Override
protected Void doInBackground(String... params) {
String url_select = "http://www.---.com/---/average_stars.php";
ArrayList<NameValuePair> param = new ArrayList<NameValuePair>();
param.add(new BasicNameValuePair("item", Item));
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url_select);
try {
httpPost.setEntity(new UrlEncodedFormEntity(param));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
// read content
is = httpEntity.getContent();
} catch (Exception e) {
Log.e("log_tag", "Error in http connection " + e.toString());
}
try {
BufferedReader br = new BufferedReader(
new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = "";
while ((line = br.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
} catch (Exception e) {
Log.e("log_tag", "Error converting result " + e.toString());
}
return null;
}
protected void onPostExecute(Void v) {
String starAvgTwo = null;
try {
jArray = new JSONArray(result);
JSONObject json_data = null;
for (int i = 0; i < jArray.length(); i++) {
json_data = jArray.getJSONObject(i);
starAvg = json_data.getString("AverageRating");
starAvgTwo = starAvg;
}
} catch (JSONException e1) {
Toast.makeText(getBaseContext(), "No Star Ratings!",
Toast.LENGTH_LONG).show();
} catch (ParseException e1) {
e1.printStackTrace();
}
Toast.makeText(getBaseContext(), starAvgTwo,
Toast.LENGTH_LONG).show();
ratingsBar.setRating(Float.valueOf(starAvg));
}
}
That second toast produces a blank (I assume a "" - empty string?). If I change the toast variable back to starAvg, then it toasts "0".
How can I retrieve the value of 4.3.
As we discussed in the comments on the original question, the PHP is sending down as single JSONObject rather than an array. Parsing as a JSONObject is required in it's present state; however, if you begin sending down an array of your value objects, then you'd use JSONArray to parse it.
I think your JSON doesn't contain array. so just do this:
JSONObject jsonObject = new JSONObject(result); //to convert string to be a JSON object
String averageRating = jsonObject.getString("AverageRating"); //get the value of AverageRating variable
and try toast the averageRating.
and how to get the array from JSON object?
if you have JSON:
{"employees": [
{ "firstName":"John" , "lastName":"Doe" },
{ "firstName":"Anna" , "lastName":"Smith" },
{ "firstName":"Peter" , "lastName":"Jones" }]
}
then use this code
JSONArray jsonArray = new JSONArray(result);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
Log.i(Rate.class.getName(), jsonObject.getString("firstName"));
}
that code will produce
John Anna Peter
in your LogCat

PHP-script server side not returning anything back to Android app

I'm programming a client-server application for Android where the application sends a POST to a php-script server side. This script search a database and returns the results. However I'm not getting it to work. The communication between client and server is json formatted.
This is the functions in the android activity. The second function is a copy-paste which I can take no credit for and which I found on the internetz:
private void testDB(){
//Creating a json-representation of my query
JSONObject query = new JSONObject();
try {
query.put("author", "SomeAuthor");
query.put("title", "SomeTitle");
} catch (JSONException e1) {
e1.printStackTrace();
}
String json = query.toString();
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://myserver.com/search_books.php");
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("jsondata", json));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
InputStream in = response.getEntity().getContent();
String results = convertStreamToString(in);
Toast.makeText(getApplicationContext(), results, Toast.LENGTH_LONG).show();
} catch (ClientProtocolException e) {
System.out.println("ERROR (ClientProtocolException): " + e.toString());
} catch (IOException e) {
System.out.println("ERROR (IOException): " + e.toString());
}
}
private String convertStreamToString(InputStream is) {
/*
* To convert the InputStream to String we use the BufferedReader.readLine()
* method. We iterate until the BufferedReader return null which means
* there's no more data to read. Each line will appended to a StringBuilder
* and returned as String.
*/
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
And this is the php-script:
<?php
//Get the information from the request (POST)
$jsonInput = $_POST['jsondata'];
$decoded = json_decode($jsonInput,true);
//Connect to the database
$connection = mysql_connect(localhost, username, password);
if (!$connection) {
die("Could not connect to db: " . mysql_error());
}
//Select the database to be used
mysql_select_db("muffin_books", $connection) or die(mysql_error());
//Construct the query
$sql = "SELECT * FROM Books WHERE author='" . $decoded['author'] . "' AND title='" . $decoded['title'] . "'";
//Make the query to the database with the connection
$query_results = mysql_query($sql, $connection);
//If no results were returned
if (!$query_results) {
die("Could not connect to db: ", mysql_error());
}
//Get the array from the results
$info = mysql_fetch_array($query_results, MYSQL_ASSOC);
//Return the data encoded in json
echo json_encode($info);
//Disconnect database
mysql_close($connection);
?>
The problem is that the Toast just comes up empty.
I am 100% sure that the row exists in the database.
myserver.com is not my actual server, in my file it says something else here.
username and password are also customized in my code.
Thanks in advance!
since you are sending strig to the server i think you need to modify your sql query as
$sql = "SELECT * FROM Books WHERE author=" . $decoded['author'] . " AND title=" . $decoded['title'] . "";

mySQL to PHP to JSON: String Cannot be Converted to JSONObject

I am trying to get data from a mySQL database using PHP. This is my fist real attempt of getting data remotely & using JSON. The php file is functioning correctly because it outputs in a browser as a JSON string and i valadated it using JSONLint. So, I am not sure what I have wrong here. Any help would be greatly appreciated
This is what LogCat is throwing:
Error parsing data org.json.JSONException: Value <?xml of type java.lang.String cannot be converted to JSONObject
threadid=9: thread exiting with uncaught exception (group=0x401dce20)
FATAL EXCEPTION: Thread-10
java.lang.NullPointerException
at com.andaero.test.JSON.JSONMain$1.run(JSONMain.java:39)
at java.lang.Thread.run(Thread.java:1020)
UPDATE: I removed the echo method from the php file as Mark requested. I think it has to do with "JSONArray a = json.getJSONArray("regulatory"). I also tried everyone else's approach with no prevail.
Here are the classes:
public class JSONfunctions {
public static JSONObject getJSONfromURL(String url) {
InputStream is = null;
String result = "regulatory";
JSONObject jArray = null;
// http post
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
} catch (Exception e) {
Log.e("log_tag", "Error in http connection " + e.toString());
}
// convert response to string
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
} catch (Exception e) {
Log.e("log_tag", "Error converting result " + e.toString());
}
try {
jArray = new JSONObject(result);
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
}
return jArray;
}
}
The List Activity:
public class JSONMain extends ListActivity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.listview);
final ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();
new Thread(new Runnable() {
public void run() {
JSONObject json = JSONfunctions
.getJSONfromURL("http://192.168.1.34/andaero/regulatory_list_ASC.php");
try {
JSONArray a = json.getJSONArray("regulatory");
for (int i = 0; i < a.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
JSONObject e = a.getJSONObject(i);
map.put("id", String.valueOf(i));
map.put("label", e.getString("label"));
map.put("title", e.getString("title"));
map.put("caption", e.getString("description"));
map.put("dummy", e.getString("gotoURL"));
mylist.add(map);
}
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
}
}
}).start();
ListAdapter adapter = new SimpleAdapter(this, mylist,
R.layout.list_item, new String[] { "label", "title", "caption",
"dummy" }, new int[] { R.id.label, R.id.listTitle,
R.id.caption, R.id.dummy });
setListAdapter(adapter);
final ListView lv = getListView();
lv.setTextFilterEnabled(true);
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
#SuppressWarnings("unchecked")
HashMap<String, String> o = (HashMap<String, String>) lv
.getItemAtPosition(position);
Toast.makeText(JSONMain.this,
"ID '" + o.get("id") + "' was clicked.",
Toast.LENGTH_SHORT).show();
}
});
}
}
The PHP:
<?php
//MySQL Database Connect
include 'andaerologin.php';
mysql_select_db("andaero");
$sql=mysql_query("select * from regulatory_list");
$output = array();
while($row = mysql_fetch_assoc($sql)) {
$output['regulatory'][] = $row;
}
exit (json_encode($output));
mysql_close();
?>
Try changing your PHP to this:
$output = new stdClass();
$output->regulatory = array();
while($row = mysql_fetch_assoc($sql)) {
$output->regulatory[] = $row;
}
header('Content-type: application/json');
echo (json_encode($output));
Try changing your PHP script to this:
<?php
// Hide errors to prevent data corruption
ini_set('display_errors', 0);
// For debugging, uncomment these lines to show errors
//ini_set('display_errors', 0);
//error_reporting(E_ALL);
//MySQL Database Connect
require 'andaerologin.php';
if (!mysql_select_db("andaero")) {
// Use trigger_error() so you can find out in the server logs if something
// goes wrong
trigger_error('Unable to select MySQL database');
header('HTTP/1.1 500 Internal Server Error');
exit;
}
$query = "SELECT *
FROM regulatory_list";
if (!$result = mysql_query($query)) {
trigger_error('MySQL error: '.mysql_error());
header('HTTP/1.1 500 Internal Server Error');
exit;
}
if (!mysql_num_rows($query)) {
trigger_error('MySQL returned no results');
header('HTTP/1.1 500 Internal Server Error');
exit;
}
// Build an array of the results
$output = array();
while ($row = mysql_fetch_assoc($result)) {
$output[] = $row;
}
// Send the results back as JSON
exit(json_encode($output));
// Closing the database connection happens implicitly at the end of the
// script. Also, you don't need to have a closing PHP tag at the end of the
// file and omitting it is a good habit to get into as it can avoid problems
In your PHP code, change
json_encode($output)
to
json_encode($output, JSON_FORCE_OBJECT)
The JSON_FORCE_OBJECT option requires PHP version >= 5.3.0
Your problem seems to be at jArray = new JSONObject(result);
I don't know what the JSONObject constructor expects, but I know you are sending a JSON array to it, not an object.
Do you really need all those fields in the table?
I once did the same, SELECT * FROM table, and json_encode() all the results. jQuery seemed to have a problem reading the data even though the JSON result looks perfectly fine.
So I tried to limit the data and send only the required fields to the browser by SELECT field1, field2 FROM table, instead of all the fields.
Then everything worked fine. I could only suspect that there's a limit to the amount of JSON data jQuery can parse.
I know you aren't using jQuery but I'm just leaving my experience here just in case.

How to retrieve data from json array and display in textview?

I've been using the coding from an example from this link: The code is as shown below:
public class food extends ListActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
String result = null;
InputStream is = null;
StringBuilder sb=null;
String result=null;
TextView fdi = (TextView)findViewById(R.id.textView1);
TextView fdn = (TextView)findViewById(R.id.textView2);
//http post
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://127.0.0.1/food.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}catch(Exception e){
Log.e("log_tag", "Error in http connection"+e.toString());
}
//convert response to string
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
sb = new StringBuilder();
sb.append(reader.readLine() + "\n");
String line="0";
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result=sb.toString();
}catch(Exception e){
Log.e("log_tag", "Error converting result "+e.toString());
}
//paring data
int fd_id;
String fd_name;
try{
jArray = new JSONArray(result);
JSONObject json_data=null;
for(int i=0;i<jArray.length();i++){
json_data = jArray.getJSONObject(i);
fd_id=json_data.getInt("FOOD_ID");
fd_name=json_data.getString("FOOD_NAME");
}
}catch(JSONException e1){
Toast.makeText(getBaseContext(), "No Food Found", Toast.LENGTH_LONG).show();
}catch (ParseException e1){
e1.printStackTrace();
}
}
}
Now my question is how to pass this data to a list view, like for each iteration a list item must be added with the retrieved data.
Please help me
Thanks in advance
You are already getting strings in below code, Why don't you use that.
for(int i=0;i<jArray.length();i++){
json_data = jArray.getJSONObject(i);
fd_id=json_data.getInt("FOOD_ID");
fd_name=json_data.getString("FOOD_NAME");
}
//fdname and fd_id you are getting it right,
If your code is not working then add what problem you are facing.
according to your response/result from the server below code is working for me and giving output in string ,
try {
String response ="[{\"FOOD_ID\":\"1\",\"FOOD_NAME\":\"Rice\"},{\"FOOD_ID\":\"2\",\"FOOD_NAME\":\"Daal\"}] ";
JSONArray array;
array = new JSONArray(response);
for (int i = 0; i < array.length(); i++) {
JSONObject obj = array.getJSONObject(0);
String id_fd = obj.getString("FOOD_ID");
String name_fd = obj.getString("FOOD_NAME");
Log.d("JSONArray", id_fd+" " +name_fd);
}} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
please use it according to your need.
The root cause of the error a NullPointerException. This means that you are trying to use an object that has the value null. Usually this is because the object has not yet been initialised.
In your case the nullpointer is caused by something at line 29 of your Food class, probably one of these two lines
TextView fdi = (TextView)findViewById(R.id.textView1);
TextView fdn = (TextView)findViewById(R.id.textView2);
Are you sure that both the R.id.textView1 and R.id.textView1 exist? They should be specified somewhere in a layout xml file, something like this:
<TextView
android:id="#+id/textView1"
....

Categories