How to push data to my index using algolia android - android

I have a problem pushing data to my index. My code is as follows:
Client client = new Client("APP_ID", "SEARCH_ID");
Index myIndex = client.initIndex("test");
JSONObject jsonObject = null;
try {
jsonObject = new JSONObject()
.put("name", "Jimmie")
.put("username", "Barninger")
} catch (JSONException e) {
e.printStackTrace();
}
myIndex.addObjectAsync(jsonObject, null);
However nothing happens, and no data is visible in my dashboard. What am I doing wrong?

I had to change the api keys which previously was SEARCH_ID. I changed it to my ADMIN_API_KEY:
Client client = new Client("APP_ID", "ADMIN_API_KEY");
This is because the search-only API key can only be used for searching, while the Admin API key can change, delete or add an object.
The full code is now:
Client client = new Client("APP_ID", "ADMIN_API_KEY");
Index myIndex = client.initIndex("test");
JSONObject object = null;
try {
object = new JSONObject()
.put("username", "Jimmie")
.put("name", "Barninger");
} catch (JSONException e) {
e.printStackTrace();
}
// myIndex.addObjectAsync(object, "myID", null);
myIndex.addObjectAsync(object, "id", null);

In order to understand more, please replace the addobjectAsync line with something like this:
index.addObjectAsync(object, new CompletionHandler() {
#Override
public void requestCompleted(JSONObject content, AlgoliaException error) {
if (error != null) {
// Check what is the error Here
}
}
}

Related

check playerSSign fail

When verifying the signature, the background server displays {"rtnCode":-1,"errMsg":"check playerSSign fail"}
The data provided by the client is
if(huaweiid != null){
PlayersClient player = Games.getPlayersClient(this, huaweiid);
player.getCurrentPlayer().addOnSuccessListener(new OnSuccessListener<Player>() {
#Override
public void onSuccess(Player player) {
String ts = player.getSignTs();
String playerId = player.getPlayerId();
int playerLevel = player.getLevel();
String playerSign = player.getPlayerSign();
//String displayName = player.getDisplayName();
//Uri hiResImageUri = player.getHiResImageUri();
//Uri iconImageUri = player.getIconImageUri();
JSONObject jo = new JSONObject();
try {
jo.put("signTs", ts);
jo.put("playerId", playerId);
jo.put("playerLevel", playerLevel);
jo.put("playerSign", playerSign);
EditText ed = findViewById(R.id.editText);
ed.setText(jo.toString());
Log.i("huawei user info", jo.toString());
} catch (JSONException e) {
e.printStackTrace();
Log.i("huawei user info", Objects.requireNonNull(e.getMessage()));
}
}
});
}
Use the preceding four data items and the following description document:
https://developer.huawei.com/consumer/cn/doc/HMSCore-References-V5/verify-login-signature-0000001050123503-V5
An error always occurs during the verification in the background.
{"rtnCode":-1,"errMsg":"check playerSSign fail"}
appId/cpid is obtained from agconnect-services.json and agconnect-services.json is downloaded from the background.
what’s the reason?
The following table describes the typical setting errors of the input parameters. Please verify the parameter settings.
https://developer.huawei.com/consumer/cn/doc/development/AppGallery-connect-Guides/faq-check-login-0000001050746133-V5

Forbidden in Call connection Android Pjsip Sip library

How to perform call in Pjsip Android with local server?
I used
User-Agent: Pjsua2 Android 2.6-svn
I made successful registraion after which i tried to call but it throws forbidden(503)
My Registraion Code :
AccountConfig accCfg = new AccountConfig();
accCfg.setIdUri("sip:localhost");
accCfg.getNatConfig().setIceEnabled(true);
accCfg.getVideoConfig().setAutoTransmitOutgoing(true);
accCfg.getVideoConfig().setAutoShowIncoming(true);
//Like 123.12.12.23
accCfg.getRegConfig().setRegistrarUri("sip:172.16.4.124");
AuthCredInfoVector creds = accCfg.getAuthCreds();
creds.clear();
if (username.length() != 0) {
creds.add(new AuthCredInfo("Digest", "*", "abc#172.16.4.124", 0,
"123"));
}
StringVector proxies = accCfg.getSipConfig().getProxies();
proxies.clear();
if (proxy.length() != 0) {
proxies.add("sip:172.16.4.124");
}
accCfg.getSipConfig().setProxies(proxies);
/* Enable ICE */
accCfg.getNatConfig().setIceEnabled(true);
try {
account.add(accCfg);
} catch (Exception e) {
e.printStackTrace();
Log.i(TAG, "Exception in Dialog");
}
}
For Making call I used
public void makeCall(View view) {
if (buddyListSelectedIdx == -1)
return;
/* Only one call at anytime */
if (currentCall != null) {
return;
}
HashMap<String, String> item = (HashMap<String, String>) buddyListView.
getItemAtPosition(buddyListSelectedIdx);
String buddy_uri = item.get("uri");
MyCall call = new MyCall(account, -1);
SendInstantMessageParam param = new SendInstantMessageParam();
param.setContent("Hello Pjsip");
param.setContentType("text");
CallOpParam prm = new CallOpParam(true);
try {
call.makeCall(buddy_uri, prm);
// call.delete();
// call.sendInstantMessage(param);
} catch (Exception e) {
e.printStackTrace();
call.delete();
return;
}
currentCall = call;
showCallActivity();
}
I am able to connect call with sip default client like sip:localhost and other sip provider like linphone but getting forbidden with our server.
Experts please help.
Thanks alot to myself, finally i get the solution after 3 day workout,
had missing portnumber for my amazon server, makes me to get connected and made a sippy call between sip ends.

