i have this small problem,i am making a android application n use a .php file to call java script file that returns me a JSON output..now my problem is the output is in a valid JSON format, now i am confused as to how to parse the values.
the output is
["15.493511","73.818659"]
where the 1st value is the latitude value and the 2nd being longitude value..
what i want to do is parse this is on fetching this value in the asynctask i want to split these values ans assign them to variables. any idea how i could do this.
Thank you in advance.
well its a json array
<?php
$val = '["15.493511","73.818659"]';
$arrVal = json_decode($val, true);
print_r($arrVal);
$latitude = $arrVal[0];
$longitude = $arrVal[1]
This will output:
array(15.493511, 73.818659);
as you said i want to do is parse this is on fetching this value in the asynctask means you need to parse the json data in android application.
JSONArray jObject = new JSONArray(result); //result is the json data you received
String lat = jObject.getString(0);
String long = jObject.getString(1);
updated the answer as suggested by spring-breaker
Do something like below,
private class MyAsyncTask extends AsyncTask<String, String, String>
{
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
String data="["15.493511","73.818659"]"; // Assuming that it is your static data
try {
JSONArray myArray=new JSONArray(data);
String lattitude=myArray.getString(0);
String longitudetude=myArray.getString(1);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
//update your UI or do your task;
}
}
}
And execute the AsyncTask like following,
new MyAsyncTask().execute();
You are getting JSON Array.
So your code can be something like this..
String latitude=jsonarray.getString(0);
String longitude=jsonarray.getString(1);
try below code:-
JSONArray j = new JSONArray("ur value");
for (int i = 0; i < j.length(); i++)
{
System.out.println(j.get(i));
}
Related
I want to put data from a MySQL database table into Android Studio.
For modifying script from tutorial.
In tutorial ArrayList value is:
HomeCollection.date_collection_arr = new ArrayList<HomeCollection>();
HomeCollection.date_collection_arr.add(new HomeCollection("2018-07-08" ,"Title1","Subject1","Description1"));
HomeCollection.date_collection_arr.add(new HomeCollection("2018-07-09" ,"Title2","Subject2","Description2"));
HomeCollection.date_collection_arr.add(new HomeCollection("2018-07-10" ,"Title3","Subject3","Description3"));
My Question:
How to modify data Array, in example with all data in MySql table
having below columns?
| id | date | title | subject | description |
Any help will be greatly appreciated
//you can do like this.
get the value from arraylist into string array then split the array and then send the string to database.given below code
String[] value = HomeCollection.date_collection_arr.get(0).split(",");
String date=value[0];
String title=value[1];
String description=value[2];
//if your array list value contain space use below code
String[] valuetrim= HomeCollection.date_collection_arr.get(0).split("\\s*,\\s*");
String valuetrim=value[0];
String valuetrim=value[1];
String valuetrim=value[2];
Thanx for your clue, but I still not understand,
I try to get array list, from this way n success to views data at list (bellow array scrip),
maybe someone can give me more specific, how to implement/combine value data i have got from this way (below) to array at my question (i want to impemented sample script from this link https://www.developerbrothers.com/highlight-events-custom-calendar-android-studio-developerbrothers-com/) but i want data values get from MySql, Thanks
private void showOrder(){
JSONObject jsonObject = null;
ArrayList> list = new ArrayList>();
try {
jsonObject = new JSONObject(JSON_STRING);
JSONArray result = jsonObject.getJSONArray(konfigurasi.TAG_JSON_ARRAY);
for(int i = 0; i<result.length(); i++){
JSONObject jo = result.getJSONObject(i);
String idplace = jo.getString(konfigurasi.TAG_PLACE);
String titl = jo.getString(konfigurasi.TAG_TITLE);
String subj = jo.getString(konfigurasi.TAG_SUBJECT);
String desc= jo.getString(konfigurasi.TAG_DESCRIPTION);
String dateo = jo.getString(konfigurasi.TAG_DATEORDER);
HashMap<String,String> orders = new HashMap<>();
orders.put(konfigurasi.TAG_PLACE,idplace);
orders.put(konfigurasi.TAG_TITLE,titl);
orders.put(konfigurasi.TAG_SUBJECT,subj);
orders.put(konfigurasi.TAG_DESCRIPTION,desc);
orders.put(konfigurasi.TAG_DATEORDER,dateo);
list.add(orders);
}
} catch (JSONException e) {
e.printStackTrace();
}
ListAdapter adapter = new SimpleAdapter(
DateEventActivity.this, list, R.layout.list_item,
new String[]{konfigurasi.TAG_PLACE,konfigurasi.TAG_TITLE,konfigurasi.TAG_SUBJECT,konfigurasi.TAG_DESCRIPTION,konfigurasi.TAG_DATEORDER},
new int[]{R.id.idplace, R.id.titl, R.id.subj, R.id.desc, R.id.dateo});
listView.setAdapter(adapter);
}
private void getJSON(){
class GetJSON extends AsyncTask<Void,Void,String> {
ProgressDialog loading;
#Override
protected void onPreExecute() {
super.onPreExecute();
loading = ProgressDialog.show(DateEventActivity.this,"Mengambil Data","Mohon Tunggu...",false,false);
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
loading.dismiss();
JSON_STRING = s;
showOrder();
}
#Override
protected String doInBackground(Void... params) {
RequestHandler rh = new RequestHandler();
String s = rh.sendGetRequest(konfigurasi.URL_GET_ALL);
return s;
}
}
GetJSON gj = new GetJSON();
gj.execute();
}
I am doing an app where I synchronize my online DB to the offline DB everytime the user logs in. The table is dropped in offline, recreated then new rows gets added ( Its neccessary to drop it and add new instead of just checking and adding the rows that are not in the table already). I had about 200 rows in my online table and they are synchronised to my offline table relatively fast (in the background, then I tried 3000 and it was still processing. But When I generated 90 000 rows and tried to synchronize it to my offline DB it wouldnt move.
The log in onPreExecute() executed, but none of the logs in my doInBackground. json is not null.
For each retrieved row I am adding a row in offline.
Anyone know what could be the issue?
I tried adding LIMIT 200 in my PHP Scripts and still didnt do it, which was weird, cause when I had 200 rows it executed, but when I limit the output to 200 it does not.
Thank you for any answers, that would bring me closer to the solution.
public class SyncVykresToOffline {
String DataParseUrl = "/scriptsforandroidapplicationofflinemode/SyncVykresToOffline.php";
JSONObject json = null;
String str = "";
HttpResponse response;
DBHelper dbh;
private Context mContext;
public static boolean syncedvykres = false;
int k = 200;
public SyncVykresToOffline(Context context) {
mContext = context;
dbh = new DBHelper(mContext);
}
public class SyncVykres extends AsyncTask<Void, Void, Void>
{
public Context context;
public SyncVykres(Context context)
{
this.context = context;
}
#Override
protected void onPreExecute()
{
super.onPreExecute();
Log.i("Poradie_zacal","ano");
}
#Override
protected Void doInBackground(Void... arg0)
{
HttpClient myClient = new DefaultHttpClient();
HttpPost myConnection = new HttpPost(DataParseUrl);
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("limit", String.valueOf(k)));
try {
myConnection.setEntity(new UrlEncodedFormEntity(nameValuePairs));
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
}
try {
HttpResponse response = myClient.execute(myConnection);
} catch (IOException e1) {
e1.printStackTrace();
}
try {
response = myClient.execute(myConnection);
str = EntityUtils.toString(response.getEntity(), "UTF-8");
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
int i = 0;
try{
int vykres_version;
JSONArray jArray = new JSONArray(str);
json = jArray.getJSONObject(i);
Log.i("Poradie_json",String.valueOf(jArray.length()));
String
Nazov_vykresu;
int Version,
ID_vykres,
ID_stav,
ID_zakazka,
Poradie;
if(json == null) {
Log.i("Poradie","son is null");
}
while(json != null) {
Log.i("Poradie","been here");
ID_vykres = Integer.parseInt(json.getString("ID_vykres"));
vykres_version = dbh.getVykresVersion(ID_vykres);
Nazov_vykresu = json.getString("Nazov_vykresu");
ID_stav = Integer.parseInt(json.getString("ID_stav"));
ID_zakazka = Integer.parseInt(json.getString("ID_zakazka"));
Version = Integer.parseInt(json.getString("Version"));
Poradie = Integer.parseInt(json.getString("Poradie"));
Log.i("Poradie",json.getString("Poradie"));
dbh.SyncVykresToOffline(new technicky_vykres(ID_vykres,Nazov_vykresu,ID_stav,ID_zakazka,Version,Poradie));
i++;
json = jArray.getJSONObject(i);
}
} catch ( JSONException e) {
e.printStackTrace();
}
catch (Exception e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
protected void onPostExecute(Void result)
{
syncedvykres = true;
}
}
}
Edit: added Logcat logs.
06-25 20:36:07.013 8278-8308/com.example.chris.normitapplication W/System.err: at org.json.JSON.typeMismatch(JSON.java:111)
at org.json.JSONArray.<init>(JSONArray.java:96)
at org.json.JSONArray.<init>(JSONArray.java:108)
at com.example.chris.normitapplication.offline.SyncVykresToOffline$SyncVykres.doInBackground(SyncVykresToOffline.java:102)
at com.example.chris.normitapplication.offline.SyncVykresToOffline$SyncVykres.doInBackground(SyncVykresToOffline.java:44)
at android.os.AsyncTask$2.call(AsyncTask.java:292)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
Edit 2: added PHP Script from where the JSON array is retrieved from:
<?php
include 'DatabaseConfig.php';
$conn = mysqli_connect($HostName,$HostUser,$HostPass,$DatabaseName);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
mysqli_set_charset($conn,"utf8");
$vykres = array();
$sql = "SELECT * FROM `technicky_vykres`";
$result = mysqli_query($conn, $sql) or die("Error in Selecting " . mysqli_error($conn));
while($row =mysqli_fetch_assoc($result))
{
$emparray[] = $row;
}
echo json_encode($emparray);
$conn->close();
?>
Issue identified when logging STR:
<html>
<head><title>502 Bad Gateway</title></head>
<body bgcolor="white">
<center><h1>502 Bad Gateway</h1></center>
<hr><center>openresty</center>
</body>
</html>
My hunch is, its the data that is breaking the loop and causing your program to end without going through the complete data set. I just added simple try/catch (see below) to printout any data objects, that we can't parse and but still continue to process the next row. Of course you'll need to have better error handling in place for production quality code.
while(json != null) {
try{
Log.i("Poradie","been here");
ID_vykres = Integer.parseInt(json.getString("ID_vykres"));
vykres_version = dbh.getVykresVersion(ID_vykres);
Nazov_vykresu = json.getString("Nazov_vykresu");
ID_stav = Integer.parseInt(json.getString("ID_stav"));
ID_zakazka = Integer.parseInt(json.getString("ID_zakazka"));
Version = Integer.parseInt(json.getString("Version"));
Poradie = Integer.parseInt(json.getString("Poradie"));
Log.i("Poradie",json.getString("Poradie"));
dbh.SyncVykresToOffline(new technicky_vykres(ID_vykres,Nazov_vykresu,ID_stav,ID_zakazka,Version,Poradie));
i++;
json = jArray.getJSONObject(i);
}catch(Exception e){
//Something wrong with the data? log it and see if you can find the culprit row/data....
Log.i("The faulty jason obj: " + json);
continue; //Move on the next one....
}
}
The error indicates that JSONArray believes your response is not formed as a Json Array.
Here's the code within JSONArray throwing your error:
public JSONArray(JSONTokener readFrom) throws JSONException {
/*
* Getting the parser to populate this could get tricky. Instead, just
* parse to temporary JSONArray and then steal the data from that.
*/
Object object = readFrom.nextValue();
if (object instanceof JSONArray) {
values = ((JSONArray) object).values;
} else {
throw JSON.typeMismatch(object, "JSONArray");
}
}
So the tokener does not recognize the object as a JSONArray. I would take a look at your raw response and see if adding a limit doesn't change the response to be an object with a result array inside of it (so that it can also include arguments to help web calls handle paging). Either way, there's something in the format of the response that the tokener does not recognize as being a Json array.
Upon realizing that the PHP script stopped working because too many rows & columns were retrieved instead of * I only Selected data that I truly needed (about 1/3 of all columns), then I added a where clause where ID would be above the number I sent from post and I keep repeating the script until finally the response is not "null".
Thank you for everyone who contributed to finding the solution.
I've got this code with fetches the "rate" data from an API, along with "rate", I need to get the "name". If I get "name" it often binds it below the "rate".
I need it to join on the same row of the List View, so it is like [Rate Name].
I need to get two objects of a JSON Array and bind it to the array adapter so I can display two objects in the same row of a List View so it is more user friendly.
The code below is of the AsyncTask, the code works fine but I need to add one more object and make sure it is displayed as one rate - one name and then iterating through the loop and adding more as needed in the same order.
public class AsyncTaskParseJson extends AsyncTask<String, String, String> {
// the url of the web service to call
String yourServiceUrl = "eg: URL";
#Override
protected void onPreExecute() {
}
String filename = "bitData";
#Override
protected String doInBackground(String... arg0) {
try {
// create new instance of the httpConnect class
httpConnect jParser = new httpConnect();
// get json string from service url
String json = jParser.getJSONFromUrl(yourServiceUrl);
// parse returned json string into json array
JSONArray jsonArray = new JSONArray(json);
// loop through json array and add each currency to item in arrayList
//Custom Loop Initialise
for (int i = 1; i < 8; i++) {
JSONObject json_message = jsonArray.getJSONObject(i);
// The second JSONObject which needs to be added
JSONObject json_name = jsonArray.getJSONObject(i);
if (json_message != null) {
//add each currency to ArrayList as an item
items.add(json_message.getString("rate"));
String bitData = json_message.getString("rate");
String writeData = bitData + ',' +'\n';
FileOutputStream outputStream;
File file = getFileStreamPath(filename);
// first check if file exists, if not create it
if (file == null || !file.exists()) {
try {
outputStream = openFileOutput(filename, MODE_PRIVATE);
outputStream.write(writeData.getBytes());
outputStream.write("\r\n".getBytes());
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
// if file already exists then append bit data to it
else if (file.exists()) {
try {
outputStream = openFileOutput(filename, Context.MODE_APPEND);
outputStream.write(writeData.getBytes());
outputStream.write("\r\n".getBytes());
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
// below method will run when service HTTP request is complete, will then bind text in arrayList to ListView
#Override
protected void onPostExecute(String strFromDoInBg) {
ListView list = (ListView) findViewById(R.id.rateView);
ArrayAdapter<String> rateArrayAdapter = new ArrayAdapter<String>(BitRates.this, android.R.layout.simple_expandable_list_item_1, items);
list.setAdapter(rateArrayAdapter);
}
}
Just Create Custom Class Messsage:
public class Item{
private String name;
private String rate;
public void Message(String n, String r){
this.name=n;
this.rate=r;
}
// create here getter and setter
}
Now in your background, you have to add name and rate in Message class
Public class MainAcitity extends Activity{
public static List<Item> items= new ArrayList<>();// define in inside the class
// this has to be down on background
Item i=new Item(json_message.getString("name"),json_message.getString("rate"));
items.add(i);
Now pass this listmessge onPostExecute :
ListView list = (ListView) findViewById(R.id.rateView);
ArrayAdapter<String> rateArrayAdapter = new ArrayAdapter<String>(BitRates.this, android.R.layout.simple_expandable_list_item_1, items);
list.setAdapter(rateArrayAdapter);
Is that any helpful for you.
Follow this link.You will get my point.
https://devtut.wordpress.com/2011/06/09/custom-arrayadapter-for-a-listview-android/
I'm Trying to save data from Json into SQLite. For now I keep the data from Json into HashMap.
I already search it, and there's said use the ContentValues. But I still don't get it how to use it.
I try looking at this question save data to SQLite from json object using Hashmap in Android, but it doesn't help a lot.
Is there any option that I can use to save the data from HashMap into SQLite?
Here's My code.
MainHellobali.java
// Hashmap for ListView
ArrayList<HashMap<String, String>> all_itemList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_helloballi);
all_itemList = new ArrayList<HashMap<String, String>>();
// Calling async task to get json
new getAllItem().execute();
}
private class getAllItem extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
all_item = new JSONArray(jsonStr);
// looping through All Contacts
for (int i = 0; i < all_item.length(); i++) {
JSONObject c = all_item.getJSONObject(i);
String item_id = c.getString(TAG_ITEM_ID);
String category_name = c.getString(TAG_CATEGORY_NAME);
String item_name = c.getString(TAG_ITEM_NAME);
// tmp hashmap for single contact
HashMap<String, String> allItem = new HashMap<String, String>();
// adding each child node to HashMap key => value
allItem.put(TAG_ITEM_ID, item_id);
allItem.put(TAG_CATEGORY_NAME, category_name);
allItem.put(TAG_ITEM_NAME, item_name);
// adding contact to contact list
all_itemList.add(allItem);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
}
I have DatabasehHandler.java and AllItem.java too.
I can put it in here if its necessary.
Thanks before
** Add Edited Code **
// looping through All Contacts
for (int i = 0; i < all_item.length(); i++) {
JSONObject c = all_item.getJSONObject(i);
String item_id = c.getString(TAG_ITEM_ID);
String category_name = c.getString(TAG_CATEGORY_NAME);
String item_name = c.getString(TAG_ITEM_NAME);
DatabaseHandler databaseHandler = new DatabaseHandler(this); //error here "The Constructor DatabaseHandler(MainHellobali.getAllItem) is undefined
}
As mentioned by #birdy you can just store the JSON data as String inside your database.
In my case I've already done the same thing you are trying to achieve, in my case I've just created an abstract datasource that will be extended for any JSON object I will set in my database.
But basically you just need a method to convert a JSONObject to a ContentValues object.
public ContentValues jsonToContentValues(JSONObject json) {
ContentValues values = new ContentValues();
values.put("MY_COLUMN", json.optString("MY_JSON_VALUE"));
return values;
}
After you have your content value object all set you just need to insert the values on your database.
return database.insert("MY_TABLE_NAME", null, contentValues);
If what you need is to store JSON data - just store it as a text. Than after taking it back from database you can again parse it into map.
I have no idea how to solve problem, which I met while designing API for Android.
API must contain a method which will be able to get JSON Object from specific URL. So, I decide to put into the method AsyncTask to achieve that.
After execution method from this API I need populate a ListView, but I do not know how. As far as I know it is not possible to put AsyncTask( from method in my API) into other AsyncTask.
Any ideas, solutions, suggestions?
EDIT:
In the other words I want to create a method which will call restful services and get JSON.
This method will be executed (from other package) to populate ListView with the result.
My AsyncTask:
protected String doInBackground(HashMap<String,Boolean>... args)
{
JSONArray readings=null;
JSONObject json = getReadingsFromDB(args[0]);
try
{
int i;
readings = json.getJSONArray(TAG_READINGS);
for(i =0; i<readings.length();i++)
{
JSONObject ob = readings.getJSONObject(i);
ReadingH newReading = new ReadingH();
HashMap<String,String> map = new HashMap<String, String>();
String id;
String date;
String humidity;
String temp;
if(!ob.isNull(TAG_TEMPERATURE))
{
temp = ob.getString(TAG_TEMPERATURE);
newReading.setValue(TAG_TEMPERATURE, temp);
map.put(TAG_TEMPERATURE, temp);
}
if(!ob.isNull(TAG_ID))
{
id = ob.getString(TAG_ID);
newReading.setValue(TAG_ID, id);
map.put(TAG_ID, id);
}
if(!ob.isNull(TAG_DATE))
{
date = ob.getString(TAG_DATE);
map.put(TAG_DATE, date);
newReading.setValue(TAG_DATE, date);
}
if(!ob.isNull(TAG_HUMIDITY))
{
humidity= ob.getString(TAG_HUMIDITY);
map.put(TAG_HUMIDITY, humidity);
newReading.setValue(TAG_HUMIDITY, humidity);
}
readingsListH.add(newReading);
readingsList.add(map);
}
}
catch(Exception e)
{
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String file_url)
{
// pDialog.dismiss();
a.runOnUiThread(new Runnable()
{
public void run()
{
ListAdapter adapter = new SimpleAdapter(
a,readingsList,
R.layout.reading_item,new String[]{TAG_ID,TAG_DATE,TAG_TEMPERATURE},
new int[]{R.id.ReadingID,R.id.ReadingDate,R.id.ReadingTemperature});
a.setListAdapter(adapter);
}
});
}
doInBackground will be in my new method, but code from onPostExecute will be there where new method will be executed.
Regards