App crashes if no data available in mysql database - php

my application crashes when Serialno and city is not available in database, sometimes it shows "No Data is Available", and some times it crashes, All i need is to display toast when ever Serial number and city is not present in database.
public String getvalues()
{
String uri = "http://www.lorryguru.com/retusno.php?city="+Citys+"&serialno="+SerialNo;
HttpGet httpGet = new HttpGet(uri);
HttpClient client = new DefaultHttpClient();
HttpResponse response;
StringBuilder stringBuilder = new StringBuilder();
try {
response = client.execute(httpGet);
HttpEntity entity = response.getEntity();
InputStream stream = entity.getContent();
int b;
while ((b = stream.read()) != -1)
{
stringBuilder.append((char) b);
}
}
catch (ClientProtocolException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
try
{
JSONArray arr = new JSONArray(stringBuilder.toString());
//result = jsonObj.getJSONArray(TAG_RESULT);
JSONObject c = arr.getJSONObject(0);
id = c.getString(TAG_ID);
district = c.getString(TAG_DISTRICT);
cit = c.getString(TAG_CITY);
serial_no = c.getString(TAG_SERIALNO);
gende = c.getString(TAG_GENDER);
wareno = c.getString(TAG_WARENO);
befor = c.getString(TAG_BEFORE);
afte = c.getString(TAG_AFTER);
latitude = c.getString(TAG_LATITUDE);
longitude = c.getString(TAG_LONGITUDE);
return "success";
}
catch (JSONException e)
{
return "No Data is Available";
//e.printStackTrace();
}
}
my php script is
<?php
require "init.php";
$serialno = $_REQUEST["serialno"];
$city = $_REQUEST["city"];
$sql = "SELECT * FROM dogs_details WHERE serial_no='".$serialno."' &&city='".$city."' ";
$res = $con->query($sql);
$result = array();
while($row = mysqli_fetch_array($res)){
if($row['after_dog']=="")
{
$afterimage="No Image";
}
else
{
$afterimage=$row['after_dog'];
}
array_push($result,
array('id'=>$row['id'],
'district'=>$row['district'],
'city'=>$row['city'],
'serialno'=>$row['serial_no'],
'gender'=>$row['gender'],
'wareno'=>$row['ware_no'],
'before'=>$row['before_dog'],
'after'=>$afterimage,
'latitude'=>$row['latitude'],
'longitude'=>$row['longitude']
));
}
echo json_encode($result);
mysqli_close($con);
?>
My postExecute is below
protected void onPostExecute(String s) {
InputMethodManager imm = (InputMethodManager) getSystemService(Activity.INPUT_METHOD_SERVICE);
imm.toggleSoftInput(InputMethodManager.HIDE_IMPLICIT_ONLY, 0);
dialog.hide();
Toast.makeText(getApplicationContext(), s, Toast.LENGTH_SHORT).show();
dis.setText("District " + district);
city.setText("City " + cit);
serialno.setText("Serial No. " + serial_no);
gender.setText("Gender " + gende);
Picasso.with(Serialno.this).load(befor).into(before);
if (afte.equals("No Image")) {
after.setImageDrawable(getResources().getDrawable(R.drawable.load));
} else {
Picasso.with(Serialno.this).load(afte).into(after);
}
// loction.setText("Latitude "+latitude+" "+"Longitude "+longitude);
Showing_Map();
}

Check nullity of all fields of JsonObject and then try to use them. For example:
try
{
JSONArray arr = new JSONArray(stringBuilder.toString());
//result = jsonObj.getJSONArray(TAG_RESULT);
JSONObject c = arr.getJSONObject(0);
if(c.isNull(TAG_ID)
id="";
else
id = c.getString(TAG_ID);
if(c.isNull(TAG_DISTRICT)
district="";
else
district = c.getString(TAG_DISTRICT);
..........................
...............................
return "success";
}
catch (JSONException e)
{
return "No Data is Available";
//e.printStackTrace();
}
And in onPostExecute show Toast:
protected void onPostExecute(String s) {
InputMethodManager imm = (InputMethodManager) getSystemService(Activity.INPUT_METHOD_SERVICE);
imm.toggleSoftInput(InputMethodManager.HIDE_IMPLICIT_ONLY, 0);
dialog.hide();
Toast.makeText(getApplicationContext(), s, Toast.LENGTH_SHORT).show();
dis.setText("District " + district);
//Toast when city is null
if(cit.equals(""))
Toast.makeText(getApplicationContext(), YOUR_MESSSAGE, Toast.LENGTH_SHORT).show();
//Toast when serail_no is null
if(serail_no .equals(""))
Toast.makeText(getApplicationContext(), YOUR_MESSSAGE, Toast.LENGTH_SHORT).show();
city.setText("City " + cit);
serialno.setText("Serial No. " + serial_no);
gender.setText("Gender " + gende);
Picasso.with(Serialno.this).load(befor).into(before);
if (afte.equals("No Image")) {
after.setImageDrawable(getResources().getDrawable(R.drawable.load));
} else {
Picasso.with(Serialno.this).load(afte).into(after);
}
// loction.setText("Latitude "+latitude+" "+"Longitude "+longitude);
Showing_Map();
}

Related

How to send array and variable from php to android app?

I need help.
Have seen similar questions but I cant still do it. So I post mine.
php codes runs well so far. Ijust dont know how to get the array.
How can I get the array from php and list it in my alertdialog like this:
soy sauce - $1
onion - $1
total= $2
Or is this possible or not? Or maybe please tell me what to add in here.
Thanks for your time in advance. Any form of help would be appreciated.
This are my codes:
public class updateData2 extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... params) {
ArrayList<NameValuePair> postVars = new ArrayList<>();
postVars.add(new BasicNameValuePair("JSON", String.valueOf(EverythingJSON)));
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://abcabc.com/buy_now.php");
try {
httppost.setEntity(new UrlEncodedFormEntity(postVars));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
try {
HttpResponse response = httpclient.execute(httppost);
String responseBody = EntityUtils.toString(response.getEntity());
} catch (ClientProtocolException e) {
e.printStackTrace();
Log.v("MAD", "Error sending... ");
} catch (IOException e) {
e.printStackTrace();
Log.v("MAD", "Error sending... ");
}
return null;
}
#Override
protected void onPostExecute(String result) {
Toast.makeText(Cart.this,EverythingJSON.toString(), Toast.LENGTH_LONG).show();
AlertDialog.Builder builder = new AlertDialog.Builder(Cart.this);
builder.setTitle("ORDER:");
builder.setMessage(EverythingJSON.toString());
builder.setPositiveButton("Confirm",
new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int id)
{
}
});
builder.show();
}
}
php
<?php
require "conn.php";
$total = 0;
// $ing = array("ampalaya", "soy sauce");
$JSON_Received = $_POST["JSON"];
$obj = json_decode($JSON_Received, true);
$products_name_array = array();
$products_price_array = array();
// foreach($ing as $value){
foreach($obj['ques'] as $value){
$sql="select MIN(product_price) , product_id , store_id , product_name,product_unit_of_measure , product_price ,product_stock from products where product_name like '%$value%'";
$result2 = mysqli_query($conn, $sql);
if(mysqli_num_rows($result2) > 0){
while($row = mysqli_fetch_assoc($result2)){
$product_id=$row['product_id'];
$store_id=$row['store_id'];
$product_name=$row['product_name']; $products_name_array[] = $product_name;
$product_unit_of_measure=$row['product_unit_of_measure'];
$product_price=$row['product_price']; $products_price_array[] = $product_price;
$total = $total+$product_price;
}}
}
foreach($products_name_array as $key => $value) {
echo $products_name_array[$key] . " - " . "$" . $products_price_array[$key] . ".00" ."<br>";
}
echo "</br>";
echo "</br>";
echo "TOTAL IS: ".$total. ".00";
?>
example:
getArray.php
<? echo json_encode($your_array);?>
and in android use for example retrofit library(http client)
interface phpApi{
#GET("url/getArray.php")
Call<YourObject> getArray();
}

