how to get from MySQL data to android with json - android

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.

Related

JSON Object to Array of String

We are developing an Ecommerce Mobile Application but here we are facing an problem in passing an array of string to an Json Object. Whenever we are passing the same it is throwing an error as attached in the Log. It seems like an extra "\" is coming up.
Please find below my code Snippet:
try {
stFullName=Edit_FullName.getText().toString();
Log.e("BillingName",stFullName);
stEmailId=Edit_EmaiAdress.getText().toString();
stAddress=Edit_Adress.getText().toString();
stCity=Edit_City.getText().toString();
stState=Edit_State.getText().toString();
stZipCode=Edit_ZipCode.getText().toString();
stPhoneNo=Edit_MobileNumber.getText().toString();
stCountry=Edit_Country.getText().toString();
stLandmark=Edit_Landmark.getText().toString();
jsonObject1.put("BillingName",stFullName);
jsonObject1.put("BillingEmail",stEmailId);
jsonObject1.put("BillingTelephone",stPhoneNo);
jsonObject1.put("BillingCountry",stCountry);
jsonObject1.put("BillingZip",stZipCode);
jsonObject1.put("BillingCity",stCity);
jsonObject1.put("BillingState",stState);
jsonObject1.put("BillingLandmark",stLandmark);
jsonObject1.put("GrandTotal",ProductAmount);
jsonObject1.put("BillingAddress",stAddress).toString().replaceAll("\\\\","");
jsonObject1.put("DeviceID",deviceId);
jsonObject1.put("IsDifferentShipping",false);
String jsonFormattedString = jSonData;
Log.e("jsonFormattedString",jsonObject1.toString());
JSONArray jsonArray = new JSONArray();
jsonArray.put(productArray);
Log.e("productArray",productArray.toString());
productArray = productArray.toString().replaceAll("\\\\","").trim();
jsonObject1.put("ChekoutProductsModel_List",productArray.toString().replaceAll("\\\\",""));
Log.e("productArray", jsonObject1.toString().replaceAll("\\\\","").trim());
//
} catch (JSONException e) {
e.printStackTrace();
}
Log.e("object1",jsonObject1.toString());
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST, Config.Url.concat(getMakePayment),
jsonObject1, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject Response) {
Log.e("jsonResponse",Response.toString());
try {
String jsonResponse=Response.getString("ResponseObject");
Log.e("ResponseBilling",jsonResponse);
if(jsonResponse.equals("Billing info save successfully!")){
Toast.makeText(context,jsonResponse,Toast.LENGTH_SHORT).show();
Intent intent=new Intent(context,ProductReview.class);
intent.putExtra("product_id",ProductCode);
intent.putExtra("stock_id",StockId);
startActivity(intent);
}
else {
Toast.makeText(context,jsonResponse,Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
If any body can please check and help us out on the same.

Android Volley: using a for loop to extract data from a JsonObject

I am working on an android project that will get a Json array from a server and then I want to iterate through the array and extract data from each Json object in the array. When I run this code the textviews do not change, but if I remove the for loop and everything in it, and then uncomment the two lines below the for loop, things seems to work. How can you iterate through the Json objects in the array so that the info will be updated on the screen and change every second for each object in the array?
Thank you in advance!
name = (TextView)findViewById(R.id.nameTxt);
email = (TextView)findViewById(R.id.emailTxt);
serverButton = (Button)findViewById(R.id.getInfoBtn);
serverButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(server_url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
try {
for (int i = 0; i < response.length(); i++) {
JSONObject nameJson = response.getJSONObject(i);
name.setText(nameJson.getString("FirstName") + " " + nameJson.getString("LastName"));
email.setText(nameJson.getString("Email"));
Thread.sleep(1000);
}
//JSONObject nameJson = response.getJSONObject(1);
// name.setText(nameJson.getString("FirstName"));
} catch (JSONException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
name.setText("Something is wrong");
}
});
MySingleton.getInstance(MainActivity.this).addToRequestQueue(jsonArrayRequest);

How to display database data after selecting the item from spinner?

I want to display person details from reg_farmer table.. If i select an item from the spinner, i want to display the corresponding data matches with that item from the database.
Here is my android MainActivity.class file..
public class MainActivity extends AppCompatActivity {
//Declaring an Spinner
private Spinner spinner,spinner2;
//An ArrayList for Spinner Items
private ArrayList<String> states;
private ArrayList<String> district;
//JSON Array
private JSONArray States;
private JSONArray District;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Initializing the ArrayList
states = new ArrayList<String>();
district = new ArrayList<String>();
//Initializing Spinner
spinner = (Spinner) findViewById(R.id.spinner);
spinner2 = (Spinner) findViewById(R.id.spinner2);
//Adding an Item Selected Listener to our Spinner
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String sid="";
try {
//Getting object of given index
JSONObject json = States.getJSONObject(position);
//Fetching id from that object
sid = json.getString("id");
} catch (JSONException e) {
e.printStackTrace();
}
getDistrict(sid);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
Toast.makeText(MainActivity.this,"Nothing Selected",Toast.LENGTH_SHORT).show();
}
});
spinner2.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String Dname="";
try {
//Getting object of given index
JSONObject json = District.getJSONObject(position);
//Fetching name from that object
Dname = json.getString("dname");
} catch (JSONException e) {
e.printStackTrace();
}
Toast.makeText(MainActivity.this,Dname,Toast.LENGTH_SHORT).show();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
Toast.makeText(MainActivity.this,"Empty",Toast.LENGTH_SHORT).show();
}
});
//This method will fetch the States data from the URL
getStates();
}
private void getStates(){
//Creating a string request
StringRequest stringRequest = new StringRequest(Request.Method.POST,Config.DATA_State,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
JSONObject j = null;
try {
//Parsing the fetched Json String to JSON Object
j = new JSONObject(response);
//Storing the Array of JSON String to our JSON Array
States = j.getJSONArray("States");
for(int i=0;i< States.length();i++){
try {
//Getting json object
JSONObject state = States.getJSONObject(i);
//Adding the name of the state to array list
MainActivity.this.states.add(state.getString("name"));
} catch (JSONException e) {
e.printStackTrace();
}
}
//Setting adapter to show the items in the spinner
spinner.setAdapter(new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_spinner_dropdown_item, states));
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this,error.toString(),Toast.LENGTH_LONG).show();
}
});
//Creating a request queue
RequestQueue requestQueue = Volley.newRequestQueue(this);
//Adding request to the queue
requestQueue.add(stringRequest);
}
private void getDistrict(final String sid){
//Creating a string request
StringRequest dRequest = new StringRequest(Request.Method.POST,Config.DATA_District,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
JSONObject j = null;
try {
//Parsing the fetched Json String to JSON Object
Log.i("tagconvertstr", "[" + response + "]");
j = new JSONObject(response);
boolean error = j.getBoolean("error");
// Check for error node in json
if (!error) {
//Storing the Array of JSON String to our JSON Array
District = j.getJSONArray("District");
//Toast.makeText(MainActivity.this, District.toString(), Toast.LENGTH_SHORT).show();
district.removeAll(district);
for (int i = 0; i < District.length(); i++) {
try {
//Getting json object
JSONObject dist = District.getJSONObject(i);
//Adding the name of the district to array list
MainActivity.this.district.add(dist.getString("dname"));
} catch (JSONException e) {
e.printStackTrace();
}
}
//Setting adapter to show the items in the spinner
spinner2.setAdapter(new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_spinner_dropdown_item, district));
}else {
String errorMsg = j.getString("error_msg");
Toast.makeText(MainActivity.this,
errorMsg, Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(MainActivity.this,error.toString(),Toast.LENGTH_LONG).show();
}
}){
#Override
protected Map<String,String> getParams(){
Map<String,String> params = new HashMap<String, String>();
params.put("state_id", sid);
return params;
}
};
//Creating a request queue
RequestQueue requestQueue = Volley.newRequestQueue(this);
//Adding request to the queue
requestQueue.add(dRequest);
}
}
Here is my Config.java file.. In this file i give the url for fetching spinner items..
public class Config {
//JSON URL
public static final String DATA_State = "http://10.0.3.2/cof/state.php";
public static final String DATA_District = "http://10.0.3.2/cof/district.php";
}
I want to display the details like this.. I want to view code,name and mobile number of the person when i choose the district and state from the spinner
I guess you are trying to communicate with a local database. Getting data from an eternal database requires 3 steps.
Creating your database - it can be local using services like wamp or it can be present on actual server.
Creating webservice - In this step you need to create a Webservice which interacts with your database and responds to your android code. It includes making of config. php file which stores your server & database information, then you have your actual anyname.php file which include config.php file, the code to get the data from database and to respond back to android app.
Calling webservice from android - In this step you actually call the webservice from your code to retrieve data from it.
Now as we can see from your provided code. You might have completed most or all of these steps. According to me you have your database ready. You have shown the config folder with two php files which shows that you have your php files ready.
Now to debug, first try to open the links in your browser and see if you get any result. If you get the information correctly then it means that you have placed the files correctly. Now try to print the result of volley in logcat to see if you have the data in your app. If everything works fine then you only have to handle spinner listener. If any of these steps fail, tell us about it.
First you have to retrieve all the data then adding them to an array list so you could get the info again,
You can look at that example it does what you want exactly ,
private void retrieveJSON() {
StringRequest stringRequest = new StringRequest(
Request.Method.GET,
URLstring,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
Log.d("strrrrr", ">>" + response);
try {
JSONObject obj = new JSONObject(response);
goodModelArrayList = new ArrayList<>();
JSONArray dataArray = obj.getJSONArray("data");
for (int i = 0; i < dataArray.length(); i++) {
PMenus playerModel = new PMenus();
JSONObject dataobj = dataArray.getJSONObject(i);
playerModel.setName(dataobj.getString("name"));
playerModel.setCountry(dataobj.getString("country"));
playerModel.setCity(dataobj.getString("city"));
playerModel.setImgURL(dataobj.getString("imgURL"));
goodModelArrayList.add(playerModel);
}
for (int i = 0; i < goodModelArrayList.size(); i++){
names.add(goodModelArrayList.get(i).getName().toString());
}
ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(AddPatient.this, simple_spinner_item, names);
spinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); // The drop down view
PmSpinner.setAdapter(spinnerArrayAdapter);
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//displaying the error in toast if occurrs
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
// request queue
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
Now after adding the data into an array you can use this method
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
String item = parent.getItemAtPosition(position).toString() ;
String city = goodModelArrayList.get(position).getCity().toString() ;
String country = goodModelArrayList.get(position).getCountry().toString() ;
testnotes.setText(item);
testno.setText(city);
testprice.setText(country);
}
and ofcourse don't forget to add this line in you onCreate
goodModelArrayList = new ArrayList<>();
and define it like that
private ArrayList<PMenus> goodModelArrayList;

Android Volley after adding items to arraylist still empty after adding

I am using volley in my android app and i add Torrent objects to the Arraylist and it fills the list but after the program exits this method getAllDetails() the arraylist is empty..could someone please explain what is really going on???
private void getAllDetails() {
String URL = MOVIE_DETAILS_URL + movie.getId() + CAST_URL;
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(URL, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONObject dataObject = response.getJSONObject(Keys.DATA);
JSONObject movieObject = dataObject.getJSONObject(Keys.MOVIE);
JSONArray torrentsArray = movieObject.getJSONArray(Keys.TORRENTS);
for (int i = 0; i < torrentsArray.length(); i++) {
JSONObject torrentObject = torrentsArray.getJSONObject(i);
Torrent torrent = new Torrent();
torrent.setUrl(torrentObject.getString(Keys.URL));
torrent.setSize(torrentObject.getString(Keys.SIZE));
torrent.setQuality(torrentObject.getString(Keys.QUALITY));
torrent.setSeeds(Integer.parseInt(torrentObject.getString(Keys.SEEDS)));
torrent.setPeers(Integer.parseInt(torrentObject.getString(Keys.PEERS)));
torrentList.add(torrent);
}
getTorrent();//when this method is called here the list has items on it and it works fine
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
requestQueue.add(jsonObjectRequest);
}
this method uses the torrentlist arraylist to download the .torrent file
private void getTorrent() {
String mUrl = torrentList.get(0).getUrl();
InputStreamVolleyRequest request = new InputStreamVolleyRequest(Request.Method.GET, mUrl,
new Response.Listener<byte[]>() {
#Override
public void onResponse(byte[] response) {
// TODO handle the response
try {
if (response != null) {
String name = movie.getMovie_title() + ".torrent";
File torrentDirectory = createFolder();
File file = new File(torrentDirectory, name);
FileOutputStream fos = new FileOutputStream(file);
fos.write(response);
Toast.makeText(ViewMovie.this,"Successfully Downloaded",Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
// TODO Auto-generated catch block
Log.d("KEY_ERROR", "UNABLE TO DOWNLOAD FILE");
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// TODO handle the error
error.printStackTrace();
}
}, null);
RequestQueue mRequestQueue = Volley.newRequestQueue(getApplicationContext(), new HurlStack());
mRequestQueue.add(request);
}
A quick fix you can try to pass your ArrayList to your getTorrent() function.
getTorrent(torrentList);
You will call your function like this.
private void getTorrent(ArrayList<Torrent> passedList) {
String mUrl = passedList.get(0).getUrl();
// rest of your code here
}
But you need to know that, this function will always give you the result of first torrent. Because you are getting 0 index in ArrayList. Maybe by passing index also, you can create more functional method.

Return multiple values using asynctask

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();
}
}
}
}

Categories

Resources