array from android java - java

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

Related

Rest API with JsonArray

I am using JsonArray as input in my REST API. Here I attached my coding part.
After deployment I getting input value as null or internal server error or glass-fish error. Kindly suggest some ideas to resolve this issue.
I tried to change #Consumes(MediaType.APPLICATION_JSON) to #Consumes("application/json") and also command the #XmlRootElement annotation.
This is TransactionData.java class:
#Path("/CreditProcess")
public class TransactionData {
//private Object ipxml;
#POST
#Path("/SOHold")
//#Consumes("application/json")
#Consumes(MediaType.APPLICATION_JSON)
#Produces(MediaType.APPLICATION_JSON)
public TransactionDataResponse Serv(TransactionDataRequest req) throws IOException, JPISException, Exception {
String Status = null, ErrorCode = null;
TransactionDataResponse ObjRes = new TransactionDataResponse();
CommonFunction ObjCF = new CommonFunction();
String SessionId = "";
boolean boolREADINI;
String Webservice = "Hold_Creation";
boolREADINI = ObjCF.ReadINIProperties();
String MISC_ID = "";
String PID = "", SaleOrder = "", Hold_Type = "", Hold_Status = "",
Approved_User = "", Date = "", Remarks = "", Hold_Desc = "", SO_COUNT = "", CH_COUNT = "", flag = "",WorkitemID="";
String Output_data = "", Input_data = "";
DMSXmlResponse Query_Response = null;
SessionId = ObjCF.ConnectCabinet(Webservice);
// PID = req.get();
ObjCF.ReportLog("Input_data request---" + req, Webservice);
JSONArray Data = new JSONArray();
try {
ObjCF.ReportLog("Before Check1---", Webservice);
Data = req.getData();
ObjCF.ReportLog("After Check2---"+Data, Webservice);
int size = Data.size();
for (int row = 0; row < size; row++) {
ObjCF.ReportLog("test1--", Webservice);
JSONObject obj;
HashMap<String, String> passedValues = (HashMap<String, String>) Data.get(row);
ObjCF.ReportLog("test2-- ", Webservice);
// ObjCF.ReportLog("test2--Data.get(i)" + Data.get(i), Webservice);
// obj = (JSONObject) Data.get(i);
for (Entry<String, String> mapTemp : passedValues.entrySet()) {
if (mapTemp.getKey().equalsIgnoreCase("SalesOrder")) {
SaleOrder = mapTemp.getValue();
ObjCF.ReportLog("json SaleOrder" + SaleOrder, Webservice);
} else if (mapTemp.getKey().equalsIgnoreCase("Hold_Type")) {
Hold_Type = mapTemp.getValue();
ObjCF.ReportLog("json Hold_Type" + Hold_Type, Webservice);
} else if (mapTemp.getKey().equalsIgnoreCase("Hold_status")) {
Hold_Status = mapTemp.getValue();
ObjCF.ReportLog("json SaleOrder" + Hold_Status, Webservice);
} else if (mapTemp.getKey().equalsIgnoreCase("Approved_User")) {
Approved_User = mapTemp.getValue();
ObjCF.ReportLog("json Approved_User" + Approved_User, Webservice);
} else if (mapTemp.getKey().equalsIgnoreCase("Date_Time")) {
Date = mapTemp.getValue();
ObjCF.ReportLog("json Date" + Date, Webservice);
} else if (mapTemp.getKey().equalsIgnoreCase("Remarks")) {
Remarks = mapTemp.getValue();
ObjCF.ReportLog("json Remarks" + Remarks, Webservice);
} else if (mapTemp.getKey().equalsIgnoreCase("Hold_status_Desc")) {
Hold_Desc = mapTemp.getValue();
ObjCF.ReportLog("json Hold_Desc" + Hold_Desc, Webservice);
}
}
}
} catch(Exception e){
}
}
}
This is my TransactionDataRequest.java class:
import com.newgen.Utils.CommonFunction;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import org.json.simple.JSONArray;
#XmlRootElement
public class TransactionDataRequest {
private JSONArray Data;
CommonFunction ObjCF = new CommonFunction();
public JSONArray getData() {
ObjCF.ReportLog("Inside getData---", "Hold_Creation");
ObjCF.ReportLog("Inside getData return data---" + Data, "Hold_Creation");
return Data;
}
#XmlElement(name = "Data")
public void setData( JSONArray Data) {
ObjCF.ReportLog("Inside Data:---" + Data, "Hold_Creation");
this.Data = Data;
ObjCF.ReportLog("After this Data:---" + Data, "Hold_Creation");
}
}

