Implement keys local language erreur - android

class MyLocale implements Translations {
#override
Map<String,Map<String,String>> get Keys => {
"ar": {},
"en":{}, };
};
#override
// TODO: implement keys
Map<String, Map<String, String>> get keys => throw UnimplementedError();
}
this the erreur photo
im trying to fix this erreur to run my application pliz help me

make it like this if you use GetX
import 'package:get/get.dart';
class MyTranslation extends Translations {
#override
Map<String, Map<String, String>> get keys => {
"ar": {,
"1": "اختر اللغه",
},
"en": {
"1": "Choose Language",
}
};
}

Related

Flutter/Dart Data Class

Currently I'm building a self practice eCommerce app using flutter (my back-end is in Laravel). Every time I make a model class, I always come across the issues in fromMap methods.
Currently I cant store my api response to the order (orders and orderItems class is given below).
Error says Unhandled Exception: type 'List' is not a subtype of type 'List' in type cast
here's how I am trying to save the api response
Orders orders = Orders(
List.from(response.data)
.map<OrderItem>((item) => OrderItem.fromMap(item))
.toList(),
);
Orders Class
class Orders {
final List<OrderItem> orders;
Orders(
this.orders,
);
Orders copyWith({
List<OrderItem>? orders,
}) {
return Orders(
orders ?? this.orders,
);
}
Map<String, dynamic> toMap() {
return <String, dynamic>{
'orders': orders.map((x) => x.toMap()).toList(),
};
}
factory Orders.fromMap(Map<String, dynamic> map) {
return Orders(
List<OrderItem>.from(
(map['orders'] as List<int>).map<OrderItem>(
(x) => OrderItem.fromMap(x as Map<String, dynamic>),
),
),
);
}
String toJson() => json.encode(toMap());
factory Orders.fromJson(String source) =>
Orders.fromMap(json.decode(source) as Map<String, dynamic>);
#override
String toString() => 'Orders(orders: $orders)';
#override
bool operator ==(covariant Orders other) {
if (identical(this, other)) return true;
return listEquals(other.orders, orders);
}
#override
int get hashCode => orders.hashCode;
}
OrderItems Class
class OrderItem {
final num id;
final List<num> pid;
OrderItem(
this.id,
this.pid,
);
OrderItem copyWith({
num? id,
List<num>? pid,
}) {
return OrderItem(
id ?? this.id,
pid ?? this.pid,
);
}
Map<String, dynamic> toMap() {
return <String, dynamic>{
'id': id,
'pid': pid,
};
}
factory OrderItem.fromMap(Map<String, dynamic> map) {
return OrderItem(
map['id'] as num,
List<num>.from(
(map['pid'] as List<num>),
),
);
}
String toJson() => json.encode(toMap());
factory OrderItem.fromJson(String source) =>
OrderItem.fromMap(json.decode(source) as Map<String, dynamic>);
#override
String toString() => 'OrderItem(id: $id, pid: $pid)';
#override
bool operator ==(covariant OrderItem other) {
if (identical(this, other)) return true;
return other.id == id && listEquals(other.pid, pid);
}
#override
int get hashCode => id.hashCode ^ pid.hashCode;
}
Here's what the API response looks like
[
{
"id": 1,
"uid": "1",
"pid": [
1,
2
],
"created_at": "2022-07-16T10:34:51.000000Z",
"updated_at": "2022-07-16T10:34:51.000000Z"
},
{
"id": 2,
"uid": "1",
"pid": "[2,3]",
"created_at": "2022-07-16T12:19:15.000000Z",
"updated_at": "2022-07-16T12:19:15.000000Z"
}
]
Typically you don't want to define all these data class methods every time since it can be time consuming and error prone.
I recently created a package which can help you add all this functionality without being too intrusive on your models. You can check it out at: https://pub.dev/packages/mint.
You can also use freezed (https://pub.dev/packages/freezed) which is an excellent package with a proven track record. However, you may have to drastically change your coding style to be compatible with freezed. This is my only issue with it. Mint's primary purpose is to stay out of your way as much as possible. It's also template driven so you can easily modify the templates and add your own functionality as you see fit.

Return data to Android from Firebase Function [duplicate]

This question already has answers here:
Why does my function that calls an API or launches a coroutine return an empty or null value?
(4 answers)
Closed 1 year ago.
What I am trying to do: Simply return data from Firebase Cloud Function.
The function is used to create a payment order in the payment gateway's server.
My required data about the order's details are present in the function(err,data) (see below), but I need this data sent back to my Android app.
Problem I faced: I could see the data printed in the Firebase console's log but it doesn't return to my Android app.
My Firebase Cloud Function:
const functions = require("firebase-functions");
exports.order = functions.https.onCall((amnt, response) => {
const Ippopay = require('node-ippopay');
const ippopay_instance = new Ippopay({
public_key: 'YOUR_PUBLIC_KEY',
secret_key: 'YOUR_SECRET_KEY',
});
ippopay_instance.createOrder({
amount: amnt,
currency: 'DOLLAR',
payment_modes: "cc,dc,nb,cheque",
customer: {
name: "Test",
email: "test#gmail.com",
phone: {
country_code: "42",
national_number: "4376543210"
}
}
}, function (err, data) {
return data.order.order_id;
});
});
My Android client-side code:
public class Payment extends AppCompatActivity implements IppoPayListener {
Button pay;
EditText amount;
private FirebaseFunctions mFunctions;
TextView order_data;
String data;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_payment);
}
#Override
protected void onPostCreate(#Nullable Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
pay=findViewById(R.id.pay_button);
amount=findViewById(R.id.user_amount);
order_data=findViewById(R.id.data_text);
pay.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d("PAY Button clicked", "yes");
mFunctions = FirebaseFunctions.getInstance("us-central1");
mFunctions.getHttpsCallable("order").call(5).continueWith(new Continuation<HttpsCallableResult, Object>() {
#Override
public Object then(#NonNull Task<HttpsCallableResult> task) throws Exception {
HttpsCallableResult result=task.getResult();
if(result !=null)
{
data=result.getData().toString();
return result.getData().toString();
}
return null;
}
});
order_data.setText(data);
onPaymentClick();
}
});
}
/* ... */
}
I'm a Beginner so there's a high possibility of some dead silly mistakes. :)
Based on what your code looks like at the moment, you have a mix of code from a Callable Cloud Function and the older HTTP Request Cloud Function.
To return data from a callable Cloud Function, you should return a Promise, a method of running asynchronous code that returns a value. Older JavaScript and many other languages use callbacks instead, which is what you have here.
In it's simplest form, this callback-based method:
someModule.doSomething(input, function (err, result) {
// check for errors and handle result
});
would be converted to use Promises using:
new Promise((resolve, reject) => {
someModule.doSomething(
input,
(err, result) => err ? reject(err) : resolve(result) // short form of "if error, reject with an error, otherwise resolve (succeed) with result"
)
});
For errors to be handled correctly by clients, you need to wrap any errors in a functions.https.HttpsError.
Combining this together gives:
const functions = require("firebase-functions");
exports.order = functions.https.onCall((amnt, context) => {
const Ippopay = require('node-ippopay');
return new Promise((resolve, reject) => {
const ippopay_instance = new Ippopay({
public_key: 'YOUR_PUBLIC_KEY',
secret_key: 'YOUR_SECRET_KEY',
});
ippopay_instance.createOrder({
amount: amnt,
currency: 'DOLLAR',
payment_modes: "cc,dc,nb,cheque",
customer: {
name: "Test",
email: "test#gmail.com",
phone: {
country_code: "42",
national_number: "4376543210"
}
}
}, function (err, data) {
if (err) {
// something went wrong, send error back to caller
reject(new functions.https.HttpsError('unknown', 'Ippopay threw an unexpected error', err));
return;
}
// successful, send data back to caller
resolve(data.order.order_id);
});
});
});
You should also make sure you make use of context.auth to restrict access to this function. You wouldn't want to bill the wrong customer.

