android enum iterating without switch - android

I have Enums with Exception number and description. I pass exception number to MessageHandler.
And then i want to handle them and show user message with error description.
What is the best way to itterate over results without using switch construction ?
I have a few solutions but i'm not sure which is better for android.
Thank you.

There's actually a fairly straight-forward way to do this, and to do it in a way that doesn't depend on a particular enum. I ran into this problem when wanting to use enums to populate different parts of the UI.
Here is a little bit of sample code to show you how I did it:
public int enumPosition(Enum<?> lookingFor, Enum<?>[] lookingIn)
{
for (int i = 0; i < lookingIn.length; i++)
{
if (lookingIn[i].getValue().equals(lookingFor.getValue()))
{
//Found Answer
}
}
}
Of course, depending on what you need there are good ways to setup your enum to allow for better access and searching, here's what I mean:
public enum ExampleEnum
{
firstValue("#1", 1),
secondValue("#2", 2),
thirdValue("#3", 3);
private final String id;
private final int somethingUseful;
ExampleEnum(String id, int usefulValue)
{
this.id = id;
this.somethingUseful = usefulValue;
}
public String getValue() { return id; }
public int getSomethingUseful () { return somethingUseful; }
public static ExampleEnumfromString(String text)
{
if (text != null)
{
for (ExampleEnumt : ExampleEnum.values())
{
if (text.equalsIgnoreCase(t.id))
{
return t;
}
}
}
//Usually best to throw an exception here
return ExampleEnum.firstValue;
}
//Useful for passing to adapters
public static String[] getValues()
{
String[] vals = new String[ExampleEnum.values().length];
int i = 0;
for (ExampleEnumt : ExampleEnum.values())
{
vals[i] = t.getValue();
i++;
}
return vals;
}
#Override
public String toString()
{
return getValue();
}
}

import java.util.HashMap;
import java.util.Map;
import android.content.Context;
import android.content.res.Resources;
import com.cyberneticscore.voliastatis.R;
public enum ExceptionEnums {
NO_ERROR(1),
CONNECTION_ERROR(2),
LOGIN_ERROR (3),
SSL_ERROR (4),
WRONG_DATE (5),
INTERRUPTED (6),
CLIENT_PROTOCOL_ERROR(7),
UNKNOWN_HOST_ERROR(8),
IO_ERROR (9),
XPATHER_ERROR(10);
private static final Map<Integer, String> map = new HashMap<Integer, String>();
private static Context context;
private static Resources reso;
public static void getContext(Context _context)
{
context =_context;
reso = context.getResources();
}
private int pos;
public static void putMapValues(){
//static{
map.put(NO_ERROR.getPos(), reso.getString(R.string.exceptions_no_error));
map.put(CONNECTION_ERROR.getPos(), reso.getString(R.string.exceptions_connection_error));
map.put(LOGIN_ERROR.getPos(), reso.getString(R.string.exceptions_login_error));
map.put(SSL_ERROR.getPos(), reso.getString(R.string.exceptions_ssl_error));
map.put(WRONG_DATE.getPos(), reso.getString(R.string.exceptions_wrong_date));
map.put(INTERRUPTED.getPos(), reso.getString(R.string.exceptions_interrupted));
map.put(CLIENT_PROTOCOL_ERROR.getPos(), reso.getString(R.string.exceptions_client_protocol_error));
map.put(UNKNOWN_HOST_ERROR.getPos(), reso.getString(R.string.exceptions_unknown_host_error));
map.put(IO_ERROR.getPos(), reso.getString(R.string.exceptions_io_error));
map.put(XPATHER_ERROR.getPos(), reso.getString(R.string.exceptions_xpather_error));
}
ExceptionEnums(int pos){
this.pos = pos;
}
public int getPos(){
return pos;
}
public static String getErrorDescription(int position_number){
return map.get(position_number);
}
}

Related

How can I temporary save data? such as shopping cart in android app

