I am trying to return multiple rows from my database. I have two coordinates that I want to retrieve that are stored in my database, namely Longitude and Latitude. As my asynctask currently only can return a row. How should I change my code so it is able to return multiple rows from the database?
Thanks for the help in advance.
Below are my codes:
php codes
$user=$_POST["username"];
$query = "SELECT longitude,latitude FROM friends INNER JOIN coordinates ON friends.username = coordinates.username WHERE friends.friend_of='$user'";
$sql=mysqli_query($conn, $query);
if (!$sql) {
echo 'Could not run query: ' . mysql_error();
exit;
}
while($row = mysqli_fetch_array($sql)>0){
$response["longitude"] = $row[0];
$response["latitude"] = $row[1];
die(json_encode($response));
}
Asynctask class.
class Findfriends extends AsyncTask<String, String, JSONObject> {
protected JSONObject doInBackground(String... args) {
// TODO Auto-generated method stub
// here Check for success tag
try {
HashMap<String, String> params = new HashMap<>();
params.put("username", args[0]);
JSONObject json = jsonParser.makeHttpRequest(
GET_FRIENDS, "POST", params);
if (json != null) {
Log.d("JSON result", json.toString());
return json;
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(JSONObject json) {
if (json != null) {
Toast.makeText(Borrower_AP.this, json.toString(),
Toast.LENGTH_LONG).show();
try {
Longitude = json.getDouble("longitude");
Latitude = json.getDouble("latitude");
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
I think you have to mistakes here, the first one is that your PHP code is Just returning one row, instead you have to use something like this:
$user=$_POST["username"];
$query = "SELECT longitude,latitude FROM friends INNER JOIN coordinates ON friends.username = coordinates.username WHERE friends.friend_of='$user'";
$sql=mysqli_query($conn, $query);
if (!$sql) {
echo 'Could not run query: ' . mysql_error();
exit;
}
$rows = array();
while($r = mysqli_fetch_assoc($sql)) {
$rows[] = $r;
}
print json_encode($rows);
On the other hand in your Android code, and if you are using Google Maps Api, you can return an ArrayList, something like this:
class Findfriends extends AsyncTask<String, String, ArrayList<LatLong> {
protected ArrayList<LatLong> doInBackground(String... args) {
// TODO Auto-generated method stub
// here Check for success tag
ArrayList<LatLong> geoPos=new ArrayList<LatLong>();
try {
HashMap<String, String> params = new HashMap<>();
params.put("username", args[0]);
JSONObject json = jsonParser.makeHttpRequest(
GET_FRIENDS, "POST", params);
if (json != null) {
Log.d("JSON result", json.toString());
//Complete here the code in which you iterate over the json and add each point to your ArrayList<LatLong>
}
} catch (Exception e) {
e.printStackTrace();
}
return geoPos;
}
}
Kindly change the php script like this,
$query = "SELECT longitude,latitude FROM friends INNER JOIN coordinates ON friends.username = coordinates.username WHERE friends.friend_of='$user'";
$sql=mysqli_query($conn, $query);
if(mysqli_num_rows($sql)>0)
{
while($row = mysqli_fetch_array($sql)
{
$latlongArray =array();
$latlongArray ["longitude"] = $row[0];
$latlongArray ["latitude"] = $row[1];
array_push($response["DATA"],$latlongArray)
}
$response["success"] = "1";
echo json_encode($response);
}
else
{
$response["success"] = "0";
echo json_encode($response);
}
And in android code, in Post execute paste this code, in logcat you will see the lat / longs from the database.
JSONArray ja = json.getJSONArray("DATA");
for (int r = 0; r < ja.length(); r++) {
JSONObject obj = ja.getJSONObject(r);
Log.i("Lat / Long",obj.getString("latitude")+" , "+obj.getString("longitude"));
}
Try this it may help you.. And it is working code.
Thank you,
Create your own handler like this:
//import android.os.Handler; this import is required.
public class MyHandler extends Handler{
public void handleMessage(Message msg) {
super.handleMessage(msg);
List<YourObject> objs=(List<YourObject>)msg.obj;
}
}
In your activity create async object as follows:
MyDataFetcher mdf=new MyDataFetcher(new MyHandler());
Write your Async like this:
class MyDataFetcher extends AsyncTask<String, String, JSONObject> {
private Handler handler
public MyDataFetcher(Handler handler){
this.handler=handler;
}
//here is code you need to write in onPost
protected void onPostExecute(JSONObject json) {
if (json != null) {
Toast.makeText(Borrower_AP.this, json.toString(),
Toast.LENGTH_LONG).show();
try {
List<YourObject> objs=new ArrayList<>();
// populate your info from json into objs
//------your code here for above logic
//Now create new Message
Message msg=new Message();
msg.obj=objs;
handler.handleMessage(msg);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
Related
I am developing an Application of JSON object Which Returns data into ListView.
if json have data then show data in listview..if dont have date then application is crashes.my application is crashes when json is empty.how to resolve this problem..thanx in advancce
here is android code..
public class EmployeePaymentHistory extends Fragment {
HttpParse httpParse = new HttpParse();
ProgressDialog pDialog;
ListView CategoryListView;
ProgressBar progressBar;
List<String> IdList = new ArrayList<>();
private String TAG = EmployeePaymentHistory.class.getSimpleName();
// Http Url For Filter Student Data from Id Sent from previous activity.
String finalResult ;
HashMap<String,String> hashMap = new HashMap<>();
String ParseResult ;
HashMap<String,String> ResultHash = new HashMap<>();
String FinalJSonObject ;
String TempItem;
ProgressDialog progressDialog2;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.activity_employee_payment, container, false);
CategoryListView = (ListView)view.findViewById(R.id.listview1);
progressBar = (ProgressBar)view.findViewById(R.id.progressBar);
//Receiving the ListView Clicked item value send by previous activity.
TempItem = getActivity().getIntent().getExtras().getString("ListViewValue1");
//Calling method to filter Student Record and open selected record.
HttpWebCall(TempItem);
// Add Click listener on Delete button.
return view;
}
// Method to Delete Student Record
//Method to show current record Current Selected Record
public void HttpWebCall(final String PreviousListViewClickedItem){
class HttpWebCallFunction extends AsyncTask<String,Void,String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = ProgressDialog.show(getActivity(),"Loading Data",null,true,true);
}
#Override
protected void onPostExecute(String httpResponseMsg) {
super.onPostExecute(httpResponseMsg);
pDialog.dismiss();
//Storing Complete JSon Object into String Variable.
FinalJSonObject = httpResponseMsg ;
//Parsing the Stored JSOn String to GetHttpResponse Method.
new EmployeePaymentHistory.GetHttpResponse(getActivity()).execute();
}
#Override
protected String doInBackground(String... params) {
ResultHash.put("CustomerID",params[0]);
ParseResult = httpParse.postRequest(ResultHash, api.EmployeePayment);
return ParseResult;
}
}
HttpWebCallFunction httpWebCallFunction = new HttpWebCallFunction();
httpWebCallFunction.execute(PreviousListViewClickedItem);
}
// Parsing Complete JSON Object.
private class GetHttpResponse extends AsyncTask<Void, Void, Void>
{
public Context context;
List<Customer> CategoryList;
public GetHttpResponse(Context context)
{
this.context = context;
}
#Override
protected void onPreExecute()
{
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... arg0)
{
try
{
if(FinalJSonObject != null)
{
JSONArray jsonArray = null;
try {
jsonArray = new JSONArray(FinalJSonObject);
JSONObject jsonObject;
Customer category;
CategoryList = new ArrayList<Customer>();
for(int i=0; i<jsonArray.length(); i++)
{
category = new Customer();
jsonObject = jsonArray.getJSONObject(i);
category.CustomerName = jsonObject.getString("date").toString();
category.Customertotal = jsonObject.getString("account").toString();
category.CustomerPaid = jsonObject.getString("total").toString();
category.CustomerUnPaid = jsonObject.getString("status").toString();
CategoryList.add(category);
}
}
catch (JSONException e) {
e.printStackTrace();
}
}
else
{
Toast.makeText(context, "abcc", Toast.LENGTH_SHORT).show();
}
}
catch (Exception e)
{
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result)
{
progressBar.setVisibility(View.GONE);
CategoryListView.setVisibility(View.VISIBLE);
CustomerListAdapterClass adapter = new CustomerListAdapterClass(CategoryList, context);
CategoryListView.setAdapter(adapter);
}
}
}
here is php Api code:
<?php
if($_SERVER['REQUEST_METHOD']=='POST'){
include 'DatabaseConfig.php';
$CustomerID= $_POST['CustomerID'];
// Create connection
$conn = new mysqli($HostName, $HostUser, $HostPass, $DatabaseName);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "sELECT b.payerid,a.account as account,b.date as date,b.status as status,b.type as type,sum(b.amount) as total FROM crm_employees a left JOIN sys_transactions b ON a.id = b.payerid where payerid= '$CustomerID' group by b.date ORDER BY a.id desc" ;
$result = $conn->query($sql);
if ($result->num_rows >0) {
while($row[] = $result->fetch_assoc()) {
$tem = $row;
$json = json_encode($tem);
}
} else {
echo "No Results Found.";
}
echo $json;
$conn->close();
}
?>
You need to give the response output same as you are parsing in android side. If you are trying to find a Json object of key name which is not in response then it will crash.
In this scenario you need to handle manually, the values you think it will be null or empty then handle using normal if statements.
Suppose jsonObject.getString("date") object is not fount then using if statements you can handle.
if(jsonObject.getString("date") != null){
//code here
}
I was tried to get data from MySQL PHP to Android with JSON Object but not work with me. I was searching about my problem but the examples I found didn't help me.
I have an array list of strings, then I set the strings MySQL DB.
After that, I want to get the cities strings from the DB with JSON, but I was unsuccessful.
My questions are:
How can I make sure that if I have city, it won't appear again?
How can I set the cities in an array list in Android?
My PHP code:
<?php
include 'connection/connection.php';
$noResult = "no results";
// to set the names at the list view
$sql = "SELECT workrCity FROM workersTable ";
$result = $connect->query($sql);
if ($result->num_rows > 0){
while($row[] = $result->fetch_assoc()) {
$json = json_encode($row,JSON_UNESCAPED_UNICODE);
}
} else {
echo $noResult;
}
echo $json;
$connect->close();
?>
the array list function in my Fragment working good :
private ArrayList<City> initCities() {
Log.d(TAG, "ArrayList_CitiesFragment_initCities");
String[] cityName = {"","","",""}; // the cities names
ArrayList<City> theCities = new ArrayList<>();
for (String aCityName : cityName) {
City city = new City(aCityName, false);
theCities.add(city);
}
return theCities;
}
Now I want to get the cities names from MySQL in a JSON-like output:
handler = new Handler(Looper.getMainLooper());
Thread runner = new Thread(new Runnable() {
#Override
public void run() {
Log.d(TAG, " runner");
GetCitiesJson getCitiesJson = new GetCitiesJson();
try{
String[] res = getCitiesJson.getCitiesDataFromDB();
JSONObject jsonObject = new JSONObject(String.valueOf(res));
JSONObject workrCity = jsonObject.getJSONObject("workrCity");
Activity activity = getActivity();
Toast.makeText(activity,"its :" + workrCity, Toast.LENGTH_SHORT).show();
} catch (IOException | JSONException e) {
e.printStackTrace();
}
}
});
runner.start();
I know that my code is not correct, but I don't know what's missing...
Hi: Im using Volley library to get a Json file from my server and works fine and fast.
In app/build.gradle under dependencies:
compile 'com.android.volley:volley:1.0.0'
Then, in the activity you want to get the json data:
String from = "http://www.yourserver.com/file.json";
StringRequest request = new StringRequest(from, new Response.Listener<String>() {
#Override
public void onResponse(String string) {
try {
parseJson(URLDecoder.decode(URLEncoder.encode(string, "iso8859-1"),"UTF-8"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError volleyError) {
// Error
Log.d("ERROR:", String.valueOf(volleyError));
}
});
Volley.newRequestQueue(this).add(request);
Then you can parse the Json:
public static void parseJson(String jsonString) {
try {
JSONObject object = new JSONObject(jsonString);
getMessage(this, object);
} catch (JSONException e) {
e.printStackTrace();
}
}
And finally you can get the strings inside your Json:
public static void getMessage(JSONObject object){
if(object.length() != 0) {
try {
message = String.valueOf(object.get("message"));
} catch (JSONException e) {
e.printStackTrace();
}
} }
Okay i was copy the code. but have one problem.that the message = String.valueOf(object.get("message")); where is the var named message? it's on red colo
message is a String:String message; Then in your Json, you need a node called message to get it.
How i Receive this data into to Model class i want to make a model class like getter setter andi use data from getter setter.
I want to make Model class
Basically i store it into variables not in separate class so i want to make model class
> Here is my code
class JSONAsyncTask extends AsyncTask<String, Void, Boolean> {
ProgressDialog dialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
/* dialog = new ProgressDialog(MainActivity.this);
dialog.setMessage("Loading, please wait");
dialog.setTitle("Connecting server");
dialog.show();
dialog.setCancelable(false);*/
Toast.makeText(getApplicationContext(), "fetch data from server", Toast.LENGTH_LONG).show();
}
#Override
protected Boolean doInBackground(String... urls) {
try {
//------------------>>
HttpGet httpGet = new HttpGet(urls[0]);
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(httpGet);
int status = response.getStatusLine().getStatusCode();
if (status == 200) {
HttpEntity entity = response.getEntity();
String data = EntityUtils.toString(entity);
JSONArray jsonarray = new JSONArray(data);
latLngList.clear();
for (int i = 0; i < jsonarray.length(); i++) {
JSONObject obj = jsonarray.getJSONObject(i);
longitudeServer = obj.getString("longi");
latitudeServer = obj.getString("lati");
uniqueidSserver = obj.getString("uniqueid");
LatLng latLng = new LatLng(Double.parseDouble(latitudeServer), Double.parseDouble(longitudeServer));
latLngList.add(latLng);
}
return true;
}
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return false;
}
protected void onPostExecute(Boolean result) {
Toast.makeText(getApplicationContext(), "Receicve data from server", Toast.LENGTH_LONG).show();
if (result == false) {
Toast.makeText(getApplicationContext(), "Unable to fetch data from server", Toast.LENGTH_LONG).show();
}
try {
if (marker != null) {
mMap.clear();
Toast.makeText(getApplicationContext(), "Remove", Toast.LENGTH_LONG).show();
}
for (LatLng object : latLngList)
marker = mMap.addMarker(new MarkerOptions().title("User Name").position(object).icon(BitmapDescriptorFactory.fromResource(R.drawable.female4)));
System.out.println(marker.getPosition() + " Marker position.......");
} catch (Exception e) {
Toast.makeText(MainActivity.this, "Error ", Toast.LENGTH_LONG).show();
// mMap.clear();
}
}
Although #Guillaume answer is correct, i would like to suggest a better and faster way. You can use a third party library LoganSquare to serialize and parse your models to and from JSON respectively. You just have to annotate your models and use LoganSquare class to parse data.
In your case it would be like this: (pay close attention to annotations above class name and fields)
#JsonObject
public class MyServer {
#JsonField(name = "longi")
public String longitudeServer;
#JsonField(name = "lati")
public String latitudeServer;
#JsonField(name = "uniqueid")
public String uniqueidSserver;
public MyServer(){
// blank constructor is required
}
}
Now use LoganSquare static class to parse the json response received from server:
for (int i = 0; i < jsonarray.length(); i++) {
MyServer s = LoganSquare.parse(jsonarray.getJSONObject(i).toString(), MyServer.class);
LatLng latLng = new LatLng(Double.parseDouble(s.getLatidude()), Double.parseDouble(s.getLongitude())); // Use your server's methods
latLngList.add(latLng);
}
First define your desired model into a class with for example a constructor allwing to create a new instance from a JSONObject
class JSONAsyncTask extends AsyncTask<String, Void, Boolean> {
class MyServer {
private String longitudeServer;
private String latitudeServer;
private String uniqueidSserver;
public MyServer(JSONObject obj){
try{
longitudeServer = obj.getString("longi");
latitudeServer = obj.getString("lati");
uniqueidSserver = obj.getString("uniqueid");
}catch(JSONException jse){
e.printStackTrace();
}
}
public String getLongitude(){
return longitudeServer;
}
public void setLongitude(String longitudeServer){
this.longitudeServer = longitudeServer;
}
//... More setter and getter here
}
// ... The existing code of your async task here
}
Once this done your can instanciate a new MyServer and use its getter/setter
for (int i = 0; i < jsonarray.length(); i++) {
JSONObject obj = jsonarray.getJSONObject(i);
MyServer s = new MyServer(obj); // Create your server from the JSONObject
LatLng latLng = new LatLng(Double.parseDouble(s.getLatidude()), Double.parseDouble(s.getLongitude())); // Use your server's methods
latLngList.add(latLng);
}
I know that there are a few question about this subject, but I read them and I tried the soluttion but it didn't work :(
the PHP script give this json array result: data[x] =
["alon","62","1.82","22","0","70","0","1"]
(this is the data[x] variable)
I have to convert this result to Java variabls like name,weight,height etc.. but I don't know how..
please help me
my function:
private class LongOperation extends AsyncTask<String, Void, Void> {
private final HttpClient Client = new DefaultHttpClient();
private String Error = null;
protected void onPreExecute() {
}
protected Void doInBackground(String... urls) {
try {
HttpGet httpget = new HttpGet(urls[0]);
ResponseHandler<String> responseHandler = new BasicResponseHandler();
data[x] = Client.execute(httpget, responseHandler);
} catch (ClientProtocolException e) {
Error = e.getMessage();
Toast.makeText(getApplicationContext(),"error2" , Toast.LENGTH_LONG).show();
cancel(true);
} catch (IOException e) {
Error = e.getMessage();
Toast.makeText(getApplicationContext(),"error34" , Toast.LENGTH_LONG).show();
cancel(true);
}
return null;
}
public void onPostExecute(Void unused) {
String name = null,weight = null;
if (Error != null) {
} else {
// here I have to do something with the arrays...
Toast.makeText(getApplicationContext(),"d:" + data[x] + "o:" + name + " : " + weight, Toast.LENGTH_LONG).show();
}
x++;
}
}
Create a Modal Class for that.
class myModal {
private String name, weight, height, ...;
public String getName() { return this.name; }
public void setName(String name) { this.name = name; }
//and more getters and setters
}
JSONObject json = new JSONObject(data[x]); // in your sample its a JSONArray but its wrong formatted. make sure you encode it properply with php json_encode(array("data", yourdata))...);
myModal modal = new myModal();
modal.setName(json.getString("name"));
php should be something like
<?php
$data = array("name" => "myname", "weight" => 20);
print json_encode( $data );
?>
while the json can be parsed in this case with
JSONArray json = new JSONArray(data);
for (int i = 0; i <= json.length();i++){
JSONObject jsonObj = json.getJsonObject(i);
myModal modal = new myModal();
modal.setString(jsonObj.getString("name"));
//and so on
}
make sure to read the basics for understanding
I am communicating with a database in php mysql travez to display results in a ListView, but I'm trying to implement a ExeptionConnection for when 3G or WIFI but the application can not connect, return to previous Activity and show a Toast. but not how to implement it in my code, I could only implement JsonExeption.
This is my code:
protected String doInBackground(String... args) {
List<NameValuePair> params = new ArrayList<NameValuePair>();
JSONObject json = jParser.makeHttpRequest(url_list_rs, "GET",
params);
Log.d("All Products: ", json.toString());
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
daftar_rs = json.getJSONArray(TAG_DAFTAR_RS);
for (int i = 0; i < list_rs.length(); i++) {
JSONObject c = list_rs.getJSONObject(i);
//Process Code
}
} else {
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
Where url_list_rs is the url of my php. Where I can Implement ExeptionConnection? Can anyone help? Thank Masters!
If you want to create you own exception, you can do:
//create a new Exception class
public class ConnectionException extends Exception {
public ConnectionException(String message){
super(message);
}
}
In your makeHttpRequest method
if(no connection) { //check connection
throw new ConnectionException ("No connection!");
} else { ... }
Finally, and try-catch block
try {
JSONObject json = jParser.makeHttpRequest(url_list_rs, "GET",
params);
catch(ConnectionException ex) {
ex.printStackTrace();
}
Note: I am not sure if this is the best practice.