Fetching data from sqlite and storing in json - java

I have a table from which I want to fetch all data on behalf of a specific column and then want to save that data in form of JSON so that I can send it over API to the database for saving.
I am unable to get all data from the database though I tried doing it through cursor I am getting single data in this. Please help me in fetching the data and converting it into JSON. This is what I have coded. This is the method from Dbsave class which extends DatabaseOpenHelper.
public Cursor getAllData() {
SQLiteDatabase db = this.getWritableDatabase();
Cursor res = db.rawQuery("select * from "+"autosave",null);
return res;
}
And then I am using this method in the Activity like this.
public void getalldata(){
cursor=dbAutoSave.getAllData();
if (cursor!=null) {
if(cursor.moveToNext()) {
for (int i = 0; i <= cursor.getCount(); i++) {
aaa = cursor.getString(1);
String bbb = cursor.getString(2);
String ccc = cursor.getColumnName(3);
}
ArrayList<String> aaaa=new ArrayList<>();
aaaa.add(aaa);
Toast.makeText(getApplicationContext(),"bbbbb"+aaaa,Toast.LENGTH_LONG).show();
}
cursor.close();
}
}
I am getting only one data in aaaa. Then I tried doing this with gettersetter but with no benefit.
private void showEmployeesFromDatabase() {
Cursor cursorEmployees = mDatabase.rawQuery("SELECT * FROM autosave", null);
if (cursorEmployees.moveToFirst()) {
do {
// Pushing each record in the employee list
employeeList.add(new SetterGetter(
cursorEmployees.getString(0),
cursorEmployees.getString(1),
cursorEmployees.getString(2)
));
} while (cursorEmployees.moveToNext());
}
// Closing the cursor
System.out.println("aaaaaa" + employeeList.get(1));
cursorEmployees.close();
}
I am unable to parse the data from the list in settergetter. If I will be able to fetch all data, I will use GSON to convert it into JSON.

The loop inside getalldata function is faulty. It's not iterating over the cursor and just looping over the same element again and again. I would like to suggest to change the function like the following.
public void getalldata() {
// Cursor is loaded with data
cursor = dbAutoSave.getAllData();
ArrayList<String> aaaa = new ArrayList<>();
if (cursor != null) {
cursor.moveToFirst();
do {
aaa = cursor.getString(1);
String bbb = cursor.getString(2);
String ccc = cursor.getColumnName(3);
// Add into the ArrayList here
aaaa.add(aaa);
} while (cursor.moveToNext());
cursor.close();
}
}
Hope that fixes your problem.
Update
To convert the data stored in the ArrayList to JSON using GSON, you need to add the library first in your build.gradle file. You can find a way of using it here.
Just add the following dependency in your build.gradle file.
dependencies {
implementation 'com.google.code.gson:gson:2.8.5'
}
GSON takes an object for converting it to JSON. So I would like to suggest you create an object with the elements fetched from your cursor like the following.
public class Data {
public String aaa;
public String bbb;
public String ccc;
}
public class ListOfData {
public List<Data> dataList;
}
Now modify the function again like the following.
public void getalldata() {
// Cursor is loaded with data
cursor = dbAutoSave.getAllData();
ArrayList<Data> dataList = new ArrayList<Data>();
if (cursor != null) {
cursor.moveToFirst();
do {
Data data = new Data();
data.aaa = cursor.getString(1);
data.bbb = cursor.getString(2);
data.ccc = cursor.getColumnName(3);
// Add into the ArrayList here
dataList.add(data);
} while (cursor.moveToNext());
// Now create the object to be passed to GSON
DataList listOfData = new DataList();
listOfData.dataList = dataList;
Gson gson = new Gson();
String jsonInString = gson.toJson(listOfData); // Here you go!
cursor.close();
}
}