Change variable inside async call

I am trying to parse the response I get from my OkHttp3Connection and it always almost always returns me String with value "true" which is names[0] in this example.
Now I try to convert this string to boolean and return true/false depending on the response. Now I guess since the OkHttp3Connection takes some time it doesnt let the query to finish and returns false which is the default value.
What I was trying to say is that this function always returns false no matter what String names[0] is.
public boolean checkIfSongPurhcased(String songName){
final boolean[] songCheckResult = new boolean[1];
OkHttp3Connection.doOkHttp3Connection("", Services_Url_class.GET_SONG_PURCHASED, OkHttp3Connection.Request_type.POST, request_data, new OkHttp3Connection.OkHttp3RequestCallback() {
#Override
public void onSuccess(String result, String userTag) throws JSONException {
JSONObject jsonResult = new JSONObject(result);
JSONArray data = jsonResult.getJSONArray("data");
if(data != null) {
String[] names = new String[data.length()];
for(int i = 0 ; i < data.length() ; i++) {
JSONArray arr = data.getJSONArray(i);
JSONObject dataObj = arr.getJSONObject(0);
Iterator<String> keys = dataObj.keys();
names[i] = dataObj.getString(keys.next());
}
//names[0] is "true"
songCheckResult[0] = Boolean.parseBoolean(names[0]);
}
}
#Override
public void onError(String error, String userTag) {
System.out.println("songy" + error);
}
}
);
//always returns false
return songCheckResult[0];
How can I make it so if names[0] is "true" it would give me true.
You should pass the listener/callback.
First create callback interface like below
public interface OnQueryResultCallback{
void onQueryResult(String songName, boolean status);
}
Then pass listener/callback to your method, here is the modified method.
public void checkIfSongPurhcased(final String songName, final OnQueryResultCallback listener){
OkHttp3Connection.doOkHttp3Connection("", Services_Url_class.GET_SONG_PURCHASED, OkHttp3Connection.Request_type.POST, request_data, new OkHttp3Connection.OkHttp3RequestCallback() {
#Override
public void onSuccess(String result, String userTag) throws JSONException {
JSONObject jsonResult = new JSONObject(result);
JSONArray data = jsonResult.getJSONArray("data");
if(data != null) {
String[] names = new String[data.length()];
for(int i = 0 ; i < data.length() ; i++) {
JSONArray arr = data.getJSONArray(i);
JSONObject dataObj = arr.getJSONObject(0);
Iterator<String> keys = dataObj.keys();
names[i] = dataObj.getString(keys.next());
}
//names[0] is "true"
boolean status = Boolean.parseBoolean(names[0]);
listener.onQueryResult(songName,status);
}
}
#Override
public void onError(String error, String userTag) {
System.out.println("songy" + error);
listener.onQueryResult(songName,false);
}
}
);
}
Then call checkIfSongPurhcased like below
checkIfSongPurhcased("songName", new OnQueryResultCallback(){
public void onQueryResult(String songName, boolean status){
if(status){
// do something on success
}else{
// do something on failure
}
}
});
Try to use getBoolean() rather than getString().
For Eg: names[i] = dataObj.getBoolean(keys.next());

org.json.JSONException: Value OR-12345 at order_no of type java.lang.String cannot be converted to int

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.

Using array as key for hashmap java

i have a method that puts some value(obtained from an excel file) into a hashmap with an array as the key
public HashMap<List<String>, List<String[]>> sbsBusServiceDataGnr() throws
IOException
{
System.out.println(engine.txtY + "Processing HashMap "
+ "sbsBusServiceData..." + engine.txtN);
int counterPass = 0, counterFail = 0, stopCounter = 0;
String dataExtract, x = "";
String[] stopInfo = new String[3];
List<String[]> stopsData = new ArrayList<String[]>();
List<String> serviceNum = new Vector<String>();
HashMap<List<String>, List<String[]>> sbsBusServiceData =
new HashMap<List<String>, List<String[]>>();
String dataPath = this.dynamicPathFinder(
"Data\\SBS_Bus_Routes.csv");
BufferedReader sbsBusServiceDataPop = new BufferedReader(
new FileReader(dataPath));
sbsBusServiceDataPop.readLine();
//Skips first line
while ((dataExtract = sbsBusServiceDataPop.readLine()) != null) {
try {
String[] dataParts = dataExtract.split(",", 5);
if (!dataParts[4].equals("-")){
if (Double.parseDouble(dataParts[4]) == 0.0){
sbsBusServiceData.put(serviceNum, stopsData);
String serviceNum1 = "null", serviceNum2 = "null";
if(!serviceNum.isEmpty()){
serviceNum1 = serviceNum.get(0);
serviceNum2 = serviceNum.get(1);
}
System.out.println("Service Number " + serviceNum1
+ ":" + serviceNum2 + " with " + stopCounter
+ " stops added.");
stopCounter = 0;
//Finalizing previous service
serviceNum.Clear();
serviceNum.add(0, dataParts[0]);
serviceNum.add(1, dataParts[1]);
//Adding new service
}
}
stopInfo[0] = dataParts[2];
stopInfo[1] = dataParts[3];
stopInfo[2] = dataParts[4];
stopsData.add(stopInfo);
//Adding stop to service
stopCounter++;
counterPass++;
}
catch (Exception e) {
System.out.println(engine.txtR + "Unable to process "
+ dataExtract + " into HashMap sbsBusServiceData."
+ engine.txtN + e);
counterFail++;
}
}
sbsBusServiceDataPop.close();
System.out.println(engine.txtG + counterPass + " number of lines"
+ " processed into HashMap sbsBusServiceData.\n" + engine.txtR
+ counterFail + " number of lines failed to process into "
+ "HashMap sbsBusServiceData.");
return sbsBusServiceData;
}
//Generates sbsBusServiceDataGnr HashMap : 15376 Data Rows
//HashMap Contents: {ServiceNumber, Direction},
// <{RouteSequence, bsCode, Distance}>
this method work for putting the values into the hashmap but i cannot seem to get any value from the hashmap when i try to call it there is always a nullpointerexception
List<String> sbsTest = new Vector<String>();
sbsTest.add(0, "10");
sbsTest.add(1, "1");
System.out.println(sbsBusServiceData.get(sbsTest));
try{
List<String[]> sbsServiceResults = sbsBusServiceData.get(sbsTest);
System.out.println(sbsServiceResults.size());
String x = sbsServiceResults.get(1)[0];
System.out.println(x);
} catch(Exception e){
System.out.println(txtR + "No data returned" + txtN + e);
}
this is a sample of the file im reading the data from:
SBS
How can i get the hashmap to return me the value i want?
Arrays are not suitable as keys in HashMaps, since arrays don't override Object's equals and hashCode methods (which means two different array instances containing the exact same elements will be considered as different keys by HashMap).
The alternatives are to use a List<String> instead of String[] as the key of the HashMap, or to use a TreeMap<String[]> with a custom Comparator<String[]> passed to the constructor.
If you are having fixed array size then the example I'm posting might be useful.
Here I've created two Object one is Food and Next is Product.
Here Food object is use and added method to get string array.
public class Product {
private String productName;
private String productCode;
public Product(String productName, String productCode) {
this.productName = productName;
this.productCode = productCode;
}
public String getProductName() {
return productName;
}
public void setProductName(String productName) {
this.productName = productName;
}
public String getProductCode() {
return productCode;
}
public void setProductCode(String productCode) {
this.productCode = productCode;
}
}
Food Model Class: Use as a Object instead of String[] and achieve String[] functionality.
public class Food implements Comparable<Food> {
private String type;
private String consumeApproach;
public Food(String type, String consumeApproach) {
this.type = type;
this.consumeApproach = consumeApproach;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getConsumeApproach() {
return consumeApproach;
}
public void setConsumeApproach(String consumeApproach) {
this.consumeApproach = consumeApproach;
}
public String[] FoodArray() {
return new String[] { this.type, this.consumeApproach };
}
//Implement compareTo method as you want.
#Override
public int compareTo(Food o) {
return o.getType().compareTo(this.type);
}
}
Using HashMap example
public class HashMapKeyAsArray {
public static void main(String[] args) {
HashMap<Food,List<Product>> map = dataSetLake();
map.entrySet().stream().forEach(m -> {
String[] food = m.getKey().FoodArray();
Arrays.asList(food).stream().forEach(f->{
System.out.print(f + " ");
});
System.out.println();
List<Product> list = m.getValue();
list.stream().forEach(e -> {
System.out.println("Name:" + e.getProductName() + " Produc Code:" + e.getProductCode());
});
System.out.println();
});
}
private static HashMap<Food,List<Product>> dataSetLake(){
HashMap<Food,List<Product>> data = new HashMap<>();
List<Product> fruitA = new ArrayList<>();
fruitA.add(new Product("Apple","123"));
fruitA.add(new Product("Banana","456"));
List<Product> vegetableA = new ArrayList<>();
vegetableA.add(new Product("Potato","999"));
vegetableA.add(new Product("Tomato","987"));
List<Product> fruitB = new ArrayList<>();
fruitB.add(new Product("Apple","123"));
fruitB.add(new Product("Banana","456"));
List<Product> vegetableB = new ArrayList<>();
vegetableB.add(new Product("Potato","999"));
vegetableB.add(new Product("Tomato","987"));
Food foodA = new Food("Fruits","Read To Eat");
Food foodB = new Food("Vegetables","Need To Cook");
Food foodC = new Food("VegetablesC","Need To Cook C");
data.put(foodA, fruitB);
data.put(foodB, vegetableB);
data.put(foodA, fruitA);
data.put(foodC, vegetableA);
return data;
}
Using TreeMap example
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.TreeMap;
public class TreeMapKeyAsArray {
public static void main(String[] args) {
TreeMap<Food, List<Product>> map = dataSetLake();
map.entrySet().stream().forEach(m -> {
String[] food = m.getKey().FoodArray();
Arrays.asList(food).stream().forEach(f->{
System.out.print(f + " ");
});
System.out.println();
List<Product> list = m.getValue();
list.stream().forEach(e -> {
System.out.println("Name:" + e.getProductName() + " Produc Code:" + e.getProductCode());
});
System.out.println();
});
}
private static TreeMap<Food, List<Product>> dataSetLake() {
TreeMap<Food, List<Product>> data = new TreeMap<>();
List<Product> fruitA = new ArrayList<>();
fruitA.add(new Product("Apple", "123"));
fruitA.add(new Product("Banana", "456"));
List<Product> vegetableA = new ArrayList<>();
vegetableA.add(new Product("Potato", "999"));
vegetableA.add(new Product("Tomato", "987"));
List<Product> fruitB = new ArrayList<>();
fruitB.add(new Product("Apple", "123"));
fruitB.add(new Product("Banana", "456"));
List<Product> vegetableB = new ArrayList<>();
vegetableB.add(new Product("Potato", "999"));
vegetableB.add(new Product("Tomato", "987"));
Food foodA = new Food("Fruits", "Read To Eat");
Food foodB = new Food("Vegetables", "Need To Cook");
data.put(foodA, fruitB);
data.put(foodB, vegetableB);
data.put(foodA, fruitA);
data.put(foodB, vegetableA);
return data;
}
}

Getting error when insert birth date into a database

I'm trying to insert contacts details to a MySQL database,
Here is my code :
public void SyncContact(){
ContentResolver cr = getContentResolver();
Cursor phones = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);
JSONArray ja = new JSONArray();
HashMap<String,String> hashmap_contactList = new HashMap<String, String>();
String id="";
String name="";
String mobileNo="";
String emailContact="";
String orgName="";
String title="";
String note="";
String street="";
String dob="";
int i = 0;
while (phones.moveToNext()) {
id = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.CONTACT_ID));
name = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
mobileNo = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
Cursor emailCur = cr.query(ContactsContract.CommonDataKinds.Email.CONTENT_URI, null, ContactsContract.CommonDataKinds.Email.CONTACT_ID + " = ?", new String[]{id}, null);
if(emailCur.getCount()>0) {
while (emailCur.moveToNext()) {
emailContact = emailCur.getString(emailCur.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA));
String emailType = emailCur.getString(emailCur.getColumnIndex(ContactsContract.CommonDataKinds.Email.TYPE));
}
}else{
emailContact="";
}
emailCur.close();
String orgWhere = ContactsContract.Data.CONTACT_ID + " = ? AND " + ContactsContract.Data.MIMETYPE + " = ?";
String[] orgWhereParams = new String[]{id,ContactsContract.CommonDataKinds.Organization.CONTENT_ITEM_TYPE};
Cursor orgCur = cr.query(ContactsContract.Data.CONTENT_URI,null, orgWhere, orgWhereParams, null);
if(orgCur.getCount()>0) {
if (orgCur.moveToFirst()) {
orgName = orgCur.getString(orgCur.getColumnIndex(ContactsContract.CommonDataKinds.Organization.DATA));
title = orgCur.getString(orgCur.getColumnIndex(ContactsContract.CommonDataKinds.Organization.TITLE));
}
}else{
orgName="";
title="";
}
orgCur.close();
String[] noteWhereParams = new String[]{id,ContactsContract.CommonDataKinds.Note.CONTENT_ITEM_TYPE};
Cursor noteCur = cr.query(ContactsContract.Data.CONTENT_URI, null, orgWhere, noteWhereParams, null);
if(noteCur.getCount()>0) {
if (noteCur.moveToFirst()) {
note = noteCur.getString(noteCur.getColumnIndex(ContactsContract.CommonDataKinds.Note.NOTE));
}
}else{
note="";
}
noteCur.close();
String[] addrWhereParams = new String[]{id,ContactsContract.CommonDataKinds.StructuredPostal.CONTENT_ITEM_TYPE};
Cursor addrCur = cr.query(ContactsContract.Data.CONTENT_URI,null, orgWhere, addrWhereParams, null);
if(addrCur.getCount()>0){
while(addrCur.moveToNext()) {
street = addrCur.getString(addrCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredPostal.STREET));
}
}else {
street="";
}
addrCur.close();
String[] selectionArgs = new String[] {id,ContactsContract.CommonDataKinds.Event.CONTENT_ITEM_TYPE};
Cursor dobCur = cr.query(ContactsContract.Data.CONTENT_URI, null, orgWhere, selectionArgs, null);
if(dobCur.getCount()>0) {
if (dobCur.moveToFirst()) {
dob = dobCur.getString(dobCur.getColumnIndex(ContactsContract.CommonDataKinds.Event.DATA));
}
}else {
dob="";
}
dobCur.close();
if(!hashmap_contactList.containsKey(name)){
hashmap_contactList.put(name, " ");
System.out.println("!! Contact ID is : " + id);
System.out.println("!! Contact Name is : " + name);
System.out.println("!! Contact Number is : " + mobileNo);
System.out.println("!!prepare Email " + emailContact );
System.out.println("!!prepare Comapny name:" + orgName);
System.out.println("!!prepare Designation :" + title);
System.out.println("!!prepare Note :" + note);
System.out.println("!!prepare Street:" + street);
System.out.println("!!hello dob :" + dob);
try{
JSONObject jsonObject = new JSONObject();
jsonObject.put("contact_uniqueid",id);
jsonObject.put("contact_name",name);
jsonObject.put("contact_number",mobileNo);
jsonObject.put("email",emailContact);
jsonObject.put("oraganization",orgName);
jsonObject.put("job_title",title);
jsonObject.put("address",street);
jsonObject.put("note",note);
jsonObject.put("dob",dob);
ja.put(jsonObject);
mainjson.put("data",ja);
}catch (Exception e){
e.printStackTrace();
}
i++;
}
}
phones.close();
System.out.println("!!json " + mainjson);
try {
Log.d("!!!main_json", mainjson.toString(1));
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ContactSync contactSync = new ContactSync();
contactSync.execute();
}
public class ContactSync extends AsyncTask<String,Void,String>{
String JsonString;
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
HttpPost post = new HttpPost(str_url);
try{
StringEntity entity = new StringEntity(mainjson.toString());
post.setEntity(entity);
post.setHeader("Accept", "application/json");
post.setHeader("Content-type", "application/json");
DefaultHttpClient client = new DefaultHttpClient();
BasicResponseHandler handler = new BasicResponseHandler();
String response = client.execute(post, handler);
System.out.println("!!Response : " + response);
JSONObject jsonObject = new JSONObject(response);
System.out.println("!!Response " + jsonObject);
System.out.println("!! " + jsonObject.getString("data"));
JSONObject success_status = jsonObject.getJSONObject("data");
System.out.println("!!Succes MSg :" + success_status.getString("success"));
if(success_status.getString("success").toString().equalsIgnoreCase("true"))
{
System.out.println("Response after data inserted....."+success_status.getString("success").toString());
CommonFunction.saveSharedPreference(CommonFunction.contactsync_flag, "1", SplashActivity.this);
}
}catch (Exception e){
e.printStackTrace();
System.out.println("!! : "+e.getMessage());
System.out.println("!!!!!!manishhhhhhh......" );
}
return null;
}
protected void onPostExecute(String s) {
super.onPostExecute(s);
}
And the API Code is :
public function temp(){
$_POST = json_decode(file_get_contents('php://input'), true);
$this->load->library('form_validation');
$boolean = TRUE;
$data = array();
$contact_data = $_POST['data'];
$i=0;
foreach($contact_data AS $row){
$fields['contact_uniqueid']=$row['contact_uniqueid'];
$fields['contact_name']=$row['contact_name'];
$fields['contact_number']=$row['contact_number'];
$fields['email']=$row['email'];
$fields['oraganization']=$row['oraganization'];
$fields['job_title']=$row['job_title'];
$fields['address']=$row['address'];
$fields['note']=$row['note'];
$fields['dob']=$row['dob'];
$data[$i] = $fields;
$i++;
}
$this->express_model->set_table('contact_list');
$data_obj = $this->express_model->saveBatch($data);
if ($boolean == TRUE)
{
$final_data['data']['success'] = 'true';
$final_data['data']['message'] = 'Data inserted successfully';
print_r(json_encode($final_data));
}
exit;
}
All contacts details are inserted into the database and I have to get "true" in the JSON response but I'm getting this error:
<div style="border:1px solid #990000;padding-left:20px;margin:0 0 10px 0;">
and I use PHP API written in codeigniter.
check the data type into your database schema and try to insert the appropriate value..
Mostly it happen when we use DateTime data type for fields

Categories