I have a requirement where I need to make few Java calls and retrieve necessary values. These are all strings. I need to write this to a console with comma separated values. Like below:
3,Till,,Till,Weiss,,
3,ugilad,,ugilad,ugilad,,
3,admintest,,admin,test,abc#sample.com,
Expected should be:
userid,firstname,lastname,email
3,Till,,Till,Weiss,,
3,ugilad,,ugilad,ugilad,,
3,admintest,,admin,test,abc#sample.com,
Now I need to add columns to these values. Say: userId, firstName, lastName like this. How can I achieve this dynamically using Java code? Here is the code that I wrote:
if (usersList.totalCount != 0 && usersList.totalCount >= 1) {
System.out.println("usersList.totalCount ----->"
+ usersList.totalCount);
for (KalturaUser user : usersList.objects) {
if (user != null) {
if (user.id != null) {
String userRole = getUserRole(user.id);
String cnum = getUserUniqueId(user.email);
// if (userRole != null) {
// if (userRole.equals("adminRole")
// || userRole
// .equals("privateOnlyRole")) {
// sb1.append(action);
if (user.id != null) {
sb.append(user.id);
} else {
sb.append(",");
}
String action = "1";
if (cnum != null) {
if (userRole == null) {
action = "3";
}
} else {
action = "3";
}
if (action != null) {
sb1.append(action);
}
if (cnum != null) {
sb1.append(",").append(cnum);
} else {
sb1.append(",").append(user.id);
sb1.append(",");
}
if (user.firstName != null) {
sb.append(",").append(user.firstName);
sb1.append(",").append(user.firstName);
} else {
sb.append(",");
sb1.append(",");
}
if (user.lastName != null) {
sb.append(",").append(user.lastName);
sb1.append(",").append(user.lastName);
} else {
sb.append(",");
sb1.append(",");
}
if (userRole != null) {
sb.append(",").append(userRole);
// sb1.append(",").append(userRole);
} else {
sb.append(",");
// action = "3";
// sb1.append(action);
}
// sb1.append("1");
if (user.email != null) {
sb.append(",").append(user.email);
sb1.append(",").append(user.email);
} else {
sb.append(",");
sb1.append(",");
}
if (userRole != null) {
sb1.append(",").append(userRole);
} else {
sb1.append(",");
}
// sb1.append("1");
if (user.partnerData != null) {
if (user.partnerData.startsWith("pw")
&& user.partnerData.length() == 43) {
sb.append(",");
}
if (user.partnerData.length() > 43) {
String partnerData = user.partnerData
.substring(44);
sb.append(",").append(partnerData);
}
if (!user.partnerData.startsWith("pw")) {
sb.append(",").append(user.partnerData);
}
}
sb.append(System.getProperty("line.separator"));
sb1.append(System.getProperty("line.separator"));
}
}
}
}
// System.out.println(sb);
System.out.println(sb1);
As per your code you are appending everything to a string buffer(sb) and printing it at once. So in between the loop you could create a string header and assign value based on condition. And outside the loop first print header and then print the buffer. That would be the simplest soultion. However if the amount of data is buge it would be better to use a file. Write everything to a file, construct the header and then after the loop print the header and then print the file. A sample with dummy logic and classes
import java.io.RandomAccessFile;
import java.util.ArrayList;
import java.util.List;
class UserList {
public int totalCount;
public List<KalturaUser> objects;
public UserList(List<KalturaUser> objects) {
this.objects = objects;
this.totalCount = (objects != null) ? objects.size() : 0;
}
}
class KalturaUser {
public String id;
public String email;
public String firstName;
public String lastName;
public String partnerData;
public KalturaUser(String id, String email, String firstName,
String lastName, String partnerData) {
this.id = id;
this.email = email;
this.firstName = firstName;
this.lastName = lastName;
this.partnerData = partnerData;
}
}
public class DynamicHeader {
private static final String NEW_LINE = System.getProperty("line.separator");
public static void main(String[] args) throws Exception {
UserList usersList = init();
RandomAccessFile csv = new RandomAccessFile("temp.csv","rw");
csv.setLength(0); //Clears the file
String header = "";
if (usersList.totalCount >= 1) {
for (KalturaUser user : usersList.objects) {
if (user != null && user.id != null) {
List<String> row = new ArrayList<String>();
String userRole = getUserRole(user.id);
String cnum = getUserUniqueId(user.email);
row.add(getNullSafeValue(user.id));
String action = "1";
if (cnum == null || userRole == null) {
action = "3";
}
row.add(action);
if (cnum != null) {
row.add(cnum);
header = "uniqueid,firstname,lastname,email";
} else {
row.add(user.id);
header = "userid,firstname,lastname,email";
}
row.add(getNullSafeValue(user.firstName));
row.add(getNullSafeValue(user.lastName));
row.add(getNullSafeValue(userRole));
row.add(getNullSafeValue(user.email));
if (user.partnerData != null) {
if (user.partnerData.startsWith("pw")) {
if (user.partnerData.length() == 43) {
row.add("");
} else if (user.partnerData.length() > 43) {
row.add(user.partnerData.substring(44));
}
} else {
row.add(user.partnerData);
}
}
csv.write(row.toString().replace("[", "").replace("]", "").replace(", ", ",").getBytes());
csv.write(NEW_LINE.getBytes());
}
}
}
csv.seek(0);
System.out.println(header);
String data;
while((data = csv.readLine()) != null){
System.out.println(data);
}
csv.close();
}
private static UserList init() {
List<KalturaUser> userObjs = new ArrayList<KalturaUser>();
userObjs.add(new KalturaUser("1", null, "Till", "Till", "Weiss"));
userObjs.add(new KalturaUser("2", null, "ugilad", "ugilad", "ugilad"));
userObjs.add(new KalturaUser("3", "abc#sample.com", "admin", "test", "admintest"));
return new UserList(userObjs);
}
private static String getNullSafeValue(String str) {
return (str != null) ? str : "";
}
private static String getUserUniqueId(String email) {
return (email != null) ? email.substring(0, email.indexOf("#")) : null; //Replace with proper logic
}
private static String getUserRole(String id) {
return ("2".equals(id)) ? "Role 2" : null; //Replace with proper logic
}
}
Apart from this you could do some clean ups in your code like below. Also insteaded of constructing string you could just add it to a list. The toString of list gives you a comma separated value.
(usersList.totalCount != 0 && usersList.totalCount >= 1)
could be reduced to (usersList.totalCount > 0)
if (user != null) {
if (user.id != null) {}
}
If you dont have to do anything specific when (user != null) then, this could be combined to
if (user != null && user.id != null) {}
And
if (cnum != null) {
if (userRole == null) {
action = "3";
}
} else {
action = "3";
}
This could be reduced to
if (cnum == null || userRole == null) {
action = "3";
}
Related
I am trying to save a txt file into the Downloads folder in my first abndroid app.
public class DisplaySettingsActivity extends AppCompatActivity implements View.OnClickListener {
private H300sVoipSettings settings;
Button saveIntoFile;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_settings);
this.settings = (H300sVoipSettings) getIntent().getSerializableExtra("H300sVoipSettings");
this.saveIntoFile = (Button)findViewById(R.id.save);
this.saveIntoFile.setOnClickListener(this);
}
private String saveFile(){
Log.d("Η300s","Saving");
String state = Environment.getExternalStorageState();
if (!Environment.MEDIA_MOUNTED.equals(state)) {
Log.e("H300s","Unable to detect external storage");
return null;
}
DateTimeFormatter pattern = DateTimeFormatter.ofPattern("yyyMMdd");
File file = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
file = new File( file.getAbsolutePath(),"voip_h300s_"+pattern.format(LocalDate.now())+".txt");
Log.d("H300s",file.toString());
try {
Log.d("H300s","Saving");
this.settings.save(file);
Log.d("H300s","Saved");
Log.d("H300s",file.getAbsolutePath());
return file.getAbsolutePath();
} catch (Exception e) {
Log.e("H300s",e.toString());
Log.e("H300s",Log.getStackTraceString(e));
return null;
}
}
}
But this piece of code in my function:
this.settings.save(file);
Fails to be saved due to lack of permissions. As the following log shows:
2021-04-24 14:48:18.498 8208-8208/com.example.vodafone_fu_h300s E/H300s: java.io.IOException: Permission denied
2021-04-24 14:48:18.499 8208-8208/com.example.vodafone_fu_h300s E/H300s: java.io.IOException: Permission denied
at java.io.UnixFileSystem.createFileExclusively0(Native Method)
at java.io.UnixFileSystem.createFileExclusively(UnixFileSystem.java:281)
at java.io.File.createNewFile(File.java:1008)
at pc_magas.vodafone_fu_h300s.screens.DisplaySettingsActivity.saveFile(DisplaySettingsActivity.java:97)
at pc_magas.vodafone_fu_h300s.screens.DisplaySettingsActivity.onClick(DisplaySettingsActivity.java:120)
at android.view.View.performClick(View.java:6597)
at com.google.android.material.button.MaterialButton.performClick(MaterialButton.java:967)
at android.view.View.performClickInternal(View.java:6574)
at android.view.View.access$3100(View.java:778)
at android.view.View$PerformClick.run(View.java:25906)
at android.os.Handler.handleCallback(Handler.java:873)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6718)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:491)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
What I want to do is to save a txt file into Downloads Folder and make it accessible to the user via file manager. The class H300sVoipSettings has the following:
public class H300sVoipSettings implements Serializable
{
private String username = null;
private String password = null;
private String primary_registar = null;
private String primary_registar_port = null;
private String secondary_registar = null;
private String secondary_registar_port = null;
private String primary_proxy = null;
private String primary_proxy_port = null;
private String secondary_proxy = null;
private String secondary_proxy_port = null;
private String sip_domain = null;
private String sip_number = null;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPrimary_registar() {
return primary_registar;
}
public void setPrimary_registar(String primary_registar) {
this.primary_registar = primary_registar;
}
public String getPrimary_registar_port() {
return primary_registar_port;
}
public void setPrimary_registar_port(String primary_registar_port) {
this.primary_registar_port = primary_registar_port;
}
public String getSecondary_registar() {
if(secondary_registar == null || secondary_registar.trim().equals("")){
return null;
}
return secondary_registar;
}
public void setSecondary_registar(String secondary_registar) {
this.secondary_registar = secondary_registar;
}
public String getSecondary_registar_port() {
return secondary_registar_port;
}
public void setSecondary_registar_port(String secondary_registar_port) {
this.secondary_registar_port = secondary_registar_port;
}
public String getPrimary_proxy() {
return primary_proxy;
}
public void setPrimary_proxy(String primary_proxy) {
this.primary_proxy = primary_proxy;
}
public String getPrimary_proxy_port() {
return primary_proxy_port;
}
public void setPrimary_proxy_port(String primary_proxy_port) {
this.primary_proxy_port = primary_proxy_port;
}
public String getSecondary_proxy() {
return secondary_proxy;
}
public void setSecondary_proxy(String secondary_proxy) {
this.secondary_proxy = secondary_proxy;
}
public String getSecondary_proxy_port() {
return secondary_proxy_port;
}
public void setSecondary_proxy_port(String secondary_proxy_port) {
this.secondary_proxy_port = secondary_proxy_port;
}
public String getSip_domain() {
return sip_domain;
}
public void setSip_domain(String sip_domain) {
this.sip_domain = sip_domain;
}
public String getSip_number() {
return sip_number;
}
public void setSip_number(String sip_number) {
this.sip_number = sip_number;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public static H300sVoipSettings createFromJson(String jsonString) throws IllegalArgumentException, JSONException {
if(jsonString == null || jsonString.trim().equals("")){
throw new IllegalArgumentException("JsonString Should not be empty");
}
JSONArray settingsJson = new JSONArray(jsonString);
H300sVoipSettings settings = new H300sVoipSettings();
for (int i = 0; i < settingsJson.length(); i++) {
JSONObject item = settingsJson.getJSONObject(i);
if(item.getString("type").equals("provider")){
settings.setPrimary_registar(item.getString("primary_registrar"));
settings.setPrimary_registar_port(item.getString("primary_registrar_port"));
settings.setPrimary_proxy(item.getString("primary_proxy"));
settings.setPrimary_proxy_port(item.getString("primary_proxy_port"));
settings.setSip_domain(item.getString("sip_domain"));
String secondary_proxy = item.getString("secondary_proxy");
if(secondary_proxy != null && !secondary_proxy.trim().equals("")){
settings.setSecondary_proxy(secondary_proxy.trim());
}
settings.setSecondary_proxy_port(item.getString("secondary_proxy_port"));
settings.setSecondary_registar(item.getString("secondary_registrar"));
settings.setSecondary_registar_port(item.getString("secondary_registrar_port"));
} else if(item.getString("type").equals("number")){
settings.setSip_number(item.getString("sip_number"));
settings.setUsername(item.getString("username"));
settings.setPassword(item.getString("password"));
}
}
return settings;
}
public boolean equals(H300sVoipSettings other){
boolean truth = other.getPassword().equals(this.getPassword()) &&
other.getUsername().equals(this.getUsername()) &&
other.getSip_number().equals(this.getSip_number()) &&
other.getSip_domain().equals(this.getSip_domain()) &&
other.getPrimary_proxy().equals(this.getPrimary_proxy()) &&
other.getPrimary_proxy_port().equals(this.getPrimary_proxy_port()) &&
other.getPrimary_registar().equals(this.getPrimary_registar()) &&
other.getPrimary_registar_port().equals(this.getPrimary_registar_port()) &&
other.getSecondary_proxy_port().equals(this.getSecondary_proxy_port()) &&
other.getSecondary_registar_port().equals(this.getSecondary_registar_port());
truth = truth && ((other.getSecondary_proxy() == null && this.getSecondary_proxy() == null) || (other.getSecondary_proxy().equals(this.getSecondary_proxy())));
truth = truth &&
(
(other.getSecondary_registar() == null && this.getSecondary_registar() == null) ||
(
other.getSecondary_registar().equals(this.getSecondary_registar())
)
);
return truth;
}
public String toString()
{
StringBuilder txt = new StringBuilder();
txt.append("Phone Number: ");
txt.append(this.getSip_number());
txt.append("\n");
txt.append("Username: ");
txt.append(this.getUsername());
txt.append("\n");
txt.append("Password: ");
txt.append(this.getPassword());
txt.append("\n");
txt.append("Sip Domain: ");
txt.append(this.getSip_domain());
txt.append("\n");
txt.append("Primary proxy: ");
txt.append(this.getPrimary_proxy());
txt.append(" Port: ");
txt.append(this.getPrimary_proxy_port());
txt.append("\n");
txt.append("Secondary proxy: ");
String secondary_proxy = this.getSecondary_proxy();
secondary_proxy = (secondary_proxy == null || !secondary_proxy.trim().equals(""))?"N/A":secondary_proxy;
txt.append(secondary_proxy);
txt.append(" Port: ");
String secondaryProxyPort = this.getSecondary_proxy_port();
secondaryProxyPort=(secondaryProxyPort == null || !secondaryProxyPort.trim().equals(""))?"N/A":secondaryProxyPort;
txt.append(secondaryProxyPort);
txt.append("\n");
txt.append("Primary Registar: ");
String primaryRegistar = this.getPrimary_registar();
txt.append(primaryRegistar);
txt.append(" Port: ");
String primaryRegistarPort = this.getPrimary_registar_port();
txt.append(primaryRegistarPort);
txt.append("\n");
txt.append("Secondary Registar: ");
String secondary_registar = this.getSecondary_registar();
secondary_registar = (secondary_registar == null || !secondary_registar.trim().equals(""))?"N/A":secondary_registar;
txt.append(secondary_registar);
txt.append(" Port: ");
String secondaryRegistarPort = this.getSecondary_registar();
secondaryRegistarPort=(secondaryRegistarPort == null || !secondaryRegistarPort.trim().equals(""))?"N/A":secondaryRegistarPort;
txt.append(secondaryRegistarPort);
txt.append("\n");
return txt.toString();
}
public void save(File file) throws IOException {
PrintWriter out = new PrintWriter(new FileWriter(file));
out.println("********");
out.print("Exported Date: ");
out.println(new Date().toString());
out.println("********");
out.print(this.toString());
out.close();
}
}
And is used for data serialization. The application has the following in Android Manifest:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Furthermore I have looked upon these answers whith no result whatsoever:
https://stackoverflow.com/a/62748149/4706711
So do you have any idea how I can access the donwloads folder?
Despite having the permissions:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
You should also prompt the user to accept these requests as well. In order to achieve this the onCLick function should be:
public void onClick(View v) {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
Log.d("H300s","Permission Accepted");
saveFile();
} else {
requestPermissionLauncher.launch(Manifest.permission.WRITE_EXTERNAL_STORAGE );
}
}
Where the requestPermissionLauncher is initialized into the onCreate like this:
requestPermissionLauncher = registerForActivityResult(new ActivityResultContracts.RequestPermission(), isGranted -> {
Log.d("H300s","Permissions Callback");
if (isGranted) {
Log.d("H300s","Permission Accepted 2");
saveFile();
} else {
permissionSaveDenied();
}
});
Furthermore, ensure that at build.gradle you should place the following:
implementation 'androidx.activity:activity-ktx:1.2.0'
implementation 'androidx.fragment:fragment:1.3.0'
In order for the ActivityResultContracts to work.
Bonus Tip
You can skip declaring the need for this permission:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
Because application gonna request the user to provide it nevertheless.
I use codeEditor to make appybuilder extensions. I tried to get the customkey value that was obtained when the application got push notification from OneSignal.
here is the full code that I tried to make:
import android.content.Context;
import android.util.Log;
import com.google.appinventor.components.common.ComponentCategory;
import com.google.appinventor.components.annotations.*;
import com.google.appinventor.components.runtime.*;
import com.google.appinventor.components.annotations.DesignerComponent;
import com.google.appinventor.components.annotations.DesignerProperty;
import com.google.appinventor.components.annotations.PropertyCategory;
import com.google.appinventor.components.annotations.SimpleObject;
import com.google.appinventor.components.annotations.SimpleProperty;
import com.google.appinventor.components.annotations.UsesLibraries;
import com.google.appinventor.components.annotations.UsesPermissions;
import com.onesignal.OSNotification;
import com.onesignal.OSNotificationAction.ActionType;
import com.onesignal.OSNotificationOpenResult;
import com.onesignal.OSPermissionSubscriptionState;
import com.onesignal.OneSignal;
import com.onesignal.OneSignal.LOG_LEVEL;
import com.onesignal.OneSignal.NotificationOpenedHandler;
import com.onesignal.OneSignal.NotificationReceivedHandler;
import com.onesignal.OneSignal.OSInFocusDisplayOption;
import org.json.JSONObject;
#DesignerComponent(version = 1, description = "This Extension was created with the AppyBuilder Code Editor.<br>" +
"Create your own here:<br><a href='https://editor.appybuilder.com' target='_blank'>https://editor.appybuilder.com</a><br>",
category = ComponentCategory.EXTENSION,
nonVisible = true, iconName = "http://appyBuilder.com/extensions/icons/extension.png")
#SimpleObject(external = true)
public class OneSignalPlus extends AndroidNonvisibleComponent {
private ComponentContainer container;
private boolean soundEnabled = true;
private boolean subscriptionEnabled = true;
private boolean vibrateEnabled = true;
private class ExampleNotificationReceivedHandler implements NotificationReceivedHandler {
private ExampleNotificationReceivedHandler() {
}
public void notificationReceived(OSNotification notification) {
JSONObject data = notification.payload.additionalData;
String notificationID = notification.payload.notificationID;
String title = notification.payload.title;
String body = notification.payload.body;
String smallIcon = notification.payload.smallIcon;
String largeIcon = notification.payload.largeIcon;
String bigPicture = notification.payload.bigPicture;
String smallIconAccentColor = notification.payload.smallIconAccentColor;
String sound = notification.payload.sound;
String ledColor = notification.payload.ledColor;
int lockScreenVisibility = notification.payload.lockScreenVisibility;
String groupKey = notification.payload.groupKey;
String groupMessage = notification.payload.groupMessage;
String fromProjectNumber = notification.payload.fromProjectNumber;
String rawPayload = notification.payload.rawPayload;
Log.d("OneSignalPush", "NotificationID received: " + notificationID);
if (data != null) {
String customKey = data.optString("customkey", null);
if (customKey != null) {
Log.d("OneSignalPush", "customkey set with value: " + customKey);
}
}
}
}
class NotificationOpenHandler implements NotificationOpenedHandler {
NotificationOpenHandler() {
}
public void notificationOpened(OSNotificationOpenResult osNotificationOpenResult) {
ActionType actionType = osNotificationOpenResult.action.type;
JSONObject data = osNotificationOpenResult.notification.payload.additionalData;
Log.d("OneSignalPush", "NotificationID received: " + data);
if (data != null) {
String customKey = data.optString("customkey", null);
if (customKey != null) {
Log.i("OneSignalExample", "customkey set with value: " + customKey);
} else {
Log.i("OneSignalExample", "No data");
}
}
}
}
public OneSignalPlus(ComponentContainer container) {
super(container.$form());
this.container = container;
OneSignal.setLogLevel(LOG_LEVEL.DEBUG, LOG_LEVEL.NONE);
OneSignal.startInit(container.$context()).autoPromptLocation(false).setNotificationReceivedHandler(new ExampleNotificationReceivedHandler()).inFocusDisplaying(OSInFocusDisplayOption.Notification).init();
}
/**
* Get Custom Key
*/
#SimpleProperty(category = PropertyCategory.BEHAVIOR, description = "Get custom Key. If ther is no customkey it will return '-1'.")
public final String GetCustomKey(OSNotificationOpenResult osNotificationOpenResult) {
try {
ActionType actionType = osNotificationOpenResult.action.type;
JSONObject data = osNotificationOpenResult.notification.payload.additionalData;
Log.d("OneSignalPush", "NotificationID received: " + data);
if (data != null) {
String customKey = data.optString("customkey", null);
if (customKey != null) {
return customKey;
} else {
return "-1";
}
}
} catch (NullPointerException e) {
return false;
}
}
/**
* Showing Log
*/
#SimpleProperty(description = "If you want to enable the log then set it to true.")
public final void EnableLog(boolean z) {
PushNotifications pushNotifications = this;
if (z) {
LOG_LEVEL log_level = LOG_LEVEL.DEBUG;
OneSignal.setLogLevel(log_level, log_level);
return;
}
OneSignal.setLogLevel(LOG_LEVEL.DEBUG, LOG_LEVEL.NONE);
}
#SimpleProperty(category = PropertyCategory.BEHAVIOR, description = "Get the subscription Status")
public final boolean GetSubscriptionStatus() {
try {
return OneSignal.getPermissionSubscriptionState().getSubscriptionStatus().getSubscribed();
} catch (NullPointerException e) {
return false;
}
}
}
but the code when compiled gives a report of the error "missing return statement". you can try to build this code here codeEditor
edited:
i have tried to add return statement after if like this
public final String GetCustomKey(OSNotificationOpenResult osNotificationOpenResult) {
ActionType actionType = osNotificationOpenResult.action.type;
JSONObject data = osNotificationOpenResult.notification.payload.additionalData;
String customKey;
if (data != null) {
customKey = data.optString("customkey", null);
if (customKey != null) {
return customKey;
} else {
return "-1";
}
}
return "-1";
}
or
public final String GetCustomKey(OSNotificationOpenResult osNotificationOpenResult) {
ActionType actionType = osNotificationOpenResult.action.type;
JSONObject data = osNotificationOpenResult.notification.payload.additionalData;
String customKey;
if (data != null) {
customKey = data.optString("customkey", null);
if (customKey != null) {
return customKey;
}
}
return "-1";
}
but it give me more warning and error report
can you give me a clue what is wrong or less from the code
You need to remove the return "-1"; out of the inner if statement.
public final String GetCustomKey() {
if (data != null) {
customKey = data.optString("customkey", null);
if (customKey != null) {
return customKey;
}
}
return "-1";
}
For bonus points, you can clean the method up a little such as
public final String GetCustomKey(OSNotificationOpenResult osNotificationOpenResult) {
ActionType actionType = osNotificationOpenResult.action.type;
JSONObject data = osNotificationOpenResult.notification.payload.additionalData;
return data.containsKey("customkey") ? data.get("customkey").toString() : "-1";
}
I am currently taking each column based on query and modifying variables based on the current position of the cursor. I was wondering if it would be possible to cut down the size of the code by doing something like this where a different function call would be made based on the column within the cursor that is currently being referenced:
do {
Ticket ticket = new Ticket();
for(int i = 0; i < cursor.getColumnCount(); i++)
{
if (cursor.getString(0) != null) {
/*Where the array contains a list of function calls*/
ticket.arrayList(i);
}
}while(cursor.moveToNext());
Below is the code I currently have. From what I know there isn't anything in Java that works like this, but I'm trying to cut down on the number of lines here as I will eventually have close to one hundred columns that will be pulled into the cursor.
public List<Ticket> getTickets(Context context, SQLiteDatabase db)
{
List<Ticket> ticketInfo = new ArrayList<>();
String selectQuery = "SELECT * FROM " + TABLE_TICKET;
Cursor cursor = null;
try {
cursor = db.rawQuery(selectQuery, null);
if (cursor != null) {
try {
if (cursor.moveToFirst()) {
do {
Ticket ticket = new Ticket();
//Set the ticket number
if (cursor.getString(0) != null) {
ticket.setTicketNr(Integer.parseInt(cursor.getString(0)));
}
//Set the ticket id
if (cursor.getString(1) != null) {
ticket.setTicketId(Integer.parseInt(cursor.getString(1)));
}
//
if (cursor.getString(2) != null) {
ticket.setServiceName(cursor.getString(2));
}
//
if (cursor.getString(3) != null) {
ticket.setServiceHouseNr(Integer.parseInt(cursor.getString(3)));
}
//
if (cursor.getString(4) != null) {
ticket.setServiceDirectional(cursor.getString(4));
}
//
if (cursor.getString(5) != null) {
ticket.setServiceStreetName(cursor.getString(5));
}
//
if (cursor.getString(6) != null) {
ticket.setServiceCommunityName(cursor.getString(6));
}
//
if (cursor.getString(7) != null) {
ticket.setServiceState(cursor.getString(7));
}
//
if (cursor.getString(8) != null) {
ticket.setServiceZip1(Integer.parseInt(cursor.getString(8)));
}
//
if (cursor.getString(9) != null) {
ticket.setServiceZip2(Integer.parseInt(cursor.getString(9)));
}
//
if (cursor.getString(10) != null) {
ticket.setTroubleReported(cursor.getString(10));
}
// Adding exercise to list
if (ticket != null) {
ticketInfo.add(ticket);
}
} while (cursor.moveToNext());
} else {
//No results from query
Toast.makeText(context.getApplicationContext(), "No tickets found", Toast.LENGTH_LONG).show();
}
} finally {
if (cursor != null && !cursor.isClosed()) {
cursor.close();
}
}
}
}
catch(SQLiteException exception)//If exception is found
{
Log.d(TAG, "Error", exception);
//Display exception
Toast.makeText(context.getApplicationContext(), exception.toString(), Toast.LENGTH_LONG).show();
}
return ticketInfo;
}
Thank you for any insights into this.
I think this would do it. Just advance the cursor and pass it into the Ticket constructor. You may want to add some error checking.
public class Ticket {
private static class Field {
int intValue;
String stringValue;
final Class type;
Field(Class fieldType){
type = fieldType;
}
void set(String value){
if(type.equals(String.class)){
stringValue = value;
}
else {
intValue = Integer.parseInt(value);
}
}
}
private List<Field> fields = new ArrayList<>();
private Field addField(Field field){
fields.add(field);
return field;
}
// This solution relies on adding fields in the order they'll be retrieved in the cursor.
// Other options are possible such as a map by column index.
private Field ticketNumber = addField(new Field(Integer.class));
private Field serviceName = addField(new Field(String.class));
public Ticket(Cursor cursor){
for(int i=0; i < fields.size(); i++){
Field f = fields.get(i);
f.set(cursor.getString(i));
}
}
}
public int getTicketNumber(){
return ticketNumber.intValue;
}
// Don't know if you need setters
public void setTicketNumber(int value){
ticketNumber.intValue = value;
}
// etc for remaining fields
I would also consider using an ORM to make this stuff easier, rather than dealing with cursors.
My code look awful, and i want do it better way.
if (e == null && !result.isJsonNull() && result.get("code").getAsInt() == 200) {
JsonArray array = result.get("data").getAsJsonObject().get("products").getAsJsonArray();
ProductDAO productDAO = new ProductDAO(getApplicationContext());
for (int i = 0; i < array.size(); i++) {
Product product = new Product();
if (!isProduct(array.get(i).getAsJsonObject().get("id").getAsString())) {
if (!array.get(i).getAsJsonObject().get("_vat_amount").isJsonNull() && !array.get(i).getAsJsonObject().get("_vat_amount").toString().equals("")) {
product.setVatAmount(array.get(i).getAsJsonObject().get("_vat_amount").getAsDouble());
}
if (!array.get(i).getAsJsonObject().get("_vat_rate").isJsonNull() && !array.get(i).getAsJsonObject().get("_vat_rate").toString().equals("")) {
product.setVatRate(array.get(i).getAsJsonObject().get("_vat_rate").getAsDouble());
}
if (!array.get(i).getAsJsonObject().get("_vat_rate_s").isJsonNull() && !array.get(i).getAsJsonObject().get("_vat_rate_s").toString().equals("")) {
product.setVatRateS(array.get(i).getAsJsonObject().get("_vat_rate_s").getAsString());
}
if (!array.get(i).getAsJsonObject().get("brutto_value").isJsonNull() && !array.get(i).getAsJsonObject().get("brutto_value").toString().equals("")) {
product.setBruttoValue(array.get(i).getAsJsonObject().get("brutto_value").getAsDouble());
}
if (!array.get(i).getAsJsonObject().get("count").isJsonNull() && !array.get(i).getAsJsonObject().get("count").toString().equals("")) {
product.setCount(array.get(i).getAsJsonObject().get("count").getAsDouble());
}
if (!array.get(i).getAsJsonObject().get("id").isJsonNull() && !array.get(i).getAsJsonObject().get("id").toString().equals("")) {
product.setFinettoID(array.get(i).getAsJsonObject().get("id").getAsInt());
}
if (!array.get(i).getAsJsonObject().get("lp").isJsonNull() && !array.get(i).getAsJsonObject().get("lp").toString().equals("")) {
product.setLp(array.get(i).getAsJsonObject().get("lp").getAsInt());
}
if (!array.get(i).getAsJsonObject().get("name").isJsonNull() && !array.get(i).getAsJsonObject().get("name").toString().equals("")) {
product.setName(array.get(i).getAsJsonObject().get("name").getAsString());
}
if (!array.get(i).getAsJsonObject().get("netto_value").isJsonNull() && !array.get(i).getAsJsonObject().get("netto_value").toString().equals("")) {
product.setNettoValue(array.get(i).getAsJsonObject().get("netto_value").getAsDouble());
}
if (!array.get(i).getAsJsonObject().get("price").isJsonNull() && !array.get(i).getAsJsonObject().get("price").toString().equals("")) {
product.setPrice(array.get(i).getAsJsonObject().get("price").getAsDouble());
}
if (!array.get(i).getAsJsonObject().get("unit").isJsonNull() && !array.get(i).getAsJsonObject().get("unit").toString().equals("")) {
product.setUnit(array.get(i).getAsJsonObject().get("unit").getAsString());
}
productDAO.save(product);
}
}
Is some way to create array with void/methods (setters)? I can cut some this json. This will be some better. But i want do it more better.
I would create some methods like this (one for each type):
private String getAsString(String key, JsonObject jsonObject) {
if (jsonObject.get(key).isJsonNull() && !jsonObject.get(key).toString().equals("")) {
return jsonObject.get(key).getAsString());
} else {
return null;
}
}
Now you can just do this:
JsonObject jsonObject = array.get(i).getAsJsonObject();
product.setVatAmount(getAsDouble("_vat_amount", jsonObject));
product.setVatRate(getAsDouble("_vat_rate", jsonObject));
product.setVatRateS(getAsString("_vat_rate_s", jsonObject));
and so on.
my app uses another projects which contains references to classes as java.beans.propertydescriptor which is not contained by android libraries.
The situation is the next: my project contains the .jar files with this another projects as libraries. I read that the solution is use an opensource class. I found it, but i dont know how can i add this class to the android .jar file. So, how can i add this class to the android java.beans library?
This is the class i have found:
package java.beans;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.Vector;
import org.apache.harmony.beans.internal.nls.Messages;
public class PropertyDescriptor extends FeatureDescriptor {
private Method getter;
private Method setter;
private Class<?> propertyEditorClass;
private boolean constrained;
private boolean bound;
public PropertyDescriptor(String propertyName, Class<?> beanClass,
String getterName, String setterName) throws IntrospectionException {
super();
if (beanClass == null) {
throw new IntrospectionException(Messages.getString("beans.03")); //$NON-NLS-1$
}
if (propertyName == null || propertyName.length() == 0) {
throw new IntrospectionException(Messages.getString("beans.04")); //$NON-NLS-1$
}
this.setName(propertyName);
this.setDisplayName(propertyName);
if (setterName != null) {
if (hasMethod(beanClass, setterName)) {
setWriteMethod(beanClass, setterName);
} else {
throw new IntrospectionException(Messages.getString("beans.20")); //$NON-NLS-1$
}
}
if (getterName != null) {
if (hasMethod(beanClass, getterName)) {
setReadMethod(beanClass, getterName);
} else {
throw new IntrospectionException(Messages.getString("beans.1F")); //$NON-NLS-1$
}
}
}
public PropertyDescriptor(String propertyName, Method getter, Method setter)
throws IntrospectionException {
super();
if (propertyName == null || propertyName.length() == 0) {
throw new IntrospectionException(Messages.getString("beans.04")); //$NON-NLS-1$
}
this.setName(propertyName);
this.setDisplayName(propertyName);
setWriteMethod(setter);
setReadMethod(getter);
}
public PropertyDescriptor(String propertyName, Class<?> beanClass)
throws IntrospectionException {
String getterName;
String setterName;
if (beanClass == null) {
throw new IntrospectionException(Messages.getString("beans.03")); //$NON-NLS-1$
}
if (propertyName == null || propertyName.length() == 0) {
throw new IntrospectionException(Messages.getString("beans.04")); //$NON-NLS-1$
}
this.setName(propertyName);
this.setDisplayName(propertyName);
getterName = createDefaultMethodName(propertyName, "is"); //$NON-NLS-1$
if (hasMethod(beanClass, getterName)) {
setReadMethod(beanClass, getterName);
} else {
getterName = createDefaultMethodName(propertyName, "get"); //$NON-NLS-1$
if (hasMethod(beanClass, getterName)) {
setReadMethod(beanClass, getterName);
}
}
setterName = createDefaultMethodName(propertyName, "set"); //$NON-NLS-1$
if (hasMethod(beanClass, setterName)) {
setWriteMethod(beanClass, setterName);
}
if (getter == null && setter == null) {
throw new IntrospectionException(Messages.getString(
"beans.01", propertyName)); //$NON-NLS-1$
}
}
public void setWriteMethod(Method setter) throws IntrospectionException {
if (setter != null) {
int modifiers = setter.getModifiers();
if (!Modifier.isPublic(modifiers)) {
throw new IntrospectionException(Messages.getString("beans.05")); //$NON-NLS-1$
}
Class<?>[] parameterTypes = setter.getParameterTypes();
if (parameterTypes.length != 1) {
throw new IntrospectionException(Messages.getString("beans.06")); //$NON-NLS-1$
}
Class<?> parameterType = parameterTypes[0];
Class<?> propertyType = getPropertyType();
if (propertyType != null && !propertyType.equals(parameterType)) {
throw new IntrospectionException(Messages.getString("beans.07")); //$NON-NLS-1$
}
}
this.setter = setter;
}
public void setReadMethod(Method getter) throws IntrospectionException {
if (getter != null) {
int modifiers = getter.getModifiers();
if (!Modifier.isPublic(modifiers)) {
throw new IntrospectionException(Messages.getString("beans.0A")); //$NON-NLS-1$
}
Class<?>[] parameterTypes = getter.getParameterTypes();
if (parameterTypes.length != 0) {
throw new IntrospectionException(Messages.getString("beans.08")); //$NON-NLS-1$
}
Class<?> returnType = getter.getReturnType();
if (returnType.equals(Void.TYPE)) {
throw new IntrospectionException(Messages.getString("beans.33")); //$NON-NLS-1$
}
Class<?> propertyType = getPropertyType();
if ((propertyType != null) && !returnType.equals(propertyType)) {
throw new IntrospectionException(Messages.getString("beans.09")); //$NON-NLS-1$
}
}
this.getter = getter;
}
public Method getWriteMethod() {
return setter;
}
public Method getReadMethod() {
return getter;
}
#Override
public boolean equals(Object object) {
boolean result = (object != null && object instanceof PropertyDescriptor);
if (result) {
PropertyDescriptor pd = (PropertyDescriptor) object;
boolean gettersAreEqual = (this.getter == null)
&& (pd.getReadMethod() == null) || (this.getter != null)
&& (this.getter.equals(pd.getReadMethod()));
boolean settersAreEqual = (this.setter == null)
&& (pd.getWriteMethod() == null) || (this.setter != null)
&& (this.setter.equals(pd.getWriteMethod()));
boolean propertyTypesAreEqual = this.getPropertyType() == pd
.getPropertyType();
boolean propertyEditorClassesAreEqual = this
.getPropertyEditorClass() == pd.getPropertyEditorClass();
boolean boundPropertyAreEqual = this.isBound() == pd.isBound();
boolean constrainedPropertyAreEqual = this.isConstrained() == pd
.isConstrained();
result = gettersAreEqual && settersAreEqual
&& propertyTypesAreEqual && propertyEditorClassesAreEqual
&& boundPropertyAreEqual && constrainedPropertyAreEqual;
}
return result;
}
public void setPropertyEditorClass(Class<?> propertyEditorClass) {
this.propertyEditorClass = propertyEditorClass;
}
public Class<?> getPropertyType() {
Class<?> result = null;
if (getter != null) {
result = getter.getReturnType();
} else if (setter != null) {
Class<?>[] parameterTypes = setter.getParameterTypes();
result = parameterTypes[0];
}
return result;
}
public Class<?> getPropertyEditorClass() {
return propertyEditorClass;
}
public void setConstrained(boolean constrained) {
this.constrained = constrained;
}
public void setBound(boolean bound) {
this.bound = bound;
}
public boolean isConstrained() {
return constrained;
}
public boolean isBound() {
return bound;
}
boolean hasMethod(Class<?> beanClass, String methodName) {
Method[] methods = findMethods(beanClass, methodName);
return (methods.length > 0);
}
String createDefaultMethodName(String propertyName, String prefix) {
String result = null;
if (propertyName != null) {
String bos = propertyName.substring(0, 1).toUpperCase();
String eos = propertyName.substring(1, propertyName.length());
result = prefix + bos + eos;
}
return result;
}
Method[] findMethods(Class<?> aClass, String methodName) {
Method[] allMethods = aClass.getMethods();
Vector<Method> matchedMethods = new Vector<Method>();
Method[] result;
for (Method method : allMethods) {
if (method.getName().equals(methodName)) {
matchedMethods.add(method);
}
}
result = new Method[matchedMethods.size()];
for (int j = 0; j < matchedMethods.size(); ++j) {
result[j] = matchedMethods.elementAt(j);
}
return result;
}
void setReadMethod(Class<?> beanClass, String getterName) {
boolean result = false;
Method[] getters = findMethods(beanClass, getterName);
for (Method element : getters) {
try {
setReadMethod(element);
result = true;
} catch (IntrospectionException ie) {
}
if (result) {
break;
}
}
}
void setWriteMethod(Class<?> beanClass, String setterName)
throws IntrospectionException {
boolean result = false;
Method[] setters = findMethods(beanClass, setterName);
for (Method element : setters) {
try {
setWriteMethod(element);
result = true;
} catch (IntrospectionException ie) {
}
if (result) {
break;
}
}
}
public PropertyEditor createPropertyEditor(Object bean) {
PropertyEditor editor;
if (propertyEditorClass == null) {
return null;
}
if (!PropertyEditor.class.isAssignableFrom(propertyEditorClass)) {
// beans.48=Property editor is not assignable from the
// PropertyEditor interface
throw new ClassCastException(Messages.getString("beans.48")); //$NON-NLS-1$
}
try {
Constructor<?> constr;
try {
// try to look for the constructor with single Object argument
constr = propertyEditorClass.getConstructor(Object.class);
editor = (PropertyEditor) constr.newInstance(bean);
} catch (NoSuchMethodException e) {
// try no-argument constructor
constr = propertyEditorClass.getConstructor();
editor = (PropertyEditor) constr.newInstance();
}
} catch (Exception e) {
// beans.47=Unable to instantiate property editor
RuntimeException re = new RuntimeException(
Messages.getString("beans.47"), e); //$NON-NLS-1$
throw re;
}
return editor;
}
}
Thanks.
I downloaded from this page https://code.google.com/p/openbeans/downloads/detail?name=openbeans-1.0.jar the openbean.jar. Then, i imported this jar to the project and changed the references at imported library.
Then export again the project as .jar library and import in the android project.