You are initializing your array list every time inside the cursor
Initialize it outside the cursor
public void getalldata(){
cursor=dbAutoSave.getAllData();
ArrayList<String> aaaa=new ArrayList<>();
if (cursor!=null) {
if(cursor.moveToNext()) {
for (int i = 0; i <= cursor.getCount(); i++) {
aaa = cursor.getString(1);
String bbb = cursor.getString(2);
String ccc = cursor.getColumnName(3);
}
aaaa.add(aaa);
Toast.makeText(getApplicationContext(),"bbbbb"+aaaa,Toast.LENGTH_LONG).show();
}
cursor.close();
}
}

Related

Converting Arraylist from java.utils to kotlin.collections.arraylist

My project contains two classes one in java another in kotlin. I am calling method in java class from kotlin but the method returns arraylist is in format of java.utils.arraylist but while excepting it need in format of kotlin.collections.arraylist. So is there any way if I could convert or other way to accept arraylist from java to kotlin
kotlin class
class contactAllFragment : Fragment() {
#BindView(R.id.contacts_lv) lateinit var contact_lv: ListView
var al = ArrayList<HashMap<String,String>>()
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
var view: View
view = inflater.inflate(R.layout.fragment_contact_all,container,false)
ButterKnife.bind(this,view)
//load all contacts
al = LoadAllContacts(activity.application.contentResolver,
activity.applicationContext)
.loadContacts()
var adapter: SimpleAdapter = SimpleAdapter(context,al,R.layout.listview_style,LoadAllContacts.keys,LoadAllContacts.ids);
if(contact_lv!=null)
contact_lv.adapter(adapter)
// Inflate the layout for this fragment
return view
}
#OnItemClick(R.id.contacts_lv)
fun onItemClick(parent: AdapterView<?>, position){
var hm_element: HashMap<String,String> = al.get(position)
var name: String = hm_element.get(LoadAllContacts.keys[0])
var number: String = hm_element.get(LoadAllContacts.keys[1])
}
}
following is java code
public class LoadAllContacts {
//parameter to import
private ContentResolver contentResolver;
private Context context;
public static ArrayList al=null;
private Cursor cursor_Android_Contacts = null;
public static final String[] keys = {"name"};
public static final int[] ids = {R.id.contact_name};
public LoadAllContacts( ContentResolver contentResolver, Context context) {
this.contentResolver = contentResolver;
this.context = context;
}
public ArrayList loadContacts() {
al = new ArrayList();
//to get connection to database in android we use content resolver
//get all contacts
try {
//sort the list while taking contact_id itself
cursor_Android_Contacts = contentResolver.query(ContactsContract.Contacts.CONTENT_URI,
null,
null,
null,
ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " ASC");
} catch (Exception e) {
Log.e("error in contact", e.getMessage());
}
//check if it has contacts
if (cursor_Android_Contacts.getCount() > 0) {
if (cursor_Android_Contacts.moveToFirst()) {
do {
//get the object of class android contact to store values and string to get the data from android database
HashMap hm = new HashMap();
String contact_id = cursor_Android_Contacts.getString(
cursor_Android_Contacts.getColumnIndex(
ContactsContract.Contacts._ID));
String contact_display_name = cursor_Android_Contacts.getString(cursor_Android_Contacts.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
hm.put(keys[0], contact_display_name);
int hasPhoneNumber = Integer.parseInt(cursor_Android_Contacts.getString(cursor_Android_Contacts.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER)));
if (hasPhoneNumber > 0) {
Cursor phoneCursor = contentResolver.query(
ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
ContactsContract.CommonDataKinds.Phone.CONTACT_ID + " =? ",
new String[]{contact_id},
null
);
if (phoneCursor.moveToFirst()) {
String phoneNumber = phoneCursor.getString(phoneCursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
//hm.put(keys[1], phoneNumber);
}
phoneCursor.close();
}
al.add(hm);
} while (cursor_Android_Contacts.moveToNext());
}
return al;
}
return al;
}
}
kotlin.collections.ArrayList is just a typealias for java.util.ArrayList on JVM, so you can pass one where the other is expected.
A problem here can be in the fact that you use raw ArrayList type in Java. In Kotlin it will be seen as ArrayList<*>, i.e. parametrized by an unknown type and therefore it won't be assignable to ArrayList<HashMap<String, String>>.
In this case you either have to use an unchecked cast in Kotlin:
al = loadContacts() as ArrayList<HashMap<String, String>>
Or - that's better - you should specify type parameters in your Java method:
public ArrayList<HashMap<String, String>> loadContacts() { ... }

search a value from sqlite always return empty result

Hi I'm trying to add the preferred option to my application I started with sqlite to save the URL of the image but I have a problem when adding image url to favorite by this code :
public void AddtoFavorite(Post pj) {
SQLiteDatabase db = getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_IMAGE_CATNAME, pj.getName());
values.put(KEY_IMAGE_URL, pj.getImgUrl());
db.insert(TABLE_NAME, null, values);
db.close();
}
It is added successfully but when i want to check if image url exist in database or not
public List<Post> getFavRow(String url) {
List<Post> dataList = new ArrayList();
#SuppressLint("Recycle") Cursor cursor = getWritableDatabase().rawQuery("SELECT * FROM Favorite WHERE imageurl = '" + url + "'", null);
if (cursor.moveToFirst()) {
do {
Post contact = new Post();
contact.setName(cursor.getString(0));
contact.setImgUrl(cursor.getString(1));
dataList.add(contact);
} while (cursor.moveToNext());
}
return dataList;
}
always i get empty list as result.
You should use getReadableDatabase() instead of getWritableDatabase() in your getFavRow() function
SQLiteDatabase db = this.getReadableDatabase();
Try
WHERE imageurl LIKE '%" + url + "%'"
Try this
public List<Post> getFavRow(String url) {
List<Post> dataList = new ArrayList();
String[] selectQuery = {"YOUR", "TABLE", "COLUMNS"};
String selection = "IMAGEURL = ?";
String[] selectionArgs = {url};
Cursor cursor = database.query(yourTable, selectQuery, selection, selectionArgs, null, null, null);
while(cursor.moveToNext()){
Post contact = new Post();
contact.setName(cursor.getString(cursor.getColumnIndex("NAME")));
contact.setImgUrl(cursor.getString(cursor.getColumnIndex("IMAGEURL")));
dataList.add(contact);
}
cursor.close();
return dataList;
}

how to insert string[] array into MySQL database?

I am new in android development i want to insert call log details in MySQL database. so, from android side i am getting an arrayList and i have converted that list into string[] array but i am not able to insert this array in database here i am insert the whole data with HashMap<String,Array>. but hashsmap is not able to take array arguement as string[] array. plz help to sort out this problem thanks in advance
here is java code..
public class MainActivity extends AppCompatActivity {
ArrayList<String> arrayList;
String phNum,callType,samay,callDuration;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView animalList=(ListView)findViewById(R.id.listView);
arrayList = new ArrayList<String>();
getCallDetails();
// Create The Adapter with passing ArrayList as 3rd parameter
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, arrayList);
// Set The Adapter
animalList.setAdapter(arrayAdapter);
}
private void getCallDetails() {
String strOrder = android.provider.CallLog.Calls.DATE + " DESC";
/* Query the CallLog Content Provider */
Cursor managedCursor = managedQuery(CallLog.Calls.CONTENT_URI, null,
null, null, strOrder);
int number = managedCursor.getColumnIndex(CallLog.Calls.NUMBER);
int type = managedCursor.getColumnIndex(CallLog.Calls.TYPE);
int date = managedCursor.getColumnIndex(CallLog.Calls.DATE);
int duration = managedCursor.getColumnIndex(CallLog.Calls.DURATION);
while (managedCursor.moveToNext()) {
phNum = managedCursor.getString(number);
String callTypeCode = managedCursor.getString(type);
String strcallDate = managedCursor.getString(date);
Date callDate = new Date(Long.valueOf(strcallDate));
samay = callDate.toString();
callDuration = managedCursor.getString(duration);
callType = null;
int callcode = Integer.parseInt(callTypeCode);
switch (callcode) {
case CallLog.Calls.OUTGOING_TYPE:
callType = "Outgoing";
break;
case CallLog.Calls.INCOMING_TYPE:
callType = "Incoming";
break;
case CallLog.Calls.MISSED_TYPE:
callType = "Missed";
break;
}
arrayList.add(phNum);
arrayList.add(callDuration);
arrayList.add(callType);
arrayList.add(samay);
}
managedCursor.close();
/*String[] array = new String[arrayList.size()];
array = arrayList.toArray(array);
for(String s : array)
{Log.d("TAG",s);}*/
final String[] data = arrayList.toArray(new String[arrayList.size()]);
final java.sql.Array sqlArray = Connection.createArrayOf("VARCHAR", data);
class getCallDetails extends AsyncTask<Void, Void, String> {
#Override
protected String doInBackground(Void... params) {
HashMap<String, Array> param = new HashMap<String, Array>();
param.put(Connect.KEY_ARRAY, sqlArray );
RequestHandler rh = new RequestHandler();
String res = rh.sendPostRequest(Connect.URL_ADD, param);
return res;
}
}
getCallDetails idata = new getCallDetails();
idata.execute();
}
}
here i have tried to convert string[] array into java.sql array but Connection.createArrayOf() shows error of non-static method can not be referenced from a static context.
First create a POJO class to store the data,
private class ContactData {
String phNum;
String callDuration;
String callType;
String samay;
public ContactData(String phNum, String callDuration, String callType, String samay) {
this.phNum = phNum;
this.callDuration = callDuration;
this.callType = callType;
this.samay = samay;
}
// getters and setters
}
Create a List before the while loop and insert data into this inside the loop,
List<ContactData> items = new ArrayList<String>();
while (managedCursor.moveToNext()) {
...
items.add(new ContactData(phNum, callDuration, callType, samay));
}
Use GSON library to convert ArrayList to JSON.
String listOfItems = new Gson().toJson(items);
Post this data to server. See here how to do this.

