I'm very new to Android and I'm currently making an application wherein the user can enter and ID number once (that serves as a login) and he can use access the rest of the features of the app.
I'm currently stuck in the displaying of a data from the MySQL server. Using the ID that the user entered (which is unique and only the user's identificaton), I can display the information with of the user (through TextView or something).
This is my code so far:
public class MainActivity3Activity extends Activity {
HttpPost httppost;
StringBuffer buffer;
HttpResponse response;
HttpClient httpclient;
List<NameValuePair> nameValuePairs;
ProgressDialog dialog = null;
TextView tv;
TextView tv2;
String get;
private WebView webView;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_activity3);
tv = (TextView)findViewById(R.id.tv);
tv2 = (TextView)findViewById(R.id.tv2);
webView = (WebView) findViewById(R.id.webView);
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl("http://usamobileapp.pe.hu/webservice/student_info.php");
SharedPreferences preferences = getSharedPreferences("rfid", Context.MODE_PRIVATE);
if(preferences.contains("rfid")){
get = preferences.getString("rfid", null);
}
}
So my question what do I do from here? I'm quite familiar about httpost but I'm wondering how do I display the user information using the previously entered ID during the login? I heard things like JSON parsing but I'm not quite sure on how to use it.
How do I get to display the information of the user matching the ID he entered? How to diplay using a TextView?
Thanks for the help.
PS. Please disregard the webview there. I only used it as a sample if my app really us connected to my php.
1) make a restful API on your server
2) receive API elements on your client (android), i suggest retrofit, its too easy
3) display your data! otto will help :)
want more? more ,
it might seem hard, but if you study for a few days you'll learn it.
To implement a login / registration system using MySql you need a server-side API, for example in PHP to manipulate the database.
You need something like that on the server side:
// check for tag type
if ($tag == 'login') {
// Request type is check Login
$email = $_POST['email'];
$password = $_POST['password'];
// check for user
$user = $db->getUserByEmailAndPassword($email, $password);
if ($user != false) {
// user found
$response["error"] = FALSE;
$response["uid"] = $user["unique_id"];
$response["user"]["name"] = $user["name"];
$response["user"]["email"] = $user["email"];
$response["user"]["created_at"] = $user["created_at"];
$response["user"]["updated_at"] = $user["updated_at"];
echo json_encode($response);
} else {
// user not found
// echo json with error = 1
$response["error"] = TRUE;
$response["error_msg"] = "Incorrect email or password!";
echo json_encode($response);
}
And the function that queries the database:
public function getUserByEmailAndPassword($username, $password) {
$query = $this->dbh->prepare("SELECT * FROM users2 WHERE username = :username");
$query->bindParam(':username', $username);
$result = $query->execute();
// check for results
if ($query->rowCount() > 0) {
$result = $query->fetch(PDO::FETCH_ASSOC);
$salt = $result['salt'];
$encrypted_password = $result['encrypted_password'];
$hash = $this->checkhashSSHA($salt, $password);
// check for password equality
if ($encrypted_password == $hash) {
// user authentication details are correct
return $result;
}
} else {
// user not found
return false;
}
}
The android 'calls' the php scripts:
private static String login_tag = "login";
public void loginUser(String username, String password) throws ExecutionException, InterruptedException {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("tag", login_tag));
params.add(new BasicNameValuePair("username", username));
params.add(new BasicNameValuePair("password", password));
jsonParser = new DbHandler(activity, this, params).execute();
}
And here is the DbHandler:
public DbHandler1(Activity activity, MyCallback dbIntf, List<NameValuePair> params) {
this.activity = activity;
intf = dbIntf;
this.params = params;
}
public JSONObject makeHttpRequest() {
// Making HTTP request
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(MainActivity.baseUrl);
//If database contains greek characters instantiate with UTF-8 Encoding
httpPost.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (HttpHostConnectException e) {
new Handler(Looper.getMainLooper()).post(new Runnable() {
#Override
public void run() {
Toast.makeText(activity, R.string.connection_error, Toast.LENGTH_LONG).show();
}
});
} catch (IOException e) {
e.printStackTrace();
}
try {
//If database contains greek characters instantiate with UTF-8 Encoding
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
#Override
protected JSONObject doInBackground(Void... params) {
jObj = makeHttpRequest();
return jObj;
}
#Override
protected void onPostExecute(JSONObject jsonObject) {
super.onPostExecute(jsonObject);
try {
intf.onRemoteCallComplete(jsonObject);
} catch (JSONException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
So the php scripts 'catches' the tag and if the user exists it returns a JSON response to the device. For example:
{
"tag": "login",
"success": 1,
"error": 0,
}
The data transfered from the MySql server must be JSON encoded.
On the android device you must read the JSON Response and act accordingly.
Take a look here for more details.
login / registration system
json parsing
you need perform network operations on a separate thread from the UI.
reade aboute rest Google I/O 2010 - Developing Android REST client application
documentation
in the client, for rest api i like use retrofit + gsongroundy
or php, very easy create rest api using slim framework ─ How to create REST API for Android app using PHP, Slim and MySQL
Related
I have found lots of responses about it but all of them are written with deprecated functions or don't work in my case.
I need to get the IMEI number (unic ID of a device) of the mobile device where my app will be installed, and then to send that value (in form of a string) to a php file located in a folder I created in my website (because the app has a webview where I visualize that website and I want to save the IMEI into a data base).
So far, I got this in my code:
public void postData() {
// Create a new HttpClient and Post Header
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.chapatelo.hol.es/php/postIMEI.php");
TelephonyManager telephonyManager = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("IMEI", telephonyManager.getDeviceId()));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
}
and I have <uses-permission android:name="android.permission.INTERNET"/> and also <uses-permission android:name="android.permission.READ_PHONE_STATE"/> in the manifest.
And this is the php file:
<?php
require_once("conexion.php");
if(!isset($_SESSION)){
session_start();
}
$imei = $_POST["IMEI"];
$query1 = "SELECT * FROM usuarios WHERE imei = '$imei'";
if($resp1 = mysqli_query($conexion, $query1)){
if(mysqli_num_rows($resp1) == 0){
$query2 = "INSERT INTO usuarios (imei) VALUES ('$imei')";
if(mysqli_query($conexion, $query2)){
$_SESSION["imei"] = $imei;
echo true;
}else{
echo "error de conexión";
}
}else{
echo "Ya existe el imei en la db";
}
}else{
echo "error de conexión";
}
mysqli_close($conexion);
?>
However, and not mentioning that almost every function such as httpclient is deprecated, nothing of that works.
I gave permitions 755 (read and execute) to the php folder and to the file I access through my app, but nothing happens...
Is there any "new version" of those functions I'm using to get the imei and then send it to the php file?
Is because of the deprecated functions that my app doesn't save the imei in the data base?
You can refer this, might help you
java
public void executeHttpGet() throws Exception {
BufferedReader in = null;
try {
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet();
request.setURI(new URI("http://testsite.com/" +
"imei_script.php?imei=" + telManager.getDeviceId()
));
HttpResponse response = client.execute(request);
in = new BufferedReader
(new InputStreamReader(response.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String line = "";
String NL = System.getProperty("line.separator");
while ((line = in.readLine()) != null) {
sb.append(line + NL);
}
in.close();
String page = sb.toString();
System.out.println(page);
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
php
<?php
// to return plain text
header("Content-Type: plain/text");
$imei = $_GET["imei"];
$file=fopen("imei.txt","r") or exit("Unable to open file!");
while(!feof($file))
{
if ($imei==chop(fgets($file)))
echo "True";
}
fclose($file);
?>
I am creating my first android which will take data from a signup form and send it to a php backend.
The php backend will take the data and save in a database and give a jason encoded message telling if it is success or not.
Now I want to eliminate the possibility of dupilicate usernames so when the android app sends data to the php backend I will first check and if it is duplicate I will throw an error message like this
$response["error"] = true;
$response["message"] = "Username Already taken";
echoRespnse(400,$response);
On Success the backend will send something like this
$response["error"] = false;
$response["message"] = "Successfuly Registered";
echoRespnse(201,$response);
How do I enable the android app to read this info and understand if the user was created or an error occured.
My current Android signup.java code looks like this
public void post() throws UnsupportedEncodingException
{
// Get user defined values
uname = username.getText().toString();
email = mail.getText().toString();
password = pass.getText().toString();
confirmpass = cpass.getText().toString();
phone = phn.getText().toString();
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.rgbpallete.in/led/api/signup");
if (password.equals(confirmpass)) {
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(4);
nameValuePairs.add(new BasicNameValuePair("uname", uname));
nameValuePairs.add(new BasicNameValuePair("pass", password));
nameValuePairs.add(new BasicNameValuePair("email", email));
nameValuePairs.add(new BasicNameValuePair("phone", phone));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
httpclient.execute(httppost);
//Code to check if user was successfully created
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
else
{
Toast.makeText(getBaseContext(), "Password mismatch", Toast.LENGTH_SHORT).show();
//Reset password fields
pass.setText("");
cpass.setText("");
}
}
I think you want help to get and read the JSON data provided by your service, right?
In your SignUp Activity create an AsyncTask because you can not perform this on the main thread.
private class DownloadOperation extends AsyncTask<Void, Void, String> {
String uname = "";
String email = "";
String password = "";
String confirmpass = "";
String phone = "";
#Override
protected void onPreExecute() {
super.onPreExecute();
// Get user defined values
uname = username.getText().toString();
email = mail.getText().toString();
password = pass.getText().toString();
confirmpass = cpass.getText().toString();
phone = phn.getText().toString();
}
#Override
protected String doInBackground(Void... params) {
String response = "";
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.rgbpallete.in/led/api/signup");
HttpEntity httpEntity = null;
HttpResponse httpResponse = null;
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(4);
nameValuePairs.add(new BasicNameValuePair("uname", uname));
nameValuePairs.add(new BasicNameValuePair("pass", password));
nameValuePairs.add(new BasicNameValuePair("email", email));
nameValuePairs.add(new BasicNameValuePair("phone", phone));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
httpclient.execute(httppost);
httpResponse = httpClient.execute(httpPost);
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
httpEntity = httpResponse.getEntity();
response = EntityUtils.toString(httpEntity);
return response;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
Log.d("tag", "Result:\n" + result);
}}
And then call
// Calling async task to get json
new DownloadOperation().execute();
And you will see the json string printed on your Console :)
To get an JSONObject using the response String:
JSONObject jsonObj = new JSONObject(STRING);
Hope that helps.
You could make your "error" an int instead of a boolean, and have your php backend return specific error codes. This would allow your android application to understand the specific error. Without this kind of modification, checking the value of message for a specific string is another option.
For example, you could return 0 if there was no error, 1 if the username was already taken, 2 if .. etc.
BEFORE registering the user and inserting into database ,check the query for username in database..and if user name found then encode json value as error
$query=mysql_query("select id from yourtable where username ='$username'");
If(mysql_numnum_rows($query)>0)
// example for response
//responses from server for success
response["success"]=1;
response["message"]='No error code'
//responses from server for duplicate username
response["success"]==0
response["message"]='Username exists';
// java code
// after getting string from server parse in into json object
JSONObject jsonObj = new JSONObject(STRING);
int success = jsonObj.getInt("success");
message = jsonObj.getString("message");
if (success == 1) {
// register successfully
} else {
// username already exist
}
I'm make app in android accept the user name in Arabic Language and store in mysql database on the server but the name when send from app to database , it's stored as ???? .
I'm using the charset in database as UTF-8 and all process on the control panel on web is ok m but from app to database it isn't ok
the asyntask for store information from app to db is :
class InsertInfo extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
namest=name.getText().toString();
//emailst=email.getText().toString();
mobilest=mobile.getText().toString();
imgst=image_name;
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("id", evid+""));
params.add(new BasicNameValuePair("name",namest));
// params.add(new BasicNameValuePair("email", emailst));
params.add(new BasicNameValuePair("mobile", mobilest));
params.add(new BasicNameValuePair("imgurl", imgst));
/* JSONObject json = jsonParser.makeHttpRequest(urlinsert,
"POST", params);*/
try
{
HttpClient httpclient = new DefaultHttpClient();
//HttpParams pa = new BasicHttpParams();
//HttpProtocolParams.setContentCharset(pa, "utf-8");
HttpPost httppost = new HttpPost(urlinsert);
// httppost.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
httppost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
Log.e("pass 1", "connection success ");
}
catch(Exception e)
{
Log.e("Fail 1", e.getMessage());
Toast.makeText(getApplicationContext(), "Invalid IP Address",
Toast.LENGTH_LONG).show();
}
try
{
BufferedReader reader = new BufferedReader
(new InputStreamReader(is,"UTF-8"),8192);
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
is.close();
result = sb.toString();
Log.e("pass 2", "connection success ");
}
catch(Exception e)
{
Log.e("Fail 2", e.toString());
}
try
{
JSONObject json_data = new JSONObject(result);
code=(json_data.getInt("code"));
if(code==1)
{
Toast.makeText(getBaseContext(), "Inserted Successfully",
Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(getBaseContext(), "Sorry, Try Again",
Toast.LENGTH_LONG).show();
}
}
catch(Exception e)
{
Log.e("Fail 3", e.toString());
}
return null;
}
protected void onPostExecute(String file_url) {
// dismiss the dialog once product uupdated
}
}
I'm trying a lot of methods and at each all i'm using UTF-8 but it's not work as proper manner , can you help me in this case please :(
If you did not start utf-8 at the beginning stage then you'll possibly have to go all the way down the line from the server -> connection -> database -> table -> query
MySQL charset: UTF-8 Unicode (utf8)
MySQL connection collation: utf8_general_ci
your database and table collations are set to: utf8_general_ci or utf8_unicode_ci
PHP code:
mysql_query("SET NAMES 'utf8'");
mysql_query('SET CHARACTER SET utf8');
Update:
Did you also uncomment the protocol line in your code?
//HttpParams pa = new BasicHttpParams();
//HttpProtocolParams.setContentCharset(pa, "utf-8");
Command for creating database to accept all types of language and fonts.
create schema databaseName default charset utf8 collate utf8_bin;
I've created basic android apps in various programming classes that I have taken before using Eclipse and the Java Android SDK.
The app that I'd like to create would require users to enter information that would later be analyzed. I want people to be able to compare this data with other people's data so I'd like every entry that users make to be submitted to a database to later be queried when a person attempts to compare their data.
I'd like direction for how to accomplish this. Should I find a free hosting site and set up a Sql server or is there a better way to accomplish this?
Edit: Just for fun.
I am a very beginner android developer, and I have found that using cloud-stored online database like mongolab.com is very friendly for user submitted data. The communication between database and server will have to be done through JSON parsing and URI requests.
Here is example of code you can bind to a button that will send object stored in field tempData:
public void send(View view) {
String apiURI = "https://api.mongolab.com/api/1/databases/MYDATABASE/collections/USERSUBMITTEDDATA?apiKey="
+ apiKey;
try {
// make web service connection
final HttpPost request = new HttpPost(apiURI);
request.setHeader("Accept", "application/json");
request.setHeader("Content-type", "application/json");
// Build JSON string with GSON library
Gson gson = new Gson();
JsonElement jsonElement = gson.toJsonTree(tempData);
String json = gson.toJson(jsonElement);
StringEntity entity = new StringEntity(json);
Log.d("****Parameter Input****", "Testing:" + json);
request.setEntity(entity);
// Send request to WCF service
final DefaultHttpClient httpClient = new DefaultHttpClient();
new AsyncTask<Void, Void, Void>() {
#Override
public Void doInBackground(Void... arg) {
try {
HttpResponse response = httpClient.execute(request);
Log.d("WebInvoke", "Saving: "
+ response.getStatusLine().toString());
// Get the status of web service
BufferedReader rd = new BufferedReader(
new InputStreamReader(response.getEntity()
.getContent()));
// print status in log
String line = "";
while ((line = rd.readLine()) != null) {
Log.d("****Status Line***", "Webservice: " + line);
}
} catch (Exception e) {
Log.e("SendMail", e.getMessage(), e);
}
return null;
}
}.execute();
} catch (Exception e) {
e.printStackTrace();
}
}
And here is an example of code used to retrieve elements in the database:
public void load() {
String apiURI = "https://api.mongolab.com/api/1/databases/MYDATABASE/collections/USERSUBMITTEDDATA"
+ "?apiKey=" + apiKey;
Log.d("****Status Line***", "" + apiURI);
try {
// make web service connection
final StringBuilder builder = new StringBuilder();
final HttpGet request = new HttpGet(apiURI);
request.setHeader("Accept", "application/json");
request.setHeader("Content-type", "application/json");
final DefaultHttpClient httpClient = new DefaultHttpClient();
new AsyncTask<Void, Void, String>() {
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
doSomethingWithReceivedData(result); //THIS METHOD IS DEFINED IN BODY OF YOUR ACTIVITY
}
#Override
public String doInBackground(Void... arg) {
try {
HttpResponse response = httpClient.execute(request);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) {
HttpEntity entity = response.getEntity();
InputStream content = entity.getContent();
BufferedReader reader = new BufferedReader(
new InputStreamReader(content));
String line;
while ((line = reader.readLine()) != null) {
builder.append(line);
}
Log.d("****Status Line***", "Success");
return builder.toString();
} else {
Log.d("****Status Line***",
"Failed to download file");
}
} catch (Exception e) {
Log.e("SendMail", e.getMessage(), e);
}
return null;
}
}.execute();
} catch (Exception e) {
e.printStackTrace();
}
}
You should have a data base to store the data. Like mentioned above, the data base is good to be in MySQL (SQL). Your application should have a method that can POST the results to the server, where the server will read the string send and retrieve and store the data.
A good start is to read about JSON
and read also about Asynctask
Also you need to know how to build your sever part. A good idea is to start with PHP, but I am not an expert on that field.
I hope this helps you start your project.
Simple, no DB required.
Usergrid by Apigee is exactly what you are looking for!
You can store each user's details
Retrieve stored data
Send events and receive event callbacks across devices
Best of all - no server side code. Only APIs
FYI This is the direction you should be heading even if you know how to code a server.
PS: I don't work for apigee or usergrid.
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.