I am the begginer android developer. I have a problem about saving shopping cart data temporary. It's a custom shirts app. Guest should select collar, cuffs, and so on.
I used listview to show these selected items and options which guest selected.
public class Cart_item_list {
private static int cart_itemimage;
private static String cart_itemname;
private static String cart_itemprice;
private static String cart_collar;
private static String cart_cuffs;
private static String cart_placket;
private static String cart_pocket;
private static String cart_fit;
private static String cart_initial;
public static int getCart_itemimage() {
return cart_itemimage;
}
public static void setCart_itemimage(int cart_itemimage) {
Cart_item_list.cart_itemimage = cart_itemimage;
}
public static String getCart_itemname() {
return cart_itemname;
}
public static void setCart_itemname(String cart_itemname) {
Cart_item_list.cart_itemname = cart_itemname;
}
public static String getCart_itemprice() {
return cart_itemprice;
}
public static void setCart_itemprice(String cart_itemprice) {
Cart_item_list.cart_itemprice = cart_itemprice;
}
public static String getCart_collar() {
return cart_collar;
}
public static void setCart_collar(String cart_collar) {
Cart_item_list.cart_collar = cart_collar;
}
public static String getCart_cuffs() {
return cart_cuffs;
}
public static void setCart_cuffs(String cart_cuffs) {
Cart_item_list.cart_cuffs = cart_cuffs;
}
public static String getCart_placket() {
return cart_placket;
}
public static void setCart_placket(String cart_placket) {
Cart_item_list.cart_placket = cart_placket;
}
public static String getCart_pocket() {
return cart_pocket;
}
public static void setCart_pocket(String cart_pocket) {
Cart_item_list.cart_pocket = cart_pocket;
}
public static String getCart_fit() {
return cart_fit;
}
public static void setCart_fit(String cart_fit) {
Cart_item_list.cart_fit = cart_fit;
}
public static String getCart_initial() {
return cart_initial;
}
public static void setCart_initial(String cart_initial) {
Cart_item_list.cart_initial = cart_initial;
}
public Cart_item_list(int cart_itemimage, String cart_itemname, String cart_itemprice, String cart_collar, String cart_cuffs, String cart_placket, String cart_pocket, String cart_fit, String cart_initial) {
this.cart_itemimage = cart_itemimage;
this.cart_itemname = cart_itemname;
this.cart_itemprice = cart_itemprice;
this.cart_collar = cart_collar;
this.cart_cuffs = cart_cuffs;
this.cart_placket = cart_placket;
this.cart_pocket = cart_pocket;
this.cart_fit = cart_fit;
this.cart_initial = cart_initial;
}
}
it's the item list for listview adapter.
package com.example.yeong.shifendingzhi;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.ArrayList;
public class Cart_item_adapter extends BaseAdapter {
Context context;
ArrayList<Cart_item_list> cart_item_listArrayList;
public Cart_item_adapter(Context context, ArrayList<Cart_item_list> cart_item_listArrayList) {
this.context = context;
this.cart_item_listArrayList = cart_item_listArrayList;
}
#Override
public int getCount() {
return cart_item_listArrayList.size();
}
#Override
public Object getItem(int i) {
return cart_item_listArrayList.get(i);
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
view = LayoutInflater.from(context).inflate(R.layout.cart_listview, null);
ImageView selected_item_image = (ImageView) view.findViewById(R.id.selected_item_image);
TextView selected_cart_name = (TextView) view.findViewById(R.id.selected_cart_name);
TextView selected_cart_cuffs = (TextView) view.findViewById(R.id.selected_cart_cuffs);
TextView selected_cart_initial = (TextView) view.findViewById(R.id.selected_cart_initial);
TextView selected_cart_placket = (TextView) view.findViewById(R.id.selected_cart_placket);
TextView selected_cart_fit = (TextView) view.findViewById(R.id.selected_cart_fit);
TextView selected_cart_pocket = (TextView) view.findViewById(R.id.selected_cart_pocket);
TextView selected_cart_price = (TextView) view.findViewById(R.id.selected_cart_price);
TextView selected_cart_collar = (TextView) view.findViewById(R.id.selected_cart_collar);
selected_cart_name.setText(cart_item_listArrayList.get(i).getCart_itemname());
selected_cart_cuffs.setText(cart_item_listArrayList.get(i).getCart_cuffs());
selected_cart_initial.setText(cart_item_listArrayList.get(i).getCart_initial());
selected_cart_placket.setText(cart_item_listArrayList.get(i).getCart_placket());
selected_cart_fit.setText(cart_item_listArrayList.get(i).getCart_fit());
selected_cart_pocket.setText(cart_item_listArrayList.get(i).getCart_pocket());
selected_cart_price.setText(cart_item_listArrayList.get(i).getCart_itemprice());
selected_cart_collar.setText(cart_item_listArrayList.get(i).getCart_collar());
selected_item_image.setImageResource(cart_item_listArrayList.get(i).getCart_itemimage());
return view;
}
}
it's the listview adapter
I tried to create global variable arraylist, and shearched a lot, but all failed, singleton, using appllication.
Could you help me to make global arraylist for listview?
It helps me to save data temporary and chage the arraylist data on another activity.
Thanks.
I recommend the Paper library from https://github.com/pilgr/Paper
it is easy to configure and no need to setup any sql kind of connections , its like writing in a text file locally.
I used it and it is solid.
I mainly used it for storing the username and password for Remember Me in the login activity page:
if(ckbRemember.isChecked())
{
Paper.book().write(Common.USER_KEY,edtUsername.getText().toString());
Paper.book().write(Common.PWD_KEY,edtPassword.getText().toString());
}
and when you want to clear the data at any time and from any activity is like:
Paper.book().destroy();
if you want to store all of those values longer (e.g. for a few days or if the user closes your app) you can store those values in the shared preferences:
SharedPreferences spInstance = getSharedPreferences("my_identifier", Context.MODE_PRIVATE);
SharedPreferences.Editor spEditor = spInstance.edit();
spEditor.putString("key", "value");
spEditor.apply(); // Save the data
//Retrieve the data:
SharedPreferences spInstance = getSharedPreferences("my_identifier", Context.MODE_PRIVATE);
SharedPreferences.Editor spEditor = spInstance.edit();
String myString = spInstance.getString("key", "default-value");
That's it!
Use a simple POJO class. Make a java class that stores shirts attributes. Then declare a global arraylist with that class as its primitive type.
public class Shirt{
String cuffs;
String plackets;
String collars;
...
public String getCuff(){...}
public String getCollar(){...}
public void setCuff(){...}
public void setCollar(){...}
}
ArrayList<Shirt> shirts = new ArrayList<>();
Now you have to either store it in a SharedPreference or some database if you want it to persist. If you don't want storage but need a global context type variable, you can use Application class or a static variable maybe depending on whatever your use case is.
Edit: A simple example of Application class. Do remember to name the package in your Manifest.
Android provides several optionsto save persistent application data. The solution you choose depends on your specific needs, such as whether the data should be private, persistent and how much space your data requires. Take a look at Developers Guide