POST string with keys and values in android to php

i want to send all contacts with contact name and number in one row in one array in my android application like
john => "+92312xxxxxxx" ,
Right now i'm using namevaluepairs to post two arrays but it's not working like :
public class ContactList extends Activity {
public TextView outputText;
String phoneNumber = null;
String names = null;
String[] keyValue;
String[] kes;
int Count;
String s = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_contact_list);
outputText = (TextView) findViewById(R.id.textView1);
fetchContacts();
//Http connection
InputStream is=null;
List<NameValuePair> nameValuePairs =new ArrayList<NameValuePair>(1);
for (int i = 0; i < Count ; i++)
{
nameValuePairs.add(new BasicNameValuePair("CN[]", keyValue[i]));
nameValuePairs.add(new BasicNameValuePair("names[]",kes[i]));
Log.i("Response", "you sent :" +kes[i]+" :"+ keyValue[i] + "\n ");
}
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://192.168.1.107/older/ContactList.php");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
}
catch(ClientProtocolException e)
{
Log.e("ClientProtocol","Log_tag");
e.printStackTrace();
System.out.println("Excep: "+e);
}
catch(IOException e)
{
Log.e("Log_tag","IOException");
e.printStackTrace();
}
String result = "";
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");
}
reader.close();
is.close();
result=sb.toString();
Log.i("Response", "result "+ result);
}
catch(Exception e)
{
Log.e("log_tag", "Error converting result "+e.toString());
}
//result = "[{\"0\":\"Muhaimin\",\"1\":\"3\",\"2\":\"o+\"}]";
try
{
JSONArray jArray = new JSONArray(result);
for (int i = 0; i < jArray.length(); i++)
{
s= s +";"+ jArray.getString(i) + "\n";
}
}
catch (Exception e)
{
Log.e("Response", "error fetching indexes" + e);
}
String[] friends= s.split(";");
StringBuffer output = new StringBuffer();
for (int i = 0; i < friends.length; i++)
{
Log.i("List","Your friends namee"+friends[i]);
output.append("\n Your friend's number"+ friends[i]);
}
}
//Fetch Contacts
public void fetchContacts() {
// String email = null;
Uri CONTENT_URI = ContactsContract.Contacts.CONTENT_URI;
String _ID = ContactsContract.Contacts._ID;
String DISPLAY_NAME = ContactsContract.Contacts.DISPLAY_NAME;
String HAS_PHONE_NUMBER = ContactsContract.Contacts.HAS_PHONE_NUMBER;
Uri PhoneCONTENT_URI = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
String Phone_CONTACT_ID = ContactsContract.CommonDataKinds.Phone.CONTACT_ID;
String NUMBER = ContactsContract.CommonDataKinds.Phone.NUMBER;
// Uri EmailCONTENT_URI = ContactsContract.CommonDataKinds.Email.CONTENT_URI;
//String EmailCONTACT_ID = ContactsContract.CommonDataKinds.Email.CONTACT_ID;
// String DATA = ContactsContract.CommonDataKinds.Email.DATA;
ContentResolver contentResolver = getContentResolver();
Cursor cursor = contentResolver.query(CONTENT_URI, null,null, null, null);
// Loop for every contact in the phone
Count = cursor.getCount();
if (cursor.getCount() > 0) {
keyValue= new String[Count];
kes= new String[Count];
while (cursor.moveToNext()) {
String contact_id = cursor.getString(cursor.getColumnIndex( _ID ));
String name = cursor.getString(cursor.getColumnIndex( DISPLAY_NAME ));
int hasPhoneNumber = Integer.parseInt(cursor.getString(cursor.getColumnIndex( HAS_PHONE_NUMBER )));
if (hasPhoneNumber > 0) {
// Query and loop for every phone number of the contact
Cursor phoneCursor = contentResolver.query(PhoneCONTENT_URI, null, Phone_CONTACT_ID + " = ?", new String[] { contact_id }, null);
while (phoneCursor.moveToNext())
{
int i=0;
String stu = phoneCursor.getString(phoneCursor.getColumnIndex(NUMBER));
phoneNumber +=":"+ stu;
names +=":" + name;
Log.i("List",stu + name +"\n" );
}
phoneCursor.close();
}
}
}
keyValue = phoneNumber.split(":");
kes = names.split(":");
Log.i("List","24th"+keyValue[23]);
Toast.makeText(getApplicationContext(), "99th "+keyValue[909] ,Toast.LENGTH_LONG).show();
}
PHP after receiving contacts will match them and return only those which have a match with database contacts. And then it returns contacts with names
i'm stuck with sending and receving part
Here is php code
<?php
define('DB_HOST', 'localhost');
define('DB_NAME', 'verification');
define('DB_USER','root');
define('DB_PASSWORD','');
// 1. Create a database connection
$connection = mysqli_connect(DB_HOST,DB_USER,DB_PASSWORD);
if (!$connection) {
die("Database connection failed: " . mysqli_error());
}
// 2. Select a database to use
$db_select = mysqli_select_db($connection, DB_NAME);
if (!$db_select) {
die("Database selection failed: " . mysqli_error());
}
$PhoneNum= $_POST["CN"];
$i=0;
$j=0;
$friends = array();
$Invite = array();
unset ($PhoneNum[0]);
foreach ($PhoneNum as $i=> $element){
//or do whatever you need to do to that variable
$query="SELECT Number FROM `user` WHERE Number=$element";
$query_exec = mysqli_query($connection ,$query);
if (!$query_exec)
{ echo mysql_error(); }
ELSE {
if(mysqli_num_rows($query_exec)>0)
{
$friends["$j"]= $PhoneNum[$i];
$j++;
}
else
{
;
}}
}
echo (json_encode($friends));
?>
You'll get a URL now that would look like:
www.example.com/yourscript?CN[]=keyValue1&names[]=key1&CN[]=keyValue2&names[]=key2 etc.. going on untill your whole list has looped.
I doubt that is what your PHP script wants to receive, you probably want to send the POST for each time you increment the loop. But thats just conjecture untill you post more information/code.
Instead send a JSON array as the value of the nameValuePair and convert it to a PHP array using json_decode function in the server side.