Is it possible to combine a GUI made with react native with utility methods from native code (kotlin)?

I have an app which was made entirely using react native. It's pretty much a todo list, this is the structure:
<SafeAreaView style={styles.container}>
<Text style={styles.title} >Registro de pacientes</Text>
{loading && (
<ActivityIndicator
style={styles.loading}
size="large"
color="#0066ff"
/>
)}
{!loading && (
<ListaPacientes
pacientes={pacientes}
onUpdate={this.handleUpdate}
/>
)}
</SafeAreaView>
And here is the list:
<SectionList
sections={
pacientes && pacientes.length ?
[
{title: "Pacientes sin registrar", data: pacientes.filter(paciente => !paciente.done)},
{title: "Pacientes registrados", data: pacientes.filter(paciente => paciente.done)}
] : []
}
keyExtractor={paciente => paciente.id}
renderItem={({item}) => renderItem(item)}
renderSectionHeader={renderSectionHeader}
style={styles.container}
ItemSeparatorComponent={renderSeparator}
ListEmptyComponent={renderEmptyComponent}
stickySectionHeadersEnabled={true}
/>
This takes a list of clients and displays their names. Upon being clicked on, they are removed from the list. Very simple.
The thing is, the list of clients must be read from a csv file and, after being clicked, update the csv. I already have a piece of code that does that. However, it's written in kotlin (It was coded for another project).
Instead of having to do the whole fetching/reading/treating/updating of the data again in react native, can I somehow use the kotlin code I already have? If so, care to provide an example on how it would be done?
EDIT: To clarify, I have a kotlin method that returns an ArrayList of strings with the names I want to store on the list. How can I call that method from the javascript, obtain the arraylist, and use it as data source for my SectionList ?.
lateinit var pacientes: Array<String>
#ReactMethod
fun getListaPacientes() : Array<String> {
return pacientes
}
Something like this?
var res = []
res = ListaPacientesModulo.getListaPacientes()
Thank you.
I have solved the problem doing the following:
First of all, turns out you can't use native modules if you are using expo, so I had to eject it.
Second, in order to use kotlin you have to install the plugin manually (which you can do, but I decided it wasn't worth the hassle so I used java instead)
When it comes to the code, you need to use "WritableArray" and "WritableMap".
private static WritableMap convertJsonToMap(JSONObject jsonObject) throws JSONException {
WritableMap map = new WritableNativeMap();
Iterator<String> iterator = jsonObject.keys();
while (iterator.hasNext()) {
String key = iterator.next();
Object value = jsonObject.get(key);
if (value instanceof JSONObject) {
map.putMap(key, convertJsonToMap((JSONObject) value));
} else if (value instanceof Boolean) {
map.putBoolean(key, (Boolean) value);
} else if (value instanceof Integer) {
map.putInt(key, (Integer) value);
} else if (value instanceof Double) {
map.putDouble(key, (Double) value);
} else if (value instanceof String) {
map.putString(key, (String) value);
} else {
map.putString(key, value.toString());
}
}
return map;
}
All react methods must return void, use promises or callbacks to comunicate with react
#ReactMethod
public void readCSV(Promise promise) {
//Load the list
for(int i = 0; i < source.size(); i++) {
this.listWithPeople.add(new Person(source.get(i), startTimes.get(i)));
}
//Pepare the map
WritableArray defList = new WritableNativeArray();
Gson g = new Gson();
for(Person p : this.listWithPeople) {
JSONObject jo = new JSONObject(g.toJson(p));
WritableMap wm = convertJsonToMap(jo);
defList.pushMap(wm);
}
promise.resolve(defList);
}
Finally, on your .js file:
import { NativeModules } from 'react-native';
const { NativeModuleName } = NativeModules;
const getPacientes = async () => {
var peopleList = []
var res = await NativeModuleName.readCSV()
for(var i = 0; i < res.length; i++) {
peopleList.push(newPerson({ name: res[i].name, star: res[i].date, done: false }))
}
return peopleList
}
On the android part you also need this class:
ModuleNamePackage.java
public class ModuleNamePackage implements ReactPackage {
#NonNull
#Override
public List<NativeModule> createNativeModules(#NonNull ReactApplicationContext reactContext) {
List<NativeModule> nativeModules = new ArrayList<>();
nativeModules.add(new NativeModuleName(reactContext));
return nativeModules;
}
#NonNull
#Override
public List<ViewManager> createViewManagers(#NonNull ReactApplicationContext reactContext) {
return Collections.emptyList();
}
}
And inside MainApplication.java, you need to add your package to the package list:
private final ReactNativeHost mReactNativeHost =
new ReactNativeHost(this) {
#Override
public boolean getUseDeveloperSupport() {
return BuildConfig.DEBUG;
}
#Override
protected List<ReactPackage> getPackages() {
#SuppressWarnings("UnnecessaryLocalVariable")
List<ReactPackage> packages = new PackageList(this).getPackages();
// Packages that cannot be autolinked yet can be added manually here, for example:
// packages.add(new MyReactNativePackage());
packages.add(new ModuleNamePackage());
return packages;
}
#Override
protected String getJSMainModuleName() {
return "index";
}
};
Assuming that your Kotlin code is well built, ie, each method is detached from the UI, you can create a bridge from react-native to Kotlin.
You need to create a Package, a Module, and your Bridge class.
import com.facebook.react.bridge.ReactMethod
class CsvManager(reactContext: ReactApplicationContext) : ReactContextBaseJavaModule(reactContext) {
// the bridge
#ReactMethod
fun update(csvUrl: String, data: List<String>) {
// your code to load or update the CSV
}
}
In your top project, create a new JS like kotlinCsv.js :
import { NativeModules } from 'react-native'
module.exports = NativeModules.CsvModule
Anywhere in your App:
import KotlinCsvUpdater from './kotlinCsv'
let myArray = []
KotlinCsvUpdater.update('pathToMyFile', myArray)

Getvalue from dynamic keys in Gson

I have one Registration Api which has error object in which it shows Errors Dynamically in Array.
This is the JsonFormat of Api :
{
"status_code": 422,
"status": "error",
"data": {
"errors": {
"password": [
"The password must be between 8 and 15 characters."
],
"mobile_no": [
"The mobile number has already been taken."
]
}
}
}
Here if a user forgot to write name then it will show username array in errors. So it changes dynamically.
My question is how I can set this type of errors in gson.I am using retrofit to call Api.
I did this in my Data class but it showing me errors.
#SerializedName("errors")
#Expose
JsonObject errorObject;
Iterator iterator=new Iterator() {
#Override
public boolean hasNext() {
Iterator keys=errorObject.keys();
if(keys.hasNext()){
}
}
#Override
public Object next() {
return null;
}
}
Please help me how can I getErrors using gson.Thank u
You can use Map to maintin the datastructure like this:
Type type = new TypeToken<Map<String, String>>(){}.getType();
Map<String, String> myMap = gson.fromJson(yourErrorsArrayHere, type);
and then just use myMap.get("your_error_key") to get the particular error.

Gson parser class for dynamic json key value - Android

I've used gson library for parsing json response. its working well. now i got a problem .
i've got below response from webservice. the json key value is not static, it will dynamically change.
how to write a parser class to parse the below response.
Formatted JSON:
{
"meta": {
"code": 201,
"dataPropertyName": "activity",
"currentTime": "2014-02-05 06:15:04",
"listedCount": "2"
},
"activity": [
{
"comments": [
{
"raja": {
"type": "Liked",
"userPhoto": "663.png",
"userId": "74",
"userName": {
"1_0": "longjump"
},
"postOwner": "you",
"postDetails": {
"471": {
"postImage": "972.png",
"postId": "471",
"postType": "1"
}
},
"dateTime": "2014-02-05 05:24:56",
"sameOwner": "1"
}
}
]
},
{
"follow": [
{
"you": {
"type": "follow",
"followByUserName": {
"0_0": "olivepop",
"1_0": "yadidroy",
"2_0": "chitra"
},
"followUserName": "you",
"followByUserPhoto": "242.png",
"followUserPhoto": "953.png",
"dateTime": "2014-01-09 06:50:42"
}
}
]
}
],
"notifications": [
"Activities has been retrieved successfully"
]
}
Use this parser class
Meta meta = new Meta();
ArrayList<Activity> activity = new ArrayList<ActivityParser.Activity>();
ArrayList<String> notifications = new ArrayList<String>();
public class Meta
{
String code,dataPropertyName,currentTime,listedCount;
}
public class Activity
{
ArrayList<HashMap<String, CommentsItem>> comments = new ArrayList<HashMap<String,CommentsItem>>();
public class CommentsItem
{
String type,userPhoto,userId,postOwner,dateTime,sameOwner;
HashMap<String, String> userName = new HashMap<String,String>();
HashMap<String, PostDetails> postDetails = new HashMap<String,PostDetails>();
public class PostDetails
{
String postImage,postId,postType;
}
}
ArrayList<HashMap<String, FollowItem>> follow = new ArrayList<HashMap<String,FollowItem>>();
public class FollowItem
{
String type,followUserName,followByUserPhoto,followUserPhoto,dateTime;
HashMap<String, String> followByUserName = new HashMap<String,String>();
}
}
If possible get a JSON response with all possible "Key" values and then get the POJO class auto build from below link:
POJO FOR GSON
It will automatically handle all the posibilities. But make sure the RESPONCE you are providing while generating the POJO should hold all the possible combinations of your Key [changing once].
HOPE THIS HELPS!!
Depending on your specification, you can make a Default Webservice response model.java which would be something like:
String success;
#SerializedName("error_msg")
String errorMessage;
#SerializedName("error_code")
String errorCode;
JsonObject data;
where the Parent of the object with dynamic keys would be the "data".
Use Gson, map the model class:
webserviceResponse= gson.fromJson(contentResponse,WebserviceResponse.class);
if (StringUtils.isNotEmpty(webserviceResponse.getSuccess()) &&
StringUtils.equalsIgnoreCase(webserviceResponse.getSuccess(), "success")) {
//check for the dynamic key name
JsonObject job = webserviceResponse.getData();
dynamicallyDefinedKeyClass= gson.fromJson(job.get("dynamicKeyValue"), DynamicallyDefinedKeyClass.class);
}
Will edit my answer on question edit, in any way if it can help
Just a suggestion - raja, you etc. can be values for a key - name or commentsBy ? Where are you getting this response from?

Categories

Resources