I am developing a final year project where I need to connect Android emulator with MySQL database in order to retrieve values. Java file:
public class connectivity extends Activity {
/** Called when the activity is first created. */
TextView txt;
public static final String KEY_121 = "http://10.0.2.2/mysqlcon.php";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
LinearLayout rootLayout = new LinearLayout(getApplicationContext());
txt = new TextView(getApplicationContext());
rootLayout.addView(txt);
setContentView(rootLayout);
// Set the text and call the connect function.
txt.setText("Connecting...");
// call the method to run the data retreival
txt.setText(getServerData(KEY_121));
}
private String getServerData(String returnString) {
InputStream is = null;
String result = null;
// the year data to send
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("year", "1970"));
// http post
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(KEY_121);
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);
StringBuilder sb = new StringBuilder();
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());
}
// parse json data
try {
JSONArray jArray = new JSONArray(result);
JSONObject json_data = null;
for (int i = 0; i < jArray.length(); i++) {
json_data = jArray.getJSONObject(i);
Log.i("log_tag", "id: " + json_data.getInt("id") + ", name: " + json_data.getString("name") + ", sex: " + json_data.getInt("sex") + ", birthyear: " + json_data.getInt("birthyear"));
// Get an output to the screen
returnString += "\n\t" + jArray.getJSONObject(i);
}
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
}
return returnString;
}
}
I have also given an internet permission in my Android manifest file. But after running the application I get the following error in logcat:
ERROR PARSING DATA org.json.JSONException:A JSONArraytext must start with '[' at character 0
I think this goes to show that a null value is being returned. Please help me out as this is my final year project. I have spent hours trying to find the solutions but it has been of no use.
I am currently using Android 2.2. The wamp server is on the localhost so I am using the address 10.0.2.2 which is a special alias to localhost (127.0.0.1). Any help will be really appreciated.
Here is the PHP code:
<?php
mysql_connect("127.0.0.1","root","chetan");
mysql_select_db("db1");
$q=mysql_query("SELECT * FROM people WHERE birthyear>'".$_REQUEST['year']."'");
while($e=mysql_fetch_assoc($q))
$output[]=$e;
print(json_encode($output,JSON_FORCE_OBJECT));
mysql_close();
This is actually an issue I've run into before. The problem is your server isn't outputting valid JSON. It's missing some of the markup. I suggest you print the raw text of the response to Logcat and examine it. Perhaps even pass it into a JSON validator. That will also help you figure out if it is returning an empty value. If it's returning an empty value, then you'll need to debug your server...not your client...
Additionally, try visiting the php page from your browser and letting it simply display the JSON response. This will allow you to see what's being written by the server and help you determine where the problem really is. Just be aware, because the server is expecting a POST the easiest way to test this would probably to be to create a simple html form to POST the test data to that page. Without doing that, getting a browser to do a POST on it's own can be a pain.
do u need to use connection to php??? if not you can directly connect to mysql db to retrieve the result:
// Assume function to be :
public String customerData() {
String customerInfo = ""; //To store result
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con =
DriverManager.getConnection(
"jdbc:mysql://10.0.2.2:3306/retailer","root","pswrd");
PreparedStatement statement = con.prepareStatement("SELECT * FROM customers");
ResultSet result = statement.executeQuery();
while(result.next()) {
customerInfo = customerInfo + result.getString("name") + "&" +
result.getString("C_ID") + "&" + result.getString("address") +
"&" + result.getString("email");
// Here "&"s are added to the return string. This is help to split the
// string in Android application
}
} catch(Exception exc) {
System.out.println(exc.getMessage());
}
return customerInfo;
}
But to your project library include Connector jar file for Mysql.
Related
i'm trying to parse the information of a json array into android.
I use the below code, and i get info from a webservice, if i open the php file it's all ok, but in android i get could not connect to database. I do have set permissions to access the internet...
Here is the code i use:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
StrictMode.enableDefaults(); //STRICT MODE ENABLED
resultView = (TextView) findViewById(R.id.result);
getData();
}
public void getData(){
String result = "";
InputStream isr = null;
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://192.168.10.28/albana/getAllCustomers.php"); //YOUR PHP SCRIPT ADDRESS
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
isr = entity.getContent();
}
catch(Exception e){
Log.e("log_tag", "Error in http connection "+e.toString());
resultView.setText("Couldnt connect to database");
}
//convert 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();
result=sb.toString();
}
catch(Exception e){
Log.e("log_tag", "Error converting result "+e.toString());
}
//parse json data
try {
String s = "";
JSONArray jArray = new JSONArray(result);
for(int i=0; i<jArray.length();i++){
JSONObject json = jArray.getJSONObject(i);
s = s +
"Name : "+json.getString("FirstName")+" "+json.getString("LastName")+"\n"+
"Age : "+json.getInt("Age")+"\n"+
"Mobile Using : "+json.getString("Mobile")+"\n\n";
}
resultView.setText(s);
} catch (Exception e) {
// TODO: handle exception
Log.e("log_tag", "Error Parsing Data "+e.toString());
}
}
I get the message "Could not connect to database";
No errors on the Log Cat...
Please someone suggest me..
You are trying to connect to 192.168.10.28, which is a private or non-routable network address. You can only connect to it if you're on that network (or a network that specifically connects to it). Are you connected through wifi to the network? If so, I would expect it to work so try opening the URL in your web browser and see if you get a json response. If you're connected to it by your mobile network I wouldn't expect it to work.
I'm pretty sure you don't want to use a HttpPost here. Try HttpGet instead, syntax stays the same.
Also check Dave's answer.
In httpd.conf file make the following changes
change:
Deny from all
Allow from 127.0.0.1
Allow from ::1
Allow from localhost
to:
Allow from all
and restart all the services, works like a charm.
I m implementing a REST based HTTP server in Android. The server responds for GET, DELETE and POST requests. Two android devices communicate using HTTP Post (I m using a service, where a device keeps listening on a port and post to next device and this keeps going on).
I m testing the GET and DELETE using Mozilla Poster. Should I add a separate socket/port to handle the same? Because when I try now, sometimes I get timeout error or no response found. However, I am able to see server response in Logcat window. Please help me.
Code to handle GET request:
if(method.equals("GET"))
{
if(checkFileExisting())
{
BufferedReader reader = new BufferedReader(new FileReader(new File(getFilesDir()+File.separator+"script.json")));
String read;
StringBuilder builder = new StringBuilder("");
while((read = reader.readLine()) != null)
{
builder.append(read);
}
String JSONContents = builder.toString();
reader.close();
JSONObject jsonObject;
try {
jsonObject = new JSONObject(JSONContents);
String name = jsonObject.getString("name");
JSONObject stateObject = jsonObject.getJSONObject("state");
String stateValue = stateObject.getString("value");
if(name.equals(target))
{
HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, 200, "OK");
response.setEntity(new StringEntity("State is:" + stateValue));
conn.sendResponseHeader(response);
conn.sendResponseEntity(response);
}
else
{
HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, 404, "Not Found");
response.setEntity(new StringEntity("The requested resource " + target + " could not be found due to mismatch!!"));
conn.sendResponseHeader(response);
conn.sendResponseEntity(response);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
else
{
HttpResponse response = new BasicHttpResponse(HttpVersion.HTTP_1_1, 404, "Not Found");
response.setEntity(new StringEntity("The requested resource " + target + " could not be found!!"));
conn.sendResponseHeader(response);
conn.sendResponseEntity(response);
}
}
The link http://www.integratingstuff.com/2011/10/24/adding-a-webserver-to-an-android-app/ has a very good example. I missed conn.close() in my code.
Here I want to display the JSON content using API key. But I am unable to get the authentication.
I am getting the error in JsonObject:
org.json.JSONException: Value Authorization of type java.lang.String cannot be converted to JSONObject
In my android application, I just pass the API key and URL id to get the JSON response in the following URL. I display the JSON content using JSON array.
But if I:
public class AndroidAPiActivity extends Activity {
/*
* FlickrQuery = FlickrQuery_url
* + FlickrQuery_per_page
* + FlickrQuery_nojsoncallback
* + FlickrQuery_format
* + FlickrQuery_tag + q
* + FlickrQuery_key + FlickrApiKey
*/
String FlickrQuery_url = "http://192.138.11.9/api/interests/";
String FlickrQuery_per_page = "&per_page=1";
String FlickrQuery_nojsoncallback = "&nojsoncallback=1";
String FlickrQuery_format = "&format=json";
String FlickrQuery_tag = "&tags=";
String FlickrQuery_key = "&api_key=";
// Apply your Flickr API:
// www.flickr.com/services/apps/create/apply/?
String FlickrApiKey = "f65215602df8f8af";
EditText searchText;
Button searchButton;
TextView textQueryResult, textJsonResult;
ImageView imageFlickrPhoto;
Bitmap bmFlickr;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
searchText = (EditText)findViewById(R.id.searchtext);
searchButton = (Button)findViewById(R.id.searchbutton);
textQueryResult = (TextView)findViewById(R.id.queryresult);
textJsonResult = (TextView)findViewById(R.id.jsonresult);
imageFlickrPhoto = (ImageView)findViewById(R.id.flickrPhoto);
searchButton.setOnClickListener(searchButtonOnClickListener);
}
private Button.OnClickListener searchButtonOnClickListener
= new Button.OnClickListener(){
public void onClick(View arg0) {
// TODO Auto-generated method stub
String searchQ = searchText.getText().toString();
String searchResult = QueryFlickr(searchQ);
textQueryResult.setText(searchResult);
String jsonResult = ParseJSON(searchResult);
textJsonResult.setText(jsonResult);
if (bmFlickr != null){
imageFlickrPhoto.setImageBitmap(bmFlickr);
}
}};
private String QueryFlickr(String q){
String qResult = null;
String qString =
FlickrQuery_url
+ FlickrQuery_per_page
+ FlickrQuery_nojsoncallback
+ FlickrQuery_format
+ FlickrQuery_tag + q
+ FlickrQuery_key + FlickrApiKey;
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(qString);
try {
HttpEntity httpEntity = httpClient.execute(httpGet).getEntity();
if (httpEntity != null){
InputStream inputStream = httpEntity.getContent();
Reader in = new InputStreamReader(inputStream);
BufferedReader bufferedreader = new BufferedReader(in);
StringBuilder stringBuilder = new StringBuilder();
String stringReadLine = null;
while ((stringReadLine = bufferedreader.readLine()) != null) {
stringBuilder.append(stringReadLine + "\n");
}
qResult = stringBuilder.toString();
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return qResult;
}
private String ParseJSON(String json){
String jResult = null;
bmFlickr = null;
String key_id;
String category;
String subcategory;
String title;
String icon_image;
try
{
JSONObject JsonObject = new JSONObject(json);
JSONObject Json_photos = JsonObject.getJSONObject("interests");
JSONArray JsonArray_photo = Json_photos.getJSONArray("interest");
//We have only one photo in this exercise
JSONObject FlickrPhoto = JsonArray_photo.getJSONObject(0);
key_id = FlickrPhoto.getString("row_key");
category = FlickrPhoto.getString("category");
subcategory = FlickrPhoto.getString("subcategory");
title = FlickrPhoto.getString("title");
jResult = "\n key_id: " + key_id + "\n"
+ "category: " + category + "\n"
+ "subcategory: " + subcategory + "\n"
+ "title: " + title + "\n";
bmFlickr = LoadPhotoFromFlickr(key_id, category, subcategory,title);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return jResult;
}
private Bitmap LoadPhotoFromFlickr(
String key_id, String category, String subcategory,
String title){
Bitmap bm= null;
String icon_image = null;
// String FlickrPhotoPath ="";
String FlickrPhotoPath ="http://182.72.180.34/media/"+icon_image+".jpg";
URL FlickrPhotoUrl = null;
try {
FlickrPhotoUrl = new URL(FlickrPhotoPath);
HttpURLConnection httpConnection = (HttpURLConnection) FlickrPhotoUrl.openConnection();
httpConnection.setDoInput(true);
httpConnection.connect();
InputStream inputStream = httpConnection.getInputStream();
bm = BitmapFactory.decodeStream(inputStream);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return bm;
}
}
Update:
Based on the HTML response, I can tell you that this is not JSON. The response tells me that you have the incorrect URL for your web service.
You need to check your URL.
Extra Info / Previous Answer:
It looks like the simple answer is the right one - your result is not a valid JSON string. See JSON.org website for details on what JSON should look like.
Check out JSON Parser Online - I find its very useful when working with JSON.
It is strange that you are requesting JSON, and it is not returning it properly - perhaps I have missed something.
Yes, we get such kind of warning when the given URL is not valid.
Just check the URL once.
Remove docType from API. and set content Type Application/json .
(as text/html will not read as json . thus you were seeing the error.)
May be this can help
https://teamtreehouse.com/community/solved-exception-cannot-convert-string-type-to-json-object
Solved.
It turns out the runtime error stretched back to the previous video.
I was doing
JSONObject currently = new JSONObject("currently");
instead of
JSONObject currently = forecast.getJSONObject("currently");
So my guess is Android thought I was trying to setup an entirely new JSON object instead of trying to retrieve information from an existing one! :) Now the console displays the time perfectly!
I've faced this issue too, I changed my Internet connection to another network and it works.
The problem was that ISP doesn't accept http access.
Another solution you can open VPN and try again, and maybe it works...
HOW I FIXED THE FOLLOWING ERRORS:
=============================================================================
org.json.JSONException: Value <br of type java.lang.String cannot be converted to JSONObject
org.json.JSONException: Value permissions of type java.lang.String cannot be converted to JSONObject
==============================================================================
This might not apply to this particular scenario, but it comes up as a top search result for the given issue/keyword.
So, i bought a script from a professional vendor on codecanyon.
The script consisted of 3x main parts;
- MAIN CART SITE (PHP)
- MAIN ADMIN SITE + /API (PHP)
- ANDROID ADMIN APP (JAVA)
I found many issues once the script was installed. Ranging from incomplete or missing table arrays on the MAIN CART SITE, then i had a problem on the ANDROID ADMIN APP that (upon inspection of logs) revealed a mysqli_exception was to blame.
So after hours of messing around with loops and trying to figure out where the issue was. After actually learning how to dump output to the logs / logcat. I was able to determine that it was in actual fact, a;
BREAKING CHANGE SINCE MYSQL-8
TO FIX, RUN THE FOLLOWING COMMANDS IN mysql TERMINAL;
SET GLOBAL sql_mode = '';
SET SESSION sql_mode = '';
THIS REMOVES THE 'STRICT MODE' amongst other rules that has caused me so much grief over the last few days. Thought i'd better share the answer, hopefully save someone else days of eye-drying torment =].
Remember to reintroduce the default ruleset one rule at a time and test to see what modes your app can support (if this solution fixes your problem) as they are no doubt essential security/data-integrity measures that are there for good reason. Ideally, update codebase to comply with current standards. Unfortunately that's way beyond me at this stage.
Hope this works for you guys.
I received the same "<!Doctype..." error when working with Google Translate's json URLs. Then, I found this code somewhere and it worked :
BasicHttpParams basicHttpParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout((HttpParams)basicHttpParams, (int)10000);
HttpConnectionParams.setSoTimeout((HttpParams)basicHttpParams, (int)10000);
HttpConnectionParams.setTcpNoDelay((HttpParams)basicHttpParams, (boolean)true);
DefaultHttpClient defaultHttpClient = new DefaultHttpClient((HttpParams)basicHttpParams);
HttpGet httpGet = new HttpGet(url);
BasicResponseHandler basicResponseHandler = new BasicResponseHandler();
JSONObject json=null;
try {
json = new JSONObject((String)defaultHttpClient.execute((HttpUriRequest)httpGet, (ResponseHandler)basicResponseHandler));
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
I am very new to android and I'm trying to make a program that shows you results from a database that I have. So when I type in a first name and the database sends the information of that person to me. However, when I look at the LogCat it says
"09-09 22:05:39.544: ERROR/log_tag(8813): Error parsing data org.json.JSONException: Value
This is my code:
public class PS extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//get the two controls we created earlier, also with the resource reference and the id
final EditText et_Text = (EditText)findViewById(R.id.et_Text);
//add new KeyListener Callback (to record key input)
et_Text.setOnKeyListener(new OnKeyListener()
{
//function to invoke when a key is pressed
public boolean onKey(View v, int keyCode, KeyEvent event)
{
//check if there is
if (event.getAction() == KeyEvent.ACTION_DOWN)
{
//check if the right key was pressed
if (keyCode == KeyEvent.KEYCODE_ENTER)
{
InputStream is = null;
String result = "";
//the name data to send
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("name",et_Text.getText().toString()));
//http post
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://myIPaddress/sampleDB/testSend.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());
}
// At this point is should be set, if it isn't, tell user what went wrong
if (is != null) {
//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());
}
//parse json data
try{
JSONArray jArray = new JSONArray(result);
for(int i=0;i<jArray.length();i++){
JSONObject json_data = jArray.getJSONObject(i);
Log.i("log_tag","PersonID: "+json_data.getInt("personID")+
", FirstName: "+json_data.getString("FirstName")+
", LastName: "+json_data.getString("LastName")+
", Age: "+json_data.getInt("Age")
);
}
}catch(JSONException e){
Log.e("log_tag", "Error parsing data "+e.toString());
}} else {Log.i("log_tag", "Something went wrong!"//I don't know what to put here);} ;
et_Text.setText("");
//and clear the EditText control
return true;
}
}
return false;
}
});
}
}
This is my php code:
<?php
$con = mysql_connect("localhost","username","password");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("_usersDB", $con);
$q=mysql_query("SELECT * FROM Persons WHERE FirstName='".$_REQUEST['name']."'");
while($e=mysql_fetch_assoc($q))
$output[]=$e;
print(json_encode($output));
mysql_close($con);
?>
The output it's parsing on is when I input "Eric" then It'll give me personID of 1, FirstName of Eric, LastName of (my last name), and age of 15. I'm not sure if you were asking for that...
First of all, it may not be wise to share your database connection details with the rest of the world. Second of all, it's not a great idea to do networking operations on the UI Thread.
Lastly (which is what you want to know), it looks likes the output on the server may be different than what the client is expecting. Can you post the output it is parsing on? I'll revise this answer once you do so.
It looks as if the server is prepending an XML declaration to the JSON (). You might want to examine the HTTP traffic output by the web server (via logging or wireshark) as a first step to see if the problem lies with the client or the server.
i want to develop an Android application that will take the content from internet (server) and present it in the application.
(ex. i take the todays weather forecast, put the numbers in SQLite database or .txt file , put the database/txt file on internet server so when i open the application, the app connects&downloads the database via the net and presents me with todays forecast)
If you can references me to some example/video tutorial/book that deals with this issue i will be very thankful!
What you want to do is developing a rest api that provides data for your android app. E.g. you website has some content that you want use in your app, then you could write a php script that just returns that data in a specific format.
E.g. mysite.net/rest/fetchAllLocations.php?maybe_some_parameters
This would return locations in e.g. json format, here is an example how that looks like:
[{"id":1,"shop_lng":8.5317153930664,"shop_lat":52.024803161621,"shop_zipcode":33602,"shop_city":"Bielefeld","shop_street":"Arndtstra\u00dfe","shop_snumber":3,"shop_name":"M\u00fcller","shop_desc":"Kaufhaus"}]
Here is an example for a rest api request:
http://shoqproject.supervisionbielefeld.de/public/gateway/gateway/get-shops-by-city/city/Bielefeld
So when you have your rest api set up you can deal with receiving that data with your android phone. I use a static method to get this data:
public class JsonGrabber{
public static JSONArray receiveData(){
String url = "your url";
String result = "";
DefaultHttpClient client = new DefaultHttpClient();
HttpGet method = new HttpGet(url);
HttpResponse res = null;
try {
res = client.execute(method);
} catch (ClientProtocolException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
try{
InputStream is = res.getEntity().getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"));
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());
}
JSONArray jArray = null;
try{
jArray = new JSONArray(result);
}catch(JSONException e){
Log.e("log_tag", "Error parsing data "+e.toString());
}
return jArray;
}
}
Well thats all, once you have your data in json format you just have to parse it:
JSONArray test = (JSONArray) JsonGrabber.receiveData()
try {
for(int i=0;i<test.length();i++){
JSONObject json_data = test.getJSONObject(i);
int id = json_data.getInt("id");
}
}
The web request should run in another thread, because it can be a time consuming process. So you need to deal with AsyncTask. Here are some resources:
Painless Threading
Multithreading for performance
Hello Android Tutorial