org.springframework.web.client.HttpClientErrorException: 415 Unsupported Media Type[EDITED]

In Android web service using POST method of REST TEMPLATE, I am trying to send an object to server which contains few parameters and and 2 Objects. Those 2 Objects contains few parameters and 3 Lists of different Objects and each of those 3 Lists of Objects contains few parameters inside them and 1 List of Object that contains a byte array alone. Like in the below pics:
Pic 1[Main Object(The one I am trying to send)]:
Pic 2[Object inside the Main Object comprising 3 Lists of Objects]:
Pic 3[An Object as List comprising 1 List of Another Object inside it, likewise for the other 2(Accommodation & Others)]:
Pic 4[List of Object inside the sub-Object containing a byre array parameter alone]:
And my code for webservice POST method:
public static final String capUrl = "http://192.168.1.7:8084/CAPWS";
public Expenses setExpensesByBatch(Expenses expenses) {
try {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
RestTemplate restTemplate = new RestTemplate();
restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
restTemplate.getMessageConverters().add(new StringHttpMessageConverter());
restTemplate.setRequestFactory(new HttpComponentsClientHttpRequestFactory());
List<HttpMessageConverter<?>> list = new ArrayList<HttpMessageConverter<?>>();
list.add(new MappingJacksonHttpMessageConverter());
restTemplate.setMessageConverters(list);
String b = restTemplate.postForObject(capUrl + "/UX/", expenses, String.class);
Log.e("String ===============b", b + " ++++");
} catch (Exception e) {
e.printStackTrace();
Log.e("expObjPost_WsCli_EX", e.toString());
}
return expenses;
}
Whatever I do it returns org.springframework.web.client.HttpClientErrorException: 415 Unsupported Media Type
My LOGCAT below:
My server side code:
#RequestMapping(value = CapRestURIConstants.UPDATEEXPENSES, method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
public #ResponseBody
String updateExpenses(#RequestBody Expenses expenses) {
String response = "true";
System.out.println("incoming--------" + "UPDATEEXPENSES");
try {
if (expenses != null) {
//System.out.println("expenses--------" + expenses);
int catType = expenses.getCategoryType();
String categoryType = String.valueOf(catType);
String categoryId = expenses.getCategoryId();
String batchId = expenses.getBatchId();
System.out.println("categoryType--------" + categoryType);
System.out.println("categoryId--------" + categoryId);
System.out.println("batchId--------" + batchId);
Batch batch = getBatchById(batchId);
if (batch != null) {
expenseDataNew(batch, expenses);
expenseImagesNew(batch, expenses);
}
}
} catch (Exception e) {
e.printStackTrace();
response = "faslse";
}
return response;
}
public void expenseDataNew(Batch batch, Expenses expenses) {
Session session = null;
Transaction transaction = null;
Gson gson = new Gson();
try {
LinkedTreeMap masterMap = (LinkedTreeMap) gson.fromJson(batch.getMasterJson(), Object.class);
LinkedTreeMap expenseObject = (LinkedTreeMap) masterMap.get("2007");
masterMap.replace(expenseObject, expenses);
String masterJson = gson.toJson(masterMap);
batch.setMasterJson(masterJson);
session = HibernateUtil.getSessionFactory().openSession();
transaction = session.beginTransaction();
session.saveOrUpdate(batch);
transaction.commit();
} catch (Exception e) {
if (transaction != null) {
transaction.rollback();
}
e.printStackTrace();
} finally {
if (session != null) {
session.close();
}
}
}
public void expenseImagesNew(Batch batch, Expenses expenses) {
Session session = null;
Transaction transaction = null;
Gson gson = new Gson();
try {
// DIVERTING TO IMAGE DB
session = ImageHibernateUtil.getSessionFactory().openSession();
transaction = session.beginTransaction();
if (expenses != null) {
int catType = expenses.getCategoryType();
String categoryType = String.valueOf(catType);
System.out.println("categoryType--------" + categoryType);
String categoryId = expenses.getCategoryId();
System.out.println("categoryId--------" + categoryId);
String travelExpenseImgId = "f257f225-41da-11e7-be05-001d92ba9634";
String accommodationExpenseImgId = "204b4baf-41db-11e7-be05-001d92ba9634";
String otherExpenseImgId = "45d31872-41db-11e7-be05-001d92ba9634";
AssessorExpense assessorExpense = expenses.getAssessorExpense();
TCExpense tCExpense = expenses.getTcExpense();
Boolean isTravel, isAccomadation, isOthers;
List<Travel> travelList;
List<Accomadation> accommodationList;
List<Others> othersList;
ArrayList proof;
Expense expense;
ExpenseImage expenseImage;
// categoryType: 1 = Assessor
// categoryType: 4 = TC
if (categoryType.equals("1")) {
if (assessorExpense != null) {
isTravel = assessorExpense.isTravel();
if (isTravel) {
travelList = (ArrayList) assessorExpense.getTravel();
System.out.println("travelList.size()==" + travelList.size());
expense = getExpense(travelExpenseImgId);
System.out.println("expense==travel==1==:" + expense);
String expenseStr = String.valueOf(expense);
System.out.println("expenseStr==travel==1==:" + expenseStr);
for (Travel travel : travelList) {
List<ExpenseImageObject> expenseImageObjects = (ArrayList) travel.getExpenseImageObjects();
System.out.println("travel==expenseImageObjects.size()== :" + expenseImageObjects.size());
for (ExpenseImageObject image : expenseImageObjects) {
System.out.println("expense===travel==for==:" + expense);
expenseImage = new ExpenseImage();
expenseImage.setBatchId(batch.getBatchId());
expenseImage.setCategoryId(expenses.getCategoryId());
expenseImage.setExpimgId(expenseStr);
expenseImage.setImage(image.getImage());
expenseImage.setStatus(1); // dummy status 1 - Travel, 2 - Accommodation, 3 - Other
session.saveOrUpdate(expenseImage);
}
}
}
}
}
}
transaction.commit();
} catch (Exception e) {
if (transaction != null) {
transaction.rollback();
}
e.printStackTrace();
} finally {
if (session != null) {
session.close();
}
}
}
I am actually trying to send an object with lists of data as well list of photos in each list to the server.
Browsed through several websites and almost all topics related to the error on Stack Overflow, Been sitting on this issue for more than a week. Hope I would find some help.
Try using "HttpHeaders" to set the content-type header explicitly to what is expected by the endpoint.
Then you use the "HttpEntity" with both your header and your body classes.
Example :
HttpHeaders requestHeaders = new HttpHeaders();
requestHeaders.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
HttpEntity<String> httpEntity = new HttpEntity<>("my body", requestHeaders);
byte[] response = restTemplate.postForObject(
"URL", httpEntity, byte[].class);
Change the call to something like this
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
headers.add("Accept","application/json;charset=utf-8");
RestTemplate restTemplate = new RestTemplate();
...
HttpEntity request = new HttpEntity(req, headers);
responseEntity = restTemplate.exchange(url, HttpMethod.POST, request,
String.class);
to specify content type
UPDATE
req is in fact body you send to the server. It could be e.g.
MultiValueMap<String, Object> req ...
There you in fact send request body and headers.
After a hell lot of research and experts suggestions, I finally managed to find the solution to my problem. The problem is not with the code. Its actually perfect. The problem is with the Objects I use to get & set. I am using NetBeans for server side coding. What I did was, I created my necessary Objects in Android studio, copied the parameters, getters & setters and pasted them on NetBeans, Object class. The problem was with the booleans I've been using. The booleans that are created on Android Studio didn't support on NetBeans in some cases, that prevented hitting the server. And after getting expert advice, I did the Object creation on NetBeans copied the parameters, getters & setters and pasted them on Android Studio Object class. And then it worked well. Took me more than 2 weeks to solve this issue. Hope this would be of some help.