What is the best way to implement Color Detection in Android?

I want to implement color detection in Android. What I exactly want to do is that after taking a picture with Android Camera, I want to detect the color of object in that picture. My goal is detecting colors according to color intensity. At this point, I searched and saw different approaches related to this goal. There are some algorithms which converts the images into Bitmap and then detects the colors, some of them use RGB. Additionally, I saw that OpenCV is also a known solution for this problem.
Now, I wonder which way I should follow. Which way is better for my case. Are there anyone who can help and direct me through a method?
Any help will be appreciated. Thank you all in advance.
If I understand your question correctly, you want a method that will take an image and determine the most dominant color in that method and then return the result.
I have put together a class that should provide you with the result, don't know if it's the most efficient algorithm but give it a try.
To implement the solution you can do the following
new ColorFinder(new CallbackInterface() {
#Override
public void onCompleted(String color) {
Toast.makeText(context, "Your Color : " + color, Toast.LENGTH_SHORT).show();
}
}).findDominantColor(yourBitmap);
ColorFinder.java
import android.graphics.Bitmap;
import android.os.AsyncTask;
import java.util.HashMap;
import java.util.Map;
/**
* Created by Neil on 15/02/23.
*/
public class ColorFinder {
private static final String TAG = ColorFinder.class.getSimpleName();
private CallbackInterface callback;
public ColorFinder(CallbackInterface callback) {
this.callback = callback;
}
public void findDominantColor(Bitmap bitmap) {
new GetDominantColor().execute(bitmap);
}
private int getDominantColorFromBitmap(Bitmap bitmap) {
int [] pixels = new int[bitmap.getWidth()*bitmap.getHeight()];
bitmap.getPixels(pixels,0,bitmap.getWidth(),0,0, bitmap.getWidth(), bitmap.getHeight());
Map<Integer, PixelObject> pixelList = getMostDominantPixelList(pixels);
return getDominantPixel(pixelList);
}
private Map<Integer, PixelObject> getMostDominantPixelList(int [] pixels) {
Map<Integer, PixelObject> pixelList = new HashMap<>();
for (int pixel : pixels) {
if (pixelList.containsKey(pixel)) {
pixelList.get(pixel).pixelCount++;
} else {
pixelList.put(pixel, new PixelObject(pixel, 1));
}
}
return pixelList;
}
private int getDominantPixel(Map<Integer, PixelObject> pixelList) {
int dominantColor = 0;
int largestCount = 0;
for (Map.Entry<Integer, PixelObject> entry : pixelList.entrySet()) {
PixelObject pixelObject = entry.getValue();
if (pixelObject.pixelCount > largestCount) {
largestCount = pixelObject.pixelCount;
dominantColor = pixelObject.pixel;
}
}
return dominantColor;
}
private class GetDominantColor extends AsyncTask<Bitmap, Integer, Integer> {
#Override
protected Integer doInBackground(Bitmap... params) {
int dominantColor = getDominantColorFromBitmap(params[0]);
return dominantColor;
}
#Override
protected void onPostExecute(Integer dominantColor) {
String hexColor = colorToHex(dominantColor);
if (callback != null)
callback.onCompleted(hexColor);
}
private String colorToHex(int color) {
return String.format("#%06X", (0xFFFFFF & color));
}
}
public interface CallbackInterface {
public void onCompleted(String dominantColor);
}
}
PixelObject.java
public class PixelObject {
public int pixel;
public int pixelCount;
public PixelObject(int pixel, int pixelCount) {
this.pixel = pixel;
this.pixelCount = pixelCount;
}
}