Delete row from MySQL table via android

I need to delete an item from a list view on android when clicked. The thing is, my table is not on the phone(SQLite), but on the server. So I'm using a PHP code for this.
I have set up an onClickListener.
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> a, View v,int position, long id) {
Show_Alert_box(v.getContext(),
"Please select action.", position);
}
});
public void Show_Alert_box(Context context, String message, int position) {
final int pos = position;
final AlertDialog alertDialog = new AlertDialog.Builder(context)
.create();
//alertDialog.setTitle(getString(R.string.app_name_for_alert_Dialog));
alertDialog.setButton("Delete", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
DBHandlerComments dbhelper = new DBHandlerComments(Comments.this);
SQLiteDatabase db = dbhelper.getWritableDatabase();
try{
JSONObject json2 = JSONParser.makeHttpRequest(urlDelete, "POST", params);
try {
int success = json2.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully updated
Intent i = getIntent();
// send result code 100 to notify about product update
setResult(100, i);
finish();
} else {
// failed to update product
}
} catch (JSONException e) {
e.printStackTrace();
}
//adapter.notifyDataSetChanged();
db.close();
}catch(Exception e){
}
}
});
alertDialog.setButton2("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
alertDialog.dismiss();
}
});
alertDialog.setMessage(message);
alertDialog.show();
}
This is my JSONParser's makehttprequest code:
public static JSONObject makeHttpRequest(String url, String method,
List<NameValuePair> params) {
// Making HTTP request
try {
// check for request method
if(method == "POST"){
// request method is POST
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}else if(method == "GET"){
// request method is GET
DefaultHttpClient httpClient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
//from here
while ((line = reader.readLine()) != null) {
if(!line.startsWith("<", 0)){
if(!line.startsWith("(", 0)){
sb.append(line + "\n");
}
}
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
`
And this is my PHP code:
$response = array();
if (isset($_POST['id'])) {
$id = $_POST['id'];
// include db connect class
$db = mysql_connect("localhost","tbl","password");
if (!$db) {
die('Could not connect to db: ' . mysql_error());
}
//Select the Database
mysql_select_db("shareity",$db);
// mysql update row with matched id
$result = mysql_query("DELETE FROM comments_activities WHERE id = $id");
// check if row deleted or not
if (mysql_affected_rows() > 0) {
// successfully updated
$response["success"] = 1;
$response["message"] = "Product successfully deleted";
// echoing JSON response
echo json_encode($response);
} else {
// no product found
$response["success"] = 0;
$response["message"] = "No product found";
// echo no users JSON
echo json_encode($response);
}
} else {
// required field is missing
$response["success"] = 0;
$response["message"] = "Required field(s) is missing";
// echoing JSON response
echo json_encode($response);
}
I'm adding the params like this:
params.add(new BasicNameValuePair(KEY_ID, id));
params.add(new BasicNameValuePair(KEY_AID, aid));
params.add(new BasicNameValuePair(KEY_ANAME, an));
params.add(new BasicNameValuePair(KEY_EVENT, ev));
params.add(new BasicNameValuePair(KEY_COMMENT, cb));
params.add(new BasicNameValuePair(KEY_USER, cby));
params.add(new BasicNameValuePair(KEY_TIME, cd));
I don't get any result. Can I know why?
I have noticed that you add unneeded parameters although you just need the id.
This is a simple code for deleting the given id, you can try it. If it worked, the error would be in your android code.
<?php
$servername = "your servername";
$username = "your username";
$password = "your password";
$dbname = "your dbname";
$link = mysql_connect($servername, $username, $password);
mysql_select_db($dbname, $link);
$id=$_POST['id'];
$result = mysql_query("DELETE FROM table_name WHERE id=$id", $link);
$response["success"] = 1;
$response["message"] = "Deleted successfully!";
echo json_encode($response);
?>
Change the servername to your database url and so on the other information.

passing spinner selected data from android to php

I need to read data from an external database with hundreds of items. so for i am trying to pass spinner selected value to php
android code is here:
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.icd);
states = getResources().getStringArray(R.array.Diseases);
t1 = (TextView) findViewById(R.id.textView1);
spinner = (Spinner) findViewById(R.id.country_spinner);
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, states);
dataAdapter
.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(dataAdapter);
spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view,
int position, long id) {
ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
value = spinner.getSelectedItem().toString();
// define the parameter
postParameters.add(new BasicNameValuePair("789", value));
try {
CustomHttpClient.executeHttpGet("789");
} catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
String response = null;
// call executeHttpPost method passing necessary parameters
try {
response = CustomHttpClient.executeHttpPost(
urlheart,
// in case of remote server
// "http://omega.uta.edu/~kmr2464/jsonscript.php",
postParameters);
// store the result returned by PHP script that runs
// MySQL query
String result = response.toString();
// parse json data
try {
returnString = "";
JSONArray jArray = new JSONArray(result);
for (int i = 0; i < jArray.length(); i++) {
JSONObject json_data = jArray.getJSONObject(i);
Log.i("log_tag", "id: " + json_data.getInt("id")
+ ", name: " + json_data.getString("name")
);
returnString += "\n" + "Name ="
+ json_data.getString("icd_disease") + "\n"
+ " Symptoms = "
+ json_data.getInt("icd_symptoms") + "\n"
+ " "
+ json_data.getString("icd_treatment");
}
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
}
try {
t1.setText(returnString);
} catch (Exception e) {
Log.e("log_tag", "Error in Display!" + e.toString());
;
}
} catch (Exception e) {
Log.e("log_tag",
"Error in http connection!!" + e.toString());
}
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
}
php:
if(isset($_POST['789'])){
$id = $_POST['789'];
$sql = "SELECT * FROM icd WHERE icd_disease = 'id'";
$result = mysql_query($sql);
while($row=mysql_fetch_assoc($result))
$output[]=$row;
print(json_encode($output));
mysql_close();
My question is how can I pass the data from spinner android to php query so the query will only return the proper items only aginst selected item
Try this:
if(isset($_POST['789'])){
$id = $_POST['789'];
$sql = "SELECT * FROM icd WHERE icd_disease = '$id'";
$result = mysql_query($sql);
while($row=mysql_fetch_assoc($result))
$output[]=$row;
print(json_encode($output));
mysql_close();

Send parameter to server from android application

I have an android application that requests data from my mysql database. This works fine but when I try to send a parameter for how many items to retrieve I get nothing.
This is my java code:
result = "";
client = new DefaultHttpClient();
post = new HttpPost("http://www.XXX.XXXX.XX/XX.php");
nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("itemsToGet", itemsToGet));
try {
post.setEntity((new UrlEncodedFormEntity(nameValuePairs)));
response = client.execute(post);
entity = response.getEntity();
inputStream = entity.getContent();
} catch (UnsupportedEncodingException e) {
Log.e(TAG, e.toString());
} catch (ClientProtocolException e) {
Log.e(TAG, e.toString());
} catch (IOException e) {
Log.e(TAG, e.toString());
}
try {
bufferedReader = new BufferedReader(new InputStreamReader(inputStream ,"iso-8859-1"), 8);
stringBuilder = new StringBuilder();
String line = null;
while((line = bufferedReader.readLine()) != null) {
stringBuilder.append(line + "\n");
}
inputStream.close();
result = stringBuilder.toString();
} catch (UnsupportedEncodingException e) {
Log.e(TAG, e.toString());
} catch (IOException e) {
Log.e(TAG, e.toString());
}
try {
JSONArray jsonArray = new JSONArray(result);
for(int i = 0; i < jsonArray.length(); i++) {
JSONObject object = jsonArray.getJSONObject(i);
Log.i(TAG, object.getString("namn") + " " + i);
}
} catch (JSONException e) {
Log.e(TAG, e.toString());
}
And this is my server side PHP code:
<?php
mysql_connect("XXX.XXX.com", "XXX", "XXX") or die(mysql_error());
mysql_select_db("XXXXXXX") or die(mysql_error());
$data = mysql_query("SELECT * FROM artikel") or die(mysql_error());
$itemsToGet = intval($_POST['itemsToGet']);
$counter = 0;
while($info = mysql_fetch_array( $data ) && $counter < $itemsToGet)
{
$databaseInfo[] = $info;
$counter++;
}
print(json_encode($databaseInfo));
?>
I solved it. The condition in the while-loop was incorrect.
while($info = mysql_fetch_array( $data ) && $counter < $itemsToGet)
It should be
while(($info = mysql_fetch_array( $data )) && ($counter < $itemsToGet))

Categories