Save HashMap data into SQLite - java

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.

Related

How to set ArrayList values from database MySQL with IDE (Android Studio)?

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

Fetching data from an API with JSON and storing two objects in a single row of an Array Adapter

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/

java.lang.IllegalArgumentException: Object would be serialized to `null`: Android

I have recently been setting up mobile apps to work with my meteor server. As a part of this I have to pass the meteor web app data from android. Unfortunately I have been receiving a error that tells me that the java object I am passing "would be serialized to null". How do I prevent this?
JSONObject json = new JSONObject();
try{
json.put("Foo", "1");
json.put("Blah", 0);
}catch (JSONException e){
}
Object[] object = new Object[1];
object[0] = json;
System.out.println(object + ", " + object[0] + ", " + object[0].toString());
mMeteor.call("xxx", object, new ResultListener() {
#Override
public void onSuccess(String result) {
}
#Override
public void onError(String error, String reason, String details) {
}
});
}
#Override
public void onError(String error, String reason, String details) {
}
});
Android/Meteor interface Library function
public void callWithSeed(final String methodName, final String randomSeed, final Object[] params, final ResultListener listener) {
// create a new unique ID for this request
final String callId = uniqueID();
// save a reference to the listener to be executed later
if (listener != null) {
mListeners.put(callId, listener);
}
// send the request
final Map<String, Object> data = new HashMap<String, Object>();
data.put(Protocol.Field.MESSAGE, Protocol.Message.METHOD);
data.put(Protocol.Field.METHOD, methodName);
data.put(Protocol.Field.ID, callId);
if (params != null) {
data.put(Protocol.Field.PARAMS, params);
}
if (randomSeed != null) {
data.put(Protocol.Field.RANDOM_SEED, randomSeed);
}
send(data);
}
I was having this same issue, my first error was passing a CharSequence instead a String as a parameter (your Object[]), and my other error was passing an Object[] as another parameter (I solved this by sending a String instead, like : String.valueOf(your_object_list)) Dont forget to handle this on your server side, you will receive a String instead of an Object.
Convert the JSONArray to List & JSONObject to HashMap and then pass those instead of the raw JSONObject or JSONArray.
You can write a recursive function for the conversion in case of nested JSONObject and JSONArray or can use GSON library for the conversion.
For more details about the conversion, this SO post may be helpful.

Access a varibale from MainActivity class to another class

I have a JSONObject in my MainActivity under a function and I want to use it outside the function and in another class, how can I do that?
I want to make this variable public, here is the code :
public void ListDrwaer() {
List<Map<String, String>> productList = new ArrayList<Map<String, String>>();
try {
JSONObject jsonResponse = new JSONObject(jsonResult);
JSONArray jsonMainNode = jsonResponse.optJSONArray("products");
for (int i = 0; i < jsonMainNode.length(); i++) {
JSONObject jsonChildNode = jsonMainNode.getJSONObject(i);
}
// System.out.println("*****JARRAY*****" + jsonMainNode.getJSONObject(0));
List<Map<String, String>> productLista = new ArrayList<Map<String, String>>();
JSONObject pro1 = jsonMainNode.getJSONObject(1);
String data = pro1.getString("name");
// System.out.println("*****JARRAY*****" + data);
System.out.println("*****JARRAY*****" + pro1);
} catch (JSONException e) {
Toast.makeText(getApplicationContext(), "Error" + e.toString(),
Toast.LENGTH_SHORT).show();
}
I want to make pro1 (which is JSONObject) public and use it outside public void and also use it in another class.
Can I do that using put or add?
try code below, it might help..
Intent intent = new Intent(getBaseContext(), SignoutActivity.class);
intent.putExtra("EXTRA_SESSION_ID", sessionId);
startActivity(intent);
You will need to create the variable first outside any method like this
Static JSONObject pro1;
and then acces it simple by using
classname.pro1
you can declare that variable public.
just put
public static JSONObject pro1;
to your class declaration.
2. that is not safe because of:
1. that variable will vanish if your app will be killed and recreated by Android system.
2. you should be carefull when accessing that variable from other threads.

parsing a specific JSON data format

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

Categories

Resources