Difference between storing data in shared preferences and database in android

I am creating an application in android and I want to store data of places user selected on the google map. I am currently storing all the places by adding them all in an array and then serialize them by Gson library and it works fine and coding is very simple and easy but if i use data base instead of that that then the coding will be more complex and because implantation of data base is more complex then simply string the array of places to shared preferences. below is the class whose objects are i am storing and saving in the shared preferences but if want to store them on the data base then i have to go through more complex I have to create queries for insert, delete update etc. so suggest me that should i use db or shred preference is good for saving list of places.
package com.example.googlemapstext;
import java.util.ArrayList;
import android.location.Address;
public class MyPlace {
private int id;
private String placeName;
private Address placeAddress;
private int ringerState;
private int brightnessState;
private int wifiState;
private int gpsState;
private int bluetoothState;
private int radiusValueIndex;
private ArrayList<Contact> contactArrayList;
private String message;
private double radiusValue;
private boolean notificationCheck;
public MyPlace(int id,String placeName, Address placeAddress, String radiusValue,
int ringerState, int brightnessState, int wifiState, int gpsState,
int bluetoothState, int radiusValueIndex, ArrayList<Contact> contactArrayList,
String message, boolean notificationCheck) {
this.id=id;
this.placeName = placeName;
this.placeAddress = placeAddress;
this.radiusValue = getTrimedRadiusValue(radiusValue);
this.ringerState = ringerState;
this.brightnessState = brightnessState;
this.wifiState = wifiState;
this.gpsState = gpsState;
this.bluetoothState = bluetoothState;
this.contactArrayList = contactArrayList;
this.message = message;
this.radiusValueIndex = radiusValueIndex;
this.notificationCheck = notificationCheck;
}
private double getTrimedRadiusValue(String radiusValue)
{
radiusValue=radiusValue.replace("Radius ", "");
radiusValue=radiusValue.replace(" Meters", "");
return Double.parseDouble(radiusValue);
}
public boolean getNotificationCheck() {
return notificationCheck;
}
public void setNotificationCheck(boolean notificationCheck) {
this.notificationCheck = notificationCheck;
}
public int getRadiusValueIndex() {
return radiusValueIndex;
}
public void setRadiusValueIndex(int radiusValueIndex) {
this.radiusValueIndex = radiusValueIndex;
}
public int getRingerState() {
return ringerState;
}
public void setRingerState(int ringerState) {
this.ringerState = ringerState;
}
public int getBrightnessState() {
return brightnessState;
}
public void setBrightnessState(int brightnessState) {
this.brightnessState = brightnessState;
}
public int getWifiState() {
return wifiState;
}
public void setWifiState(int wifiState) {
this.wifiState = wifiState;
}
public int getGpsState() {
return gpsState;
}
public void setGpsState(int gpsState) {
this.gpsState = gpsState;
}
public int getBluetoothState() {
return bluetoothState;
}
public void setBluetoothState(int bluetoothState) {
this.bluetoothState = bluetoothState;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public double getRadiusValue() {
return radiusValue;
}
public void setRadiusValue(String radiusValue) {
this.radiusValue = getTrimedRadiusValue(radiusValue);
}
public String getPlaceName() {
return placeName;
}
public void setPlaceName(String placeName) {
this.placeName = placeName;
}
public Address getPlaceAddress() {
return placeAddress;
}
public void setPlaceAddress(Address placeAddress) {
this.placeAddress = placeAddress;
}
public ArrayList<Contact> getContactArrayList() {
return contactArrayList;
}
public void setContactArrayList(ArrayList<Contact> contactArrayList) {
this.contactArrayList = contactArrayList;
}
public int getId() {
return id`enter code here`;
}
public void setId(int id) {
this.id = id;
}
}
The main difference between SharedPreferences and DataBase is like you mentioned :
SharedPreferences works on an Key-Value pair basis. you simply provide the Key and get back the Value you stored. that's great.
DataBase creates an SQLite Tables and you need to use queries to pull them out.
I think that if you are good with the JSON mechanism that you built, then storing a string in SharedPreferences is all you need.
But when the Data get more and more complex, and you would like quick access to any part of it, I think DB would be easier than parsing and seaching a JSON string all the time.
Yes, it might make you write more code for handling the DB queries..
I think SQLite will be better for you. I only use SharePreferences for small, simple and "key - value" structured data. (and it should be like that)
You have a lot of data, so SQLite is the way to go.
Read this for more information : Pros and Cons of SQLite and Shared Preferences
I think answer depends on how many places you want to save and what do you plan to do with them but I consider DB as hte best way to go.
With a DB you will be able to create queries to get only places you want and not load all places in a list and search in it.
To simplify DB creation (and use) you can try orm for Android like OrmLite and GreenDao. I think OrmLite is easier to use than GreenDao (but second one seems to have better performance...) and you can find multiple examples there.
In my opinion, SharedPreferences should only be used for saving user preferences data.

creating parcelable in android from some of the fields of a class

i have the following class which i intent to pass from one activity to another:
public class Ad extends ListItem implements parcelable{
private String _type;
private String _recordID;
private String _line1;
private String _line2;
private String _line3;
private String _line4;
private String _url;
private IOnUiNeedToUpdateListener _listener;
private boolean _notActive = false;
private String _alertText;
private Double _longitude;
private Double _latitude;
}
i want to pass an array of such objects from one activity to another. however, i do not need to pass all fields.
is it possible to create a parcel only from the desired fields and send it?
It's your code that writes to Parcel and your code that reads from Parcel. So basically yes. You can write whatever you want. Content of all members, content of some, no members, but other values you use to restore state of the object etc, etc.
Try design your class like this..
public class Form implements Parcelable {
private String formdata1;
private String formdata2;
private String formdata3;
private String formdata4;
public Form() {
}
public Form(Parcel in) {
setFormdata1(in.readString());
setFormdata2(in.readString());
setFormdata3(in.readString());
setFormdata4(in.readString());
}
public String getFormdata1() {
return formdata1;
}
public void setFormdata1(String formdata1) {
this.formdata1 = formdata1;
}
public String getFormdata2() {
return formdata2;
}
public void setFormdata2(String formdata2) {
this.formdata2 = formdata2;
}
public String getFormdata3() {
return formdata3;
}
public void setFormdata3(String formdata3) {
this.formdata3 = formdata3;
}
public String getFormdata4() {
return formdata4;
}
public void setFormdata4(String formdata4) {
this.formdata4 = formdata4;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel in, int arg1) {
in.writeString(getFormdata1());
in.writeString(getFormdata2());
in.writeString(getFormdata3());
in.writeString(getFormdata4());
}
public static final Parcelable.Creator<Form> CREATOR = new Parcelable.Creator<Form>() {
#Override
public Form createFromParcel(Parcel in) {
return new Form(in);
}
#Override
public Form[] newArray(int size) {
return new Form[size];
}
};
}

How to Pass Custom Arraylist content from one Activity to another Activity in android

i have an objects in an custom arraylist as "finaljsoncontent", and now i am trying to pass this "finaljsoncontent" array to another Activity, and i have also tried getters and setters, and also bundle, but i cant, help me how to do this.
Thanks in advance.
Check this out: How do I pass an object from one activity to another on Android?
Your class "JSonKey" should implement parcealable or serializable so that Android can "send" it from an activity to the other activity.
You could try implementing Parcelable, then you can pass it in a bundle. You will need to reduce your object to mostly primitive types to do this. Otherwise you can extend the Application class and store it there. You would retrieve that using the call to getApplicationContext(). Or, of course, you could always create some sort of static globals class that all of your classes can reference.
Here is one of my implementations of parcelable..
package warrior.mail.namespace;
import android.os.Parcel;
import android.os.Parcelable;
public class JView implements Parcelable {
public String subject;
public String from;
public boolean unread;
public String body;
public int inboxIndex;
private long id;
public static final Parcelable.Creator<JView> CREATOR = new Parcelable.Creator<JView>() {
public JView createFromParcel(Parcel in) {
return new JView(in);
}
public JView[] newArray(int size) {
return new JView[size];
}
};
public JView(){
body = "";
}
public JView(String subject,String from,boolean unread){
body = "";
this.subject = subject;
this.from = from;
this.unread = unread;
}
public JView(Parcel parcel){
subject = parcel.readString();
from = parcel.readString();
body = parcel.readString();
unread = parcel.createBooleanArray()[0];
inboxIndex = parcel.readInt();
}
#Override
public int describeContents() {
return inboxIndex;
}
#Override
public void writeToParcel(Parcel out, int arg1) {
out.writeString(subject);
out.writeString(from);
out.writeString(body);
boolean[] array = new boolean[] {unread};
out.writeBooleanArray(array);
out.writeInt(inboxIndex);
}
public void setIndex(int index){
inboxIndex = index;
}
public void setUnread(boolean arg){
unread = arg;
}
public void setContent(String content){
body = content;
}
public void setSubject(String subject){
this.subject = subject;
}
public void setFrom(String f){
from = f;
}
public void setId(long arg){
id = arg;
}
public long getId(){
return id;
}
public void updateIndex(){
}
}
You can either make your class Parcelable(android specific) or make it serializable like in java(just write implements Serializable with your class)

Categories

Resources