java.lang.IndexOutOfBoundsException: Invalid index 1, size is 0 error

Can anyone help me? I debugg app many more time but I can not found what exact issue going in my android app. In my android app, My cases are describe below.
cases 1: Insert data into database It is perfectly worked fine.
case 2: That data display in to recycler view ok. It will display fine.
It will work with only single user login. When another user will login in to app and try to add data then It will get this exception. Or when I will refresh first user login view at that time it have same exception.
Or when I remove second user from database then I refresh first login user view at that time it will work perfectly . Now what to do? Please any one help me out of this issue. I attached screen shot of my error log please refer it.
Retrive data.java
private void makeJsonArrayRequest(final String email) {
String cancel_req_tag = "list";
JsonArrayRequest req = new JsonArrayRequest(URL_FOR_SELECT,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d("OnResponse", response.toString());
try {
// Parsing json array response
// loop through each json object
for (int i = 0; i < response.length(); i++) {
JSONObject jsonObject = response.getJSONObject(i);
ListMobileModal objMobileModal = new ListMobileModal();
if (jsonObject.getString("email").equals(email)) {
objMobileModal.email = jsonObject.getString("email");
if (!jsonObject.isNull("name")) {
objMobileModal.lname = jsonObject.getString("name"); //here we can fetch webservice field
}
if (!jsonObject.isNull("title")) {
objMobileModal.title = jsonObject.getString("title"); //here we can fetch webservice field
}
if (!jsonObject.isNull("eimage")) {
objMobileModal.eimage = jsonObject.getString("eimage");
}
if (!jsonObject.isNull("eid")) {
objMobileModal.eid = jsonObject.getString("eid");
}
if (!jsonObject.isNull("ename")) {
objMobileModal.ename = jsonObject.getString("ename");
}
if (!jsonObject.isNull("edescription")) {
objMobileModal.edescription = jsonObject.getString("edescription");
}
if (!jsonObject.isNull("evlocation")) {
objMobileModal.elocation = jsonObject.getString("elocation");
}
lstListMobile.add(i, objMobileModal);
}
}
objMobileAdapter = new ListMobileAdapter(SavedPhoneBottomActivity.this, lstListMobile);
objEmptyRecyclerViewAdapter = new EmptyRecyclerViewAdapter("No selected list!");
if (lstListMobile == null || lstListMobile.size() == 0) {
rvDisplay.setAdapter(objEmptyRecyclerViewAdapter);
rvDisplay.setVisibility(View.VISIBLE);
} else {
rvDisplay.setAdapter(objMobileAdapter);
rvDisplay.setVisibility(View.VISIBLE);
}
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(SavedPhoneBottomActivity.this,
"Error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
VolleyLog.d("VolleyError", "Error: " + error.getMessage());
Toast.makeText(SavedPhoneBottomActivity.this,
error.getMessage(), Toast.LENGTH_SHORT).show();
}
});
AppSingleton.getInstance(getApplicationContext()).addToRequestQueue(req, cancel_req_tag);
}
List exception error
try to replace lstListMobile.add(i, objMobileModal); with lstListMobile.add(objMobileModal);
when if (jsonObject.getString("email").equals(email)) condition fails 0 index is not added for that user.
you will get ArrayIndexOutOfBound error on lstListMobile.add(1, objMobileModal); if 0 index is not present
You're inserting lstListMobile.add(i, objMobileModal); maybe you can just add lstListMobile.add(objMobileModal);? Probably whats happening is that when i==0 is does not pass the test if (jsonObject.getString("email").equals(email)) {. So it does not add and the size remains 0. When i==1 it breaks when inserting.
Please check first array is not null
if (response.length > 0) {
// do something
}
else{
//empty array
}

Gdata map Api in android

i am trying to implement gdata map api in my android project.. but i am unable to solve this error
"java.lang.VerifyError: com.google.gdata.client.media.MediaService"
i am using all the libraries required to implement gdata apis
MapsService myService = new MapsService("createMap"); error is coming due to this line
is there any clue..
thnx..
i am trying with following code
//
**MapsService myService = new MapsService("createMap");**
try {
// Replace username and password with your authentication credentials
myService.setUserCredentials("username","password");
createMap(myService);
} catch(AuthenticationException e) {
System.out.println("Authentication Exception");
} catch(ServiceException e) {
System.out.println("Service Exception: " + e.getMessage());
} catch(IOException e) {
System.out.println("I/O Exception");
}
}
public static MapEntry createMap(MapsService myService)
throws ServiceException, IOException {
// Replace the following URL with your metafeed's POST (Edit) URL
// Replace userID with appropriate values for your map
final URL editUrl = new URL("http://maps.google.com/maps/feeds/maps/userID/full");
MapFeed resultFeed = myService.getFeed(editUrl, MapFeed.class);
URL mapUrl = new URL(resultFeed.getEntryPostLink().getHref());
// Create a MapEntry object
MapEntry myEntry = new MapEntry();
myEntry.setTitle(new PlainTextConstruct("Demo Map"));
myEntry.setSummary(new PlainTextConstruct("Summary"));
myEntry.getAuthors().add(new Person("My Name", null, "username"));
return myService.insert(mapUrl, myEntry);
}
You have to add "servlet.jar, activation.jar, mail.jar" In your source code

Categories

Resources