value Data of type java.lang.String cannot be converted to JSONObject # java android - java

Can you help, why I'm getting this error in logcat?
Recently it was OK since I moved to SDK 28, it is failing. But I'm not sure that this is an issue of SDK 28.
Payment is getting OK (user receives a payment, but Intent isn't working and in Logcat I got this error)
Can you suggest something?
thank you
public void sendPayment(String type) {
ProjectUtils.showProgressDialog(mContext, true, getResources().getString(R.string.please_wait));
new HttpsRequest(Consts.MAKE_PAYMENT_API, getParms(type), mContext).stringPost(TAG, new Helper() {
#Override
public void backResponse(boolean flag, String msg, JSONObject response) {
ProjectUtils.pauseProgressDialog();
if (flag) {
ProjectUtils.showToast(mContext, msg);
Intent in = new Intent(mContext, WriteReview.class);
in.putExtra(Consts.HISTORY_DTO, historyDTO);
startActivity(in);
finish();
} else {
ProjectUtils.showToast(mContext, msg);
}
}
});
}
public Map<String, String> getParms(String type) {
HashMap<String, String> params = new HashMap<>();
params.put(Consts.INVOICE_ID, historyDTO.getInvoice_id());
params.put(Consts.USER_ID, userDTO.getUser_id());
params.put(Consts.COUPON_CODE, coupon_code);
params.put(Consts.FINAL_AMOUNT, final_amount);
params.put(Consts.PAYMENT_STATUS, "1");
params.put(Consts.PAYMENT_TYPE, type);
params.put(Consts.DISCOUNT_AMOUNT, discount_amount);
Log.e("sendPaymentConfirm", params.toString());
return params;
}
UPD:
errors
sendPaymentConfirm: {payment_type=1, final_amount=150, discount_amount=0, invoice_id=RCVG2QNWBHCP, payment_status=1, user_id=614, coupon_code=}
PaymentProActivity: error body --->null error msg --->org.json.JSONException: Value <div of type java.lang.String cannot be converted to JSONObject

Issue solved, by downgrade from PHP 7.2, to PHP 7.1

Related

Getting NameNotFoundException when trying to get name of app from StatusBarNotification

I am using a notification listener and trying to get the name of the app that sent the notification. I tried using the PackageManager class to get the name of the app, however, I keep getting a NameNotFoundException every time I get a notification. Here is my code:
public class NotificationListener extends NotificationListenerService {
private final ArrayList<Integer> postedIds = new ArrayList<>();
#Override
public void onNotificationPosted(StatusBarNotification sbn) {
ArrayList<Integer> connectedThreadNotifications = new ArrayList<>();
for (BluetoothConnectionThread bluetoothConnectionThread :
Utils.getCurrentlyRunningThreads()) {
connectedThreadNotifications.add(bluetoothConnectionThread.getNotificationID());
}
if (sbn.getId() != 800 && !connectedThreadNotifications.contains(sbn.getId())) {
if (!postedIds.contains(sbn.getId())) {
postedIds.add(sbn.getId());
HashMap<String, Object> notification = new HashMap<>();
try {
PackageManager packageManager = getApplicationContext().getPackageManager();
ApplicationInfo appInfo = packageManager.getApplicationInfo(sbn.getPackageName(), 0);
String appName = packageManager.getApplicationLabel(appInfo).toString();
notification.put("appName", appName);
} catch (PackageManager.NameNotFoundException e) {
notification.put("appName", "Unknown");
}
notification.put("title", sbn.getNotification().extras.get("android.title"));
notification.put("subText", sbn.getNotification().extras.get("android.subText"));
notification.put("text", sbn.getNotification().extras.get("android.text"));
notification.put("infoText", sbn.getNotification().extras.get("android.infoText"));
Gson gson = new Gson();
System.out.println(gson.toJson(notification));
}
}
}
#Override
public void onNotificationRemoved(StatusBarNotification sbn) {
if (postedIds.contains(sbn.getId())) {
postedIds.remove((Integer) sbn.getId());
}
}
public void broadcastNotification() {
}
}
Any idea how I can get this to work?
Just encountered this issue, seems like Android 11 has changed the permission model of those APIs, see https://developer.android.com/about/versions/11/privacy/package-visibility
Unfortunately as far as I can tell, adding this permission is the only way to get app name of a notification now.

How To send array in params in fast android networking library

I am using Fast-Android-Networking and I want to send data to server which contains strings and arrays. It's ok to send string but I am unable to send array its not array list. It's simple array.
I have search other solution but all are regarding volley.
can anyone help?
Please dont mark duplicate.
The last 5 parameters are arrays. I tried it as String.valueOf(ReadQuran) but it also didn't work.
My Code:
AndroidNetworking.post(Api.ROOT_URL +"api/stageFiveFormData")
.addBodyParameter("mto_id",idu)
.addBodyParameter("school_id", scholid)
.addBodyParameter("person_name", personnameS)
.addBodyParameter("designation", designantionS)
.addBodyParameter("cell_number",personcellS)
.addBodyParameter("email",emailpersonS)
.addBodyParameter("whatsapp_number",whatsApppersonS)
.addBodyParameter("school_name",schoolNameS)
.addBodyParameter("postal_address",postalAdressS)
.addBodyParameter("city",cityS)
.addBodyParameter("tehsil",tehsilS)
.addBodyParameter("district",districtS)
.addBodyParameter("s_primary", priamryChecked)
.addBodyParameter("s_middle", middleChecked)
.addBodyParameter("s_high", highChecked)
.addBodyParameter("s_higher", hsChecked)
.addBodyParameter("principal_name", nameOfPrincipalS)
.addBodyParameter("p_contact_num",cellNoPrincipalS)
.addBodyParameter("p_email",emailPrincipalS)
.addBodyParameter("p_whatsapp_number",whatsAppPrincipalS)
.addBodyParameter("class", Class)
.addBodyParameter("rq_book", String.valueOf(ReadQuran))
.addBodyParameter("rqb_qty", String.valueOf(ReadQuranQty))
.addBodyParameter("fq_book", String.valueOf(FehamQuran))
.addBodyParameter("fqb_qty", String.valueOf(FehamQuranQty))
.setPriority(Priority.HIGH)
.build()
.getAsString(new StringRequestListener() {
public void onResponse(String response) {
try {
JSONArray jsonArray = new JSONArray(response);
JSONObject jsonObject = jsonArray.getJSONObject(0);
String result = jsonObject.getString("result");
String message = jsonObject.getString("message");
if (result.equalsIgnoreCase("success")) {
Toast.makeText(FormStage5.this, "" + message, Toast.LENGTH_SHORT).show();
Intent intent = new Intent(FormStage5.this, formstage2submittedmsg.class);
startActivity(intent);
pDialog.dismiss();
} else/* (result.equalsIgnoreCase("0"))*/ {
Toast.makeText(FormStage5.this, ""+message, Toast.LENGTH_SHORT).show();
pDialog.dismiss();
}
} catch (JSONException e) {
pDialog.dismiss();
Toast.makeText(FormStage5.this, "Something Went Wrong , Try Again", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onError(ANError anError) {
Toast.makeText(FormStage5.this, "Please Check Your Internet Connection" + anError.toString(), Toast.LENGTH_LONG).show();
pDialog.hide();
}
});
The best way is to create a POJO class and set Array value, then pass it. It will automatically gets converted into JSON, if you are using retrofit with GSONConverter factory.
The accepted answer to this question talks about Retrofit and GSON, while the question is about Fast Android Networking. The accepted answer did not work for me.
I found that the only way to do this was to build the body myself and add it to the request with .addJSONObjectBody.
I wanted a body that looks like:
{
"roles": [
"customer-admin"
]
}
The final way I found which works is:
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
JSONObject roles;
try {
roles = new JSONObject();
JSONArray rolesArr = new JSONArray();
rolesArr.put("customer-admin");
roles.put("roles", rolesArr);
} catch (JSONException e) {
// Make error toast here
return;
}
AndroidNetworking.post(url)
.addJSONObjectBody(roles)
.build()
pass the arrayname.toString() as a value

Issue calling firebase function

I am developing an Android app and I also have some cloud functions already created in my Firebase. My problem is that when I try to call a function, I just get no answer, like nothing happens.
My function:
private Task<String> createUser(HashMap<String, Object> data) {
// Create the arguments to the callable function, which is just one string
return mFunctions
.getHttpsCallable("createUser")
.call(data)
.continueWith(new Continuation<HttpsCallableResult, String>() {
#Override
public String then(#NonNull Task<HttpsCallableResult> task) throws Exception {
// This continuation runs on either success or failure, but if the task
// has failed then getResult() will throw an Exception which will be
// propagated down.
String result = (String) task.getResult().getData();
return result;
}
Where I call it:
mCreate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!mName.getText().toString().isEmpty() &&
!mAge.getText().toString().isEmpty() &&
!mBio.getText().toString().isEmpty() &&
!mSpinner.getSelectedItem().toString().isEmpty()){
data.put("email", userEmail);
data.put("age", mAge.getText());
if (mSpinner.getSelectedItem().toString() == "Hombre")
data.put("sex", "M");
else
data.put("sex", "F");
data.put("name", mName.getText());
createUser(data);
Toast.makeText(MainActivity.this,
"Usuario Creado!",
Toast.LENGTH_SHORT).show();
dialog.dismiss();
} else {
Toast.makeText(MainActivity.this,
"Completar todos los campos",
Toast.LENGTH_SHORT).show();
}
}
});
I really don't know whats wrong with it, and I don't know a way of finding the error.
If anyone can help me I would be really grateful.
Thanks!

Android sending JSON object to server gone wrong using retrofit2?

I am trying to develop an program which allows you to send a JSON object to server and then read the object in order to store the data in the database, but I'm unable to achieve that. Here is my code, could you tell me where I am going wrong and how I could correct it?
Here is my APIService:
#POST("testingjson.php")
Call<Result> confirmOrder(
#Body JSONObject productCart
);
Here is the Result class:
public class Result {
private JSONObject cartProducts;
public JSONObject getCartProducts() {
return cartProducts;
}
public void setCartProducts(JSONObject cartProducts) {
this.cartProducts = cartProducts;
}
}
And finally this is the call of service on the clicklistener of an button:
Gson gson = new GsonBuilder().setLenient().create();
Retrofit retrofit = new Retrofit.Builder().baseUrl(APIUrl.BASE_URL).addConverterFactory(GsonConverterFactory.create(gson)).build();
APIService service = retrofit.create(APIService.class);
Call<Result> call=service.confirmOrder(Cart);
call.enqueue(new Callback<Result>() {
#Override
public void onResponse(Call<Result> call, Response<Result> response) {
Toast.makeText(getApplicationContext(),"OrderPlaced",Toast.LENGTH_LONG).show();
}
#Override
public void onFailure(Call<Result> call, Throwable t) {
Toast.makeText(getApplicationContext(),t.toString(),Toast.LENGTH_LONG).show();
}
});
And here is the PHP code where it is sent in order to store the elements to the database on the server:
<?php
$password="";
$user="root";
$database="shadowpets";
$host="localhost";
$con = mysqli_connect($host,$user,$password,$database) or die('Unable to Connect');
if($_SERVER["REQUEST_METHOD"]=="POST") {
$jsonData=file_get_contents("php://input");
$jsonString=json_decode($jsonData,true);
try {
foreach($jsonString['Order Summary'] as $cart) {
$name=$cart['ProductName'];
$price=$cart['ProductPrice'];
$quantity=$cart['ProductQuantity'];
$cost=$cart['ProductCost'];
$seller=$cart['SellerId'];
$stmt=$con->prepare("INSERT INTO sProducts(Name,Price,Quantity,Cost,Sellerid)VALUES(?,?,?,?,?)");
$stmt->bind_param("sssss",$name,$price,$quantity,$cost,$seller);
$stmt->execute();
}
$res['result']="data inserted";
} catch(Exception $ex) {
$res['result']=$ex;
}
print_r (json_encode($res));
}
?>
Upon running the app I'm getting following error:
com.google.gson.JsonSyntaxException:java.lang.illlegalStateException:Expected BEGIN_OBJECT but was String at line 1 column 1 path$
Could anybody tell me where I am going wrong, and how I can rectify the mistake?

Android Facebook Unsupported post request error

I am working on a Facebook application and am currently trying to have my app tag one of the user's friends. I almost have it working 100%, except when it is supposed to be tagging the person, I instead get an error message that follows:
{"error":{"message":"Unsupported post request.","type":"GraphMethodException","code":100}}
The user and photo IDs are for sure correct, that is not the issue. Otherwise, I'm not sure what else could be causing this error. Code is below for reference. Thanks much!
public void setTag() {
String relativePath = Constants.photoID + "/tags/" + Constants.userID;
Bundle params = new Bundle();
params.putString("x", "5");
params.putString("y", "5");
Constants.mAsyncRunner.request(relativePath, params, "POST", new TagPhotoRequestListener(),
null);
}
public class TagPhotoRequestListener extends BaseRequestListener {
#Override
public void onComplete(final String response, final Object state) {
if (response.equals("true"))
{
String message = "User tagged in photo at (5, 5)" + "\n";
message += "Api Response: " + response;
Log.i("TagPhotoRequestListener", message);
}
else
{
Log.w("TagPhotoRequestListener", "User could not be tagged.");
}
}
public void onFacebookError(FacebookError e) {
Log.w("TagPhotoRequestListener", "Facebook Error: " + e.getMessage());
}
}
EDIT: Here is my code for posting of a picture and getting the photoID. For testing purposes it's just a single photo from my sdcard.
public void postPhoto() {
byte[] data = null;
Bitmap bi = BitmapFactory.decodeFile("/mnt/sdcard/Download/KathleenSchedule.jpg");
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bi.compress(Bitmap.CompressFormat.JPEG, 100, baos);
data = baos.toByteArray();
Bundle params = new Bundle();
params.putString(Facebook.TOKEN, Constants.mFacebook.getAccessToken());
params.putString("method", "photos.upload");
params.putByteArray("picture", data);
AsyncFacebookRunner mAsyncRunner = new AsyncFacebookRunner(Constants.mFacebook);
mAsyncRunner.request(null, params, "POST", new PhotoUploadListener(), null);
}
public class PhotoUploadListener extends BaseRequestListener {
#Override
public void onComplete(final String response, final Object state) {
try {
// process the response here: (executed in background thread)
Log.d("PhotoUploadListener", "Response: " + response.toString());
JSONObject json = Util.parseJson(response);
System.out.println(response);
final String photo_id = json.getString("pid");
Constants.photoID = photo_id;
Ok, now your problem is clear.
You are using the photos.upload method which is deprecated:
We are in the process of deprecating the REST API, so if you are
building a new application you shouldn't use this function. Instead
use the Graph API and POST to the photos connection of the User object
Because you are using an old method, you're getting and old response type.
Switch to using the graph api way, and you should get the photo id in the response.

Categories