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.
Related
I am making an application where I have String which behaves like Array.
e.g : String name = " "john","kat" ";
I was trying to send them in php server(just sending the string wasn't converting it to array).
<?php
if($_SERVER['REQUEST_METHOD']=='POST'){
$names=array($_POST['name']);
$phones=array($_POST['phone']);
// $names = array("Hw", "V");
// $phones = array("656", "646");
array_map(function ($name, $phone) {
include '../connection.php';
$username=$_POST['username'];
$insert = "INSERT INTO `contact`(`username`, `name`, `contact`) VALUES ('$username','$name','$phone')";
if(mysqli_query($con,$insert)){
}else{
}
}, $names, $phones);
}
?>
It was just inserting these not different strings
database
I request not to comment about SQL Injections. I will work on it later.
private void readContacts(String username){
Cursor c;
ArrayList<HashMap<String, String>> list = new ArrayList<HashMap<String, String>>();
c=getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,null,null,null,ContactsContract.Contacts.DISPLAY_NAME+" ASC ");
int i=0;
String name = "",contact_number="";
while (c.moveToNext()){
//get contact list
String displayName=c.getString(c.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
String number=c.getString(c.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
//put value into Hashmap
HashMap<String, String> user_data = new HashMap<>();
user_data.put(Constant.NAME, displayName);
user_data.put(Constant.PHONE_NUMBER, number);
list.add(user_data);
if (name.isEmpty()){
name = "\""+displayName+"\"";
}else {
name = name + ", " +"\""+ displayName+"\"";
}
if (contact_number.isEmpty()){
contact_number = "\""+number+"\"";
}else{
contact_number = contact_number+ ", " +"\""+ number+"\"";
}
}
Log.d("CONTACTS_NAME", String.valueOf(list));
Log.d("COUNTS_CONTACTS",name);
Log.d("CONTACTS_",contact_number);
if (!name.isEmpty()){
insertContacts(username,name,contact_number);
}
c.close();
}
private void insertContacts(String username,String name,String contactNumber){
ApiInterface apiInterface = ApiClient.getApiClient().create(ApiInterface.class);
Call<Contacts> call = apiInterface.contact(username,name,contactNumber);
call.enqueue(new Callback<Contacts>() {
#Override
public void onResponse(Call<Contacts> call, Response<Contacts> response) {
// String value = response.body().getValue();
// String message = response.body().getMessage();
// Log.d("value",value);
// Log.d("message",message);
}
#Override
public void onFailure(Call<Contacts> call, Throwable t) {
Log.d("ERROR",t.toString());
}
});
}
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() { ... }
I am trying to populate the recycler view using json data from dummy api but it is not working. I have tried almost several solutions given in stack overflow.
Here is my code below:
public class loadOrdersList extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
ordersList = new ArrayList<>();
rvor = findViewById(R.id.recycler_view_orders);
rvor.setHasFixedSize(true);
rvor.setLayoutManager(new LinearLayoutManager(OrdersActivity.this));
}
#Override
protected void onPostExecute(Void aVoid) {
if (new CheckNetworkUtil(OrdersActivity.this).isNetworkAvailable()) {
Log.d("TEST", "------------------ordersList: " + ordersList.size());
OrdersAdapter adapter = new OrdersAdapter(getApplicationContext(), ordersList);
rvor.setAdapter(adapter);
srl.setRefreshing(false);
} else
Toast.makeText(OrdersActivity.this, "No Internet Connection!", Toast.LENGTH_SHORT).show();
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
#Override
protected Void doInBackground(Void... voids) {
try {
OkHttpClient client = new OkHttpClient();
final Request request = new Request.Builder()
.url("https://api.myjson.com/bins/la2gh")
.build();
Response responses = client.newCall(request).execute();
JSONArray orders = new JSONArray(responses.body().string());
ordersList = new ArrayList<>();
for (int i = 0; i < orders.length(); i++) {
JSONObject name = orders.getJSONObject(i);
String customerName = name.getString("customer_name");
String agentAssigned = name.getString("agent_assigned");
String orderId = name.getString("order_id");
Integer totalQuantity = name.getInt("total_quantity");
String orderDate = name.getString("order_date");
Integer orderNo = name.getInt("order_no");
String schoolYear = name.getString("school_year");
String company = name.getString("company");
String deliveryDate = name.getString("delivery_date");
String orderStatus = name.getString("order_status");
Integer grossRevenue = name.getInt("gross_revenue");
Integer netRevenue = name.getInt("net_revenue");
Integer totalOrdered = name.getInt("total");
Integer grandTotalOrdered = name.getInt("grand_total");
OrderModel orderModel = new OrderModel(customerName
,agentAssigned
,orderId
,totalQuantity
,orderDate
,orderNo
,schoolYear
,company
,deliveryDate
,orderStatus
,grossRevenue
,netRevenue
,totalOrdered
,grandTotalOrdered);
ordersList.add(orderModel);
}
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
}
I suspected that integer is not supported by the string during execution.
You are expecting order_no to be an Integer and thus written this
Integer orderNo = name.getInt("order_no");
But you are receiving an alphanumeric value for orderNo in recycler view.
So either you have to change the type of orderNo property of OrderModel from Integer to String or restrict values to Integer type only.
I have an ArrayList called results that uses the class ItemObjects when I want to add an item in results. My problem is that I cannot manage to retrieve a specific String from an item.
The class code is:
public class ItemObjects {
private String mText1;
private String mText2;
public ItemObjects(String text1, String text2){
mText1 = text1;
mText2 = text2;
}
public String getmText1() {
return mText1;
}
public void setmText1(String mText1) {
this.mText1 = mText1;
}
public String getmText2() {
return mText2;
}
public void setmText2(String mText2) {
this.mText2 = mText2;
}
}
And I use the following code to add an item into the ArrayList:
ArrayList results = new ArrayList<ItemObjects>();
//THis part goes inside a for using i as increment;
ItemObjects obj = new ItemObjects(type, sender);
results.add(i , obj);
I have tried several things to retrieve the data such as:
String type = ItemObjects.getmText1();
or:
String type= results.get(i);
the first try, only retrieves the mText1 from the first item, and the second is an object and I dn't know how i should get the mText1 from it.
Any help would be appreciated :)
For adding the Value
ArrayList<ItemObjects> results = new ArrayList<ItemObjects>();
ItemObjects obj = new ItemObjects(type, sender);
results.add(obj);
For getting the Value
for (int i=0, i<result.size(); i++)
{
String type = results.get(i).mText1;
String sender= results.get(i).mText2;
Toast.makeText(this, "" + type, Toast.LENGTH_LONG).show();
Toast.makeText(this, "" + sender, Toast.LENGTH_LONG).show();
}
Change
ArrayList results = new ArrayList<ItemObjects>();
to
ArrayList<ItemObjects> results = new ArrayList<>();
Then results.get() will return ItemObjects.
Or you can simply cast your current result.get() to ItemObjects
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.