How to load ArrayList data into ListView using Android?

I am trying to create JSON data store into ArrayList and load on ListView. Now I have successfully stored my JSON data into ArrayList. But the problem is I have maintaining multiple column listview. I need to List out my first array on first column.
Below I have tried something, multiple columns with array. But exactly I dont know how to do that. Please help me, I am new developer for Android.
// I need to add my array into first column
private ArrayList<String> myarray = new ArrayList<String>();
//JSON string data's I have loaded
myarray.add(jsondata);
//LISTVIEW WATCHLIST
ListView listView=(ListView)findViewById(R.id.listView1);
list=new ArrayList<HashMap<String,String>>();
HashMap<String,String> temp=new HashMap<String, String>();
temp.put(FIRST_COLUMN, "Minchu");
temp.put(SECOND_COLUMN, "USA");
temp.put(THIRD_COLUMN, "City");
temp.put(FOURTH_COLUMN, "Ranks");
list.add(temp);
.
.
.
.
ListViewAdapters adapter=new ListViewAdapters(this,list);
listView.setAdapter(adapter);
NOTE : Above HashMap to putted manual data. I need to load first array first columns, second array second columns.
You need to create model for your json object see below code.
import java.io.Serializable;
public class PersonDetailsItem implements Serializable {
public int id;
private String intEducationEN, intVillageID;
public PersonDetailsItem(int id, String name, String phoneNo, String email) {
// TODO Auto-generated constructor stub
this.id = id;
this.strNameEN = name;
this.strEmailid = email;
}
public String getIntVillageID() {
return intVillageID;
}
public void setIntVillageID(String intVillageID) {
this.intVillageID = intVillageID;
}
public String getIntEducationEN() {
return intEducationEN;
}
public void setIntEducationEN(String intEducationEN) {
this.intEducationEN = intEducationEN;
}
public PersonDetailsItem() {
// TODO Auto-generated constructor stub
}
Then set the value for the model form parsing json received string.
private void parseJson(String rs) {
private ArrayList<PersonDetailsItem> listData = new ArrayList<PersonDetailsItem>();;
// TODO Auto-generated method stub
listData = new ArrayList<PersonDetailsItem>();
spinerPersonData = new ArrayList<SpinerItem>();
try {
JSONObject obj = new JSONObject(rs);
JSONArray jArray = obj.getJSONArray("Table");
for (int i = 0; i < jArray.length(); i++) {
JSONObject c = jArray.optJSONObject(i);
String intEducationEN = c.getString("intEducationEN");
String intVillageID = c.getString("intVillageID");
PersonDetailsItem personItem = new PersonDetailsItem();
personItem.setIntEducationEN(intEducationEN);
personItem.setIntVillageID(intVillageID);
listData.add(personItem);
}
} catch (JSONException e) { // TODO Auto-generated catch block
e.printStackTrace();
Log.v("perosnJson Error", e.toString());
}
}
set to listadapter
CustomAdapter adapter = new CustomAdapter(MainActivity.this, R.id.listView1, listData);
lv.setAdapter(adapter);
adapter.notifyDataSetChanged();
enter code here
You can check link for more detail https://github.com/yagneshshinde101/mysamaj/blob/master/MySamaj/src/com/example/mysamajmain/MainActivity.java

ParseObject as a data to the table/chart

I'm new in coding and I have a problem to understand something. I follow the example form Parse.com Doc and wrote this.
public void getData() {
ParseQuery<ParseObject> query = ParseQuery.getQuery("ParseClass");
query.getInBackground("lxFzCTeOcl", new GetCallback<ParseObject>() {
public void done(ParseObject parseObject, ParseException e) {
if (e == null) {
String object = parseObject.getString("value");
int object_value = Integer.parseInt(obiect);
} else {
Log.d("score", "Error: " + e.getMessage());
}
}
});
}
I understand this like:
I send query to server
get obiect with "lxFzCTeOcl" id
if there is no exception I create String object which takes string
form "value" column.
convert String to int
My question is: How can I use object_value for example to make a chart or put it into a table?
Here we will add the array list to your code and start to store an object inside the array every time we call the getData method in your class.
private ArrayList<Integer> dataArray;
public void getData() {
ParseQuery<ParseObject> query = ParseQuery.getQuery("ParseClass");
query.getInBackground("lxFzCTeOcl", new GetCallback<ParseObject>() {
public void done(ParseObject parseObject, ParseException e) {
if (e == null) {
String object = parseObject.getString("value");
Integer objectValue = Integer.parseInt(obiect);
if(dataArray==null)
dataArray = new ArrayList<Integer>();
dataArray.add(objectValue);
} else {
Log.d("score", "Error: " + e.getMessage());
}
}
});
}
And here I'm just adding a simple example of how to create a simple pie chart using our array list (note that I used the lib AChartEngine http://www.achartengine.org/):
private static int[] COLORS = new int[] { Color.GREEN, Color.BLUE,Color.MAGENTA, Color.CYAN };
private GraphicalView createPieChart(ArrayList<Integer> data){
GraphicalView chartView;
CategorySeries series = new CategorySeries("PIE");
for (int i = 0; i < VALUES.length; i++) {
series.add(i, data.get(i));
SimpleSeriesRenderer renderer = new SimpleSeriesRenderer();
renderer.setColor(COLORS[(series.getItemCount() - 1) % COLORS.length]);
mRenderer.addSeriesRenderer(renderer);
}
chartView = ChartFactory.getPieChartView(this, series, new DefaultRenderer());
chartView.repaint();
return chartView;
}
Now you can add this GraphicalView to your view.
The returned object is much like a map, with key/value pairs. In your example, the key is "value", which makes it a little confusing, but it would be like this if you wanted all fields:
for (Field field : myInstance.getClass().getDeclaredFields()) {
String name = field.getName();
value = field.get(myInstance).toString();
map.put(name, value);
}

Categories