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() { ... }
Related
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();
}
}
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.
The problem is this adapter is giving the error although i have pass the Object array to it.(Read the methods belows then you will find what i want to know from you guys)
This method declares a List of private class objects. Then return that list of object to onPostExecute method.
private class DownloadXmlTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
try {
return loadXmlFromNetwork(urls[0]);
} catch (IOException e) {
return "I/O exception ae hy";
} catch (XmlPullParserException e) {
return "XML pull parser ke exception ae hy";
}
}
#Override
protected void onPostExecute(List<StackOverflowXmlParser.Entry> result) {
//Log.d(TAG,result.toString());
ArrayAdapter<String> adapter;
adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,result);
setListAdapter(adapter);
}
private Object loadXmlFromNetwork(String urlString) throws XmlPullParserException, IOException {
InputStream stream = null;
// Instantiate the parser
StackOverflowXmlParser stackOverflowXmlParser = new StackOverflowXmlParser();
List<StackOverflowXmlParser.Entry> entries = null;
String title = null;
String url = null;
String summary = null;
try {
stream = downloadUrl(urlString);
entries = stackOverflowXmlParser.parse(stream);
} finally {
if (stream != null) {
stream.close();
}
}
for (StackOverflowXmlParser.Entry entry : entries)
{
Log.d(TAG, entry.link + " /" + entry.title);
}
return entries;
}
I think it should be onPostExecute(List<StackOverflowXmlParser.Entry> result)
And you AsyncTask should be
extends AsyncTask<smth, smth, List<StackOverflowXmlParser.Entry> >
ArrayAdapter<String> requires that you provide it a String[] or a List<String>. You are trying to pass in Object[], which is neither String[] nor List<String>. And, it would appear that you are really trying to populate the ListView with a list of StackOverflowXmlParser.Entry objects, which are not String objects.
My guess is that the right answer is for you to create an ArrayAdapter<StackOverflowXmlParser.Entry> instead of an ArrayAdapter<String>.
Regardless, you need to ensure that the data type in your declaration (String in ArrayAdapter<String>) matches the data type in your constructor parameter that supplies the data to be adapted.
I have a json parse like this
public class SecondFragment extends Fragment implements OnClickListener {
// URL to get contacts JSON
private static String contestUrl = "http://api.apps.com/contest";
// JSON Node names
private static final String TAG_ITEM_ID = "id";
private static final String TAG_URL = "url";
private static final String TAG_START_DATE = "start_date";
private static final String TAG_END_DATE = "end_date";
// contacts JSONArray
JSONArray foods = null;
// Hashmap for ListView
ArrayList<HashMap<String, String>> foodslist;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onActivityCreated(savedInstanceState);
foodslist = new ArrayList<HashMap<String, String>>();
// Calling async task to get json
new GetContacts().execute();
}
/**
* Async task class to get json by making HTTP call
* */
private class GetContacts 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(contestUrl, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
foods = new JSONArray(jsonStr);
// looping through All Contacts
for (int i = 0; i < foods.length(); i++) {
JSONObject c = foods.getJSONObject(i);
String id = c.getString(TAG_ITEM_ID);
String name = c.getString(TAG_URL);
String email = c.getString(TAG_START_DATE);
String address = c.getString(TAG_END_DATE);
// tmp hashmap for single contact
HashMap<String, String> contact = new HashMap<String, String>();
// adding each child node to HashMap key => value
contact.put(TAG_ITEM_ID, id);
contact.put(TAG_URL, name);
contact.put(TAG_START_DATE, email);
contact.put(TAG_END_DATE, address);
String start_date = (String)contact.get(TAG_ITEM_ID);
// adding contact to contact list
foodslist.add(contact);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
}
}
I have two function, onCreate and GetContacts. In the end of onCreate it call GetContacts and call this json.
My question is, how can I got the Hashmap value on GetContacts so I can use it on onCreate
So far, I got this to get the value of Hashmap
String start_date = (String)contact.get(TAG_ITEM_ID);
But, its only works on GetContacts.
Anyone can help me?
Thanks Before
There are couple of ways:
Way-1:
Create instance variable (class-level) of HashMap contact and then you can use it anywhere within class inclusing onCreate and getContacts method.
package stackoverflow.q_25034927;
import java.util.HashMap;
import java.util.Map;
public class PassVariable {
private static Map<String, String> contact = new HashMap<String, String>();
public void onCreate() {
//populate contact object as per your logic
getContacts();
}
private void getContacts() {
//Use contact object directly which was pre-populby onCreate method.
}
}
Way-2:
Pass map to the getContacts() method:
package stackoverflow.q_25034927;
import java.util.HashMap;
import java.util.Map;
public class PassVariable {
public void onCreate() {
final Map<String, String> contact = new HashMap<String, String>();
//populate contact object as per your logic.
getContacts(contact);
}
private void getContacts(Map<String, String> contact) {
//Use contact object which is passed as argument.
}
}
On other side, please use cameCasing while naming Java methods or variables. GetContacts is not right, make it getContacts.
For email and address fields, using TAG_START_DATE and TAG_END_DATE is no fun. :-)
String email = c.getString(TAG_START_DATE);
String address = c.getString(TAG_END_DATE);
To answer about #3 below, variable s is not accessible in NotInner class:
package com.test;
public class Test {
static String s = "";
}
class NotInner {
public static void main(String[] args) {
System.out.println(s); //Compilation error: s cannot be resolved to a variable
}
}
You have
List<Map<String,String>> foodslist = ...;
which is filled in the loop.
To get at individual values, iterate:
for( Map<String,String> item: foodslist ){
String id = item.get(TAG_ITEM_ID);
String name = item.get(TAG_URL);
String email = item.get(TAG_START_DATE);
String address = item.get(TAG_END_DATE);
}
Or you write a method for the class where you keep foodslist:
String getAttr( int i, String tag ){
return foodslist.get(i).get(tag);
}
and you can call
String id = xxx.getAttr( i, TAG_ITEM_ID );
So return the data ...
public List<Map<String, String>> getContacts() {
if (foodslist != null && foodslist.isEmpty()) {
return foodslist;
}
foodslist = new ArrayList<Map<String, String>>();
try {
foods = new JSONArray(jsonStr);
// looping through All Contacts
for (int i = 0; i < foods.length(); i++) {
JSONObject c = foods.getJSONObject(i);
String id = c.getString(TAG_ITEM_ID);
String name = c.getString(TAG_URL);
String email = c.getString(TAG_START_DATE);
String address = c.getString(TAG_END_DATE);
// tmp hashmap for single contact
HashMap<String, String> contact = new HashMap<String, String>();
// adding each child node to HashMap key => value
contact.put(TAG_ITEM_ID, id);
contact.put(TAG_URL, name);
contact.put(TAG_START_DATE, email);
contact.put(TAG_END_DATE, address);
// adding contact to contact list
foodslist.add(contact);
}
return foodslist;
}
Though I'm not sure why that variable is called foodslist if it's supposed to contain contacts.
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);
}