I have a fairly simple question, how would I name a variable using another variable.
For example:
public static void addSortListItem(int group_id) {
if (lists.contains(group_id)) {
// add item to correct array list
} else {
lists.add(group_id);
// create new array list using the group_id value as name identifier
ArrayList<ExpListObject> group_id = new ArrayList<ExpListObject>();
}
}
In this function I need to create a new arrayList using the group_id integer as the name. The error here is obviously a duplicate local variable, but what is the correct way to name this?
Any help is appreciated!
You are using group_id as both an identifier name and parameter name. That doesn't make sense. Instead, map the new ArrayList to the group_id. For example:
HashMap<Integer,ArrayList<ExpListObject>> hm = new HashMap<Integer,ArrayList<ExpListObject>>();
hm.put(group_id, new ArrayList<ExpListObject>());
You can make something like this using HashMap, this way:
public static void addSortListItem(int group_id) {
//Create a HashMap to storage your lists
HashMap<String, ArrayList<ExpListObject>> mapList = new HashMap<String, ArrayList<ExpListObject>>();
ArrayList<Object> array = mapList.get(String.valueOf(group_id));
if (array != null) {
array.add(new ExpListObject());
} else {
// Insert the new Array into the HashMap
mapList.put(String.valueOf(group_id), new ArrayList<ExpListObject>());
}
}
Or this way:
public static void addSortListItem(int group_id) {
//Create a HashMap to storage your lists
HashMap< Integer, ArrayList<ExpListObject>> mapList = new HashMap< Integer, ArrayList<ExpListObject>>();
ArrayList<Object> array = mapList.get(group_id);
if (array != null) {
array.add(new ExpListObject());
} else {
// Insert the new Array into the HashMap
mapList.put(group_id, new ArrayList<ExpListObject>());
}
}
Related
Please any one can help how to remove particular key from hashmap and then rearrange the keys in hashmap accordingly.
Below is my code.
Set<Integer> integerSet = hashMap.keySet();
int removekey = pos;
ArrayList<Integer> integers = new ArrayList<>();
for (Integer integer : integerSet) {
if (integer > removekey) {
integers.add(integer);
}
}
for (Integer integer : integers) {
if (hashMap.containsKey(integer)) {
AddCardPojo pojo = hashMap.get(integer);
pojo.setImagCard(cardImage[integer - 1]);
hashMap.remove(integer);
hashMap.put(integer - 1, pojo);
}
}[![enter image description here][1]][1]
I have attached screenshot of error
You can directly remove a key value pair,you can directly do
hashMap.remove(removeKey);
as for 're arranging keys in hashmap',
it is a data structure which makes no guarantees of order of data.
Check this answer for more
If you need a particular order as per integer, you could use arraylist
Finally it could be done.
Below is my answer.
hashMap.remove(key);
List<AddCardPojo> hashMapsList=new ArrayList<>();
Iterator it = hashMap.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pair = (Map.Entry)it.next();
hashMapsList.add((AddCardPojo) pair.getValue());
}
hashMap = new HashMap<>();
for(int i=0; i<hashMapsList.size();i++){
hashMap.put(i,hashMapsList.get(i));
}
I am new to parse data from parse.com.I am trying to update a column.The column in parse table is of array type.I am trying to add a value in array.For Example :
it is showing in data browser like this:
["Ado", "Wassja", "Cristi_3"]
And I want to add "ABC" value in this array programmatically like this:
["Ado", "Wassja", "Cristi_3","ABC"]
I have searched for this and got to know that first I need to fetch all the data of that particular row which I have to update ,then put the data in array I have fetch successfully the data for that particular row like this:
ParseQuery<ParseObject> query = ParseQuery.getQuery("UserMaster");
query.whereEqualTo("userName",str_uname2);
query.findInBackground(new FindCallback<ParseObject>() {
#Override
public void done(List<ParseObject> userList, ParseException e) {
dlg.dismiss();
if (e == null) {
if (userList.size()>0) {
for (int i = 0; i < userList.size(); i++) {
ParseObject p = userList.get(i);
str_dbpassword = p.getString("password");
String email = p.getString("email");
List<ParseObject> mfollowers = p.getList("followers");
List<ParseObject> mfollowing = p.getList("following");
ParseFile pp = (ParseFile)p.get("photo");
str_dbuname = p.getString("userName");
}
Log.d("password", "Retrieved " +str_dbpassword +"<uname>"+str_dbuname);
}
}
else {
Alert.alertOneBtn(LoginActivity.this,"Something went wrong!");
}
}
});
Now I have to update data in
List<ParseObject> mfollowers = p.getList("followers");
And
List<ParseObject> mfollowing = p.getList("following");
I don't know how to do this.Please help me.Your small clue will be very helpful.
Per the docs: http://parse.com/docs/android/api/com/parse/ParseObject.html
You can use add, addUnique, addAll, or addAllUnique to add elements to an array on a Parse Object:
someParseObject.add("arrayColumn", "ABC");
someParseObject.saveEventually();
To expand on Fosco's answer:
ParseObject parseObject = new ParseObject("YOURCLASS");
String[] stringArray = ["Ado", "Wassja", "Cristi_3"];
List<String> stringArrayList = new ArrayList(Arrays.asList(stringArray));
if (stringArray != null)parseObject.addAll("YOURCOLUMN", stringArrayList);
Make sure that the security settings for YOURCLASS enable you to create columns automatically or that you have the correct types set for your columns.
I hope that completes Fosco's answer.
I have an array of HashMaps, how to find a particular HashMap entry given a key that is within one of the HashMap entries?
For example, I have this:
ArrayList<HashMap<String, String>> bathroomList = new ArrayList<HashMap<String, String>>();
I also know a key within one of the array entries I want to find:
String selectedKey = ((TextView) view.findViewById(R.id.key)).getText().toString();
How do I iterate the array to find it?
Any help appreciated.
A map is a dictionary. For each key, it has one and only one entry. And there's no point in iterating over a map to find a key, since the whole point af a map is to be able to get the entry for a key in a single method call (O(1) for a HashMap):
String value = map.get(selectedKey)
will get you the value associated with selectedKey in the map.
You want something like a regular for loop to iterate over the arraylist and then just check for null You cannot iterate over a hashmap but if you look for a key and it is not there then it will just return null.
ArrayList< HashMap< String, Object>> bathroomList; //this must be initialized.
public String getEntry(String key) {
int count = bathroomList.length(); // this might be size i can never
// remember
String result = null;
for (int i = 0; i < count; i++) {
result = ((String) bathroomList[i].get(key));
if (result != null) {
break;
}
}
if(result == null){
result = "Key Not Found";
}
return result;
}
Edit to map hashmaps.
public HashMap<String, String> getData(String key) {
String[] hashmapKeys = {"key1", "key2", "key3"};
if(key.equals("key1"){
return bathroomList[0];
}
if(key.equals("key2"){
return bathroomList[1];
}
if(key.equals("key3"){
return bathroomList[2];
}
}
Might i suggest using a different data structure. If you already know that you are maping things with keys then instead of an ArrayList< HashMap< String, String > > you could use a HashMap< String, HashMap<String, String>>
HashMap< String, HashMap<String, String>> bathroomList;
then to get your dataset use
HashMap<String, String>> dataSelected =bathroomList.get(selectedKey);`
Most of the time when you pick something out of a list you will use the arraylist because you pass in the position of the list that the user clicked on. The position in the list is what determines what data was selected anyways.
I have a problem on arraylist and hashmap
As according to my requirement, I am storing the data into HashMap and after that I have created a List as List>.
HashMap<String,String> hashmap;
static List<HashMap<String,String>> hashmap_string;
And while retrieving the value from database and putting it on HashMap and ArrayList like:
contract_number=c.getString(c1);
Log.i("c1.getString,contract_number", contract_number);
String service_level=c.getString(c2);
hashmap=new HashMap<String, String>();
hashmap.put(contract_number, service_level);
hashmap_string.add(hashmap);
And now I want to retrieve the value as String,String
And when I am applying the code as:
for(int i=0;i<hashmap_string.size();i++)
{
Log.i("arraylist", ""+hashmap_string.get(i));
}
I am getting a single string value in the formet as
{Contract,ServiveValue}
but I want to split this into 2 string values...Also these values are redundant and if am using hashMap then it will not showing me the redundant value.
Please help me on this..
It seems you are missing something. When you execute hashmap_string.get(i), you will get the <HashMap<String,String>. So, This is the right value from code.
What you can do is :
HashMap<String, String> hashMap2 = hashmap_string.get(i);
String value = hashMap2.get("your_key");
Other way, you already have two splited string values. you can get that by using keySet() and values() methods over hashMap2 Object.
HashMap (and Maps in general) are used for multiple one-to-one mappings of keys and values. Are you sure you need that? Looking at your code it appears you're using the map as a "Pair" class. I would skip the list, and put everything in the same map, and then iterate over the pairs in the map:
// using tree map to have entries sorted on the key,
// rather than the key's hash value.
Map<String, String> data = new TreeMap<String, String>();
data.put("c1", "s1");
data.put("c2", "s2");
for (Map.Entry<String, String> entry : data.entrySet()) {
String contract = entry.getKey();
String level = entry.getValue();
Log.i("data", contract + " : " + level");
}
would output (assuming TreeSet):
c1 : s1
c2 : s2
Alternatively, create e.g. a ContractServiceLevel class that holds two strings (the contract number and the service level), and put instances of that class in your list.
EDIT:
public final class ContractServiceLevel {
public final String number;
public final String serviceLevel;
public ContractServiceLevel(String c, String s) {
number = c;
serviceLevel = s;
}
}
List<ContractServiceLevel> contracts = new ArrayList<ContractServiceLevel>();
contracts.add(new ContractServiceLevel("c1", "s1.1"));
contracts.add(new ContractServiceLevel("c1", "s1.2"));
contracts.add(new ContractServiceLevel("c2", "s2.1"));
for (ContractServiceLevel contract : contracts) {
Log.i("data", contract.number + ":" + contract.servicveLevel);
}
would output:
c1 : s1.1
c1 : s1.2
c2 : s2.1
String value = hashmap.get("contract");
u will be getting the value as ServiveValue
So I want to save an ordered set of double values, and I want to be able to insert, retrieve or delete any value from this easily. As of such, I'm using a an ArrayList, where I define a class called Doubles to store the double values.
How do I store this arraylist in a record in an SQLite database? I mean...what should the columns type be? Can it be done?
You cannot insert ArrayList directly into Sqlite. Instead, you could use JSONObject (org.json.JSONObject) to insert the ArrayList. Please check below snippet, you can try something like below....
To insert,
JSONObject json = new JSONObject();
json.put("uniqueArrays", new JSONArray(items));
String arrayList = json.toString();
Insert the string into db.
To Read,
Read the string from db as String,
JSONObject json = new JSONObject(stringreadfromsqlite);
ArrayList items = json.optJSONArray("uniqueArrays");
To Insert :
ArrayList<String> inputArray=new ArrayList<String>();
Add Values to inputArray
Gson gson = new Gson();
String inputString= gson.toJson(inputArray);
System.out.println("inputString= " + inputString);
Use "inputString" to save the value of ArrayList<String> in SQLite Database
To retreive:
Get the String from the SQLiteDatabse what you saved and changed into ArrayList type like below:
outputarray is a String which is get from SQLiteDatabase for this example.
Type type = new TypeToken<ArrayList<String>>() {}.getType();
ArrayList<String> finalOutputString = gson.fromJson(outputarray, type);
In my case it was ArrayList of POJO classes Note
private String mNoteTitle;
private int mFingerIndex;
private Point mNoteCoordinates;
public Note(String noteTitle, int fingerIndex, Point noteCoordinates) {
this.mNoteTitle = noteTitle;
this.mFingerIndex = fingerIndex;
this.mNoteCoordinates = noteCoordinates;
}
As manual says JSONObject supports only following types: Object: a JSONObject, JSONArray, String, Boolean, Integer, Long, Double, NULL, or null. May not be NaNs or infinities. So, I should break my Note class into supported objects.
JSONObject json = new JSONObject();
JSONArray jsonArray = new JSONArray();
for(Note note: chordShape.getNotes()){
JSONObject singleNoteJsonObject = new JSONObject();
try {
singleNoteJsonObject.put(SHAPE_NOTE_TITLE, note.getNoteTitle());
singleNoteJsonObject.put(SHAPE_NOTE_FINGER_INDEX, note.getFingerIndex());
singleNoteJsonObject.put(SHAPE_NOTE_X, note.getNoteCoordinates().x);
singleNoteJsonObject.put(SHAPE_NOTE_Y, note.getNoteCoordinates().y);
} catch (JSONException e){
e.printStackTrace();
}
jsonArray.put(singleNoteJsonObject);
}
Pack created array into JSONObject.
try {
json.put(SHAPE_NOTES, jsonArray);
Log.i(TAG, json.toString());
} catch (JSONException e){
e.printStackTrace();
}
Create String.
String notesList = json.toString();
Put created String in ContentValues, cause in my case it's Android app
if(notesList.length() > 0){
contentValues.put(DatabaseHelper.SHAPE_NOTES_LIST, notesList);
}
And when i should read values from SQLite database.
ArrayList<Note> notes = new ArrayList<>();
while(cursor.moveToNext()){
JSONObject jsonNotes = null;
try {
jsonNotes = new JSONObject(cursor.getString(cursor.getColumnIndex(DatabaseHelper.SHAPE_NOTES_LIST)));
} catch (JSONException e){
e.printStackTrace();
}
if(jsonNotes != null){
Log.i(TAG, jsonNotes.toString());
JSONArray jsonArray = jsonNotes.optJSONArray(SHAPE_NOTES);
for(int i = 0; i < jsonArray.length(); i++){
Note note = null;
JSONObject arrayObject = null;
try {
arrayObject = jsonArray.getJSONObject(i);
} catch (JSONException e){
e.printStackTrace();
}
if(arrayObject != null){
try {
note = new Note(
arrayObject.getString(SHAPE_NOTE_TITLE),
arrayObject.getInt(SHAPE_NOTE_FINGER_INDEX),
new Point(
arrayObject.getInt(SHAPE_NOTE_X),
arrayObject.getInt(SHAPE_NOTE_Y)
)
);
} catch (JSONException e){
e.printStackTrace();
}
}
if(note != null){
notes.add(note);
}
}
}
}
cursor.close();
I suggest going through all 3 Notepad tutorials you want to store the values your storing to a database table. you don't store the actual array directly into the database just the data. but you shouldn't actually need to use an array at all instead of adding a new item to the array instead call your db insert method
I've needed to do something similar in my application, where I have a custom class (Foo, Bar, etc.) and I have an ArrayList of foo, bar, etc. that I persist to SQL. My knowledge of SQL isn't strong, but I'll explain my approach here in case it helps.
My understanding is that to store any kind of object, you need to define a particular table for that object type, where the table has separate columns representing the primitive types within that object. Furthermore, to persist and retrieve an ArrayList of those objects, you'll use one table row per ArrayList entry, and iterate over in a loop to store and retrieve.
There are ArrayLists of several custom classes in my application that I wanted to persist to DB. So, to make things tidy (well, to me at least -- I'm still a relatively new Java / Android programmer, so take this with a pinch of salt) I decided to implement a kind of "SQL Serializable Interface" that my DB-persistable objects must implement. Each object (Foo, Bar, etc.) that can be persisted to DB must implement:
A public static final TABLE_NAME string, the name of the SQL DB table used for this object type.
A public static final TABLE_CREATE_STRING, a complete SQL instruction to create the table for this object.
A constructor method to populate its member variables from a ContentValues object.
A 'get' method to populate a ContentValues from its member variables.
So, say I have ArrayLists of objects Foo and Bar. When the DB is first created, within my DB helper class I call Foo.TABLE_CREATE_STRING, Bar.TABLE_CREATE_STRING, etc. to create the tables for those objects.
To populate my ArrayList, I use something like:
cursor = dbh.retrieve(Foo.TABLE_NAME);
if(!cursor.moveToFirst()){
return false
}
do{
DatabaseUtils.cursorRowToContentValues(cursor, vales);
FooArrayList.add( new Foo(values) );
} while( cursor.moveToNext() );
Create a dbHelper class which has an inner class and pretty much whatever the notepad tutorial says. The class must be having an insertion method somthing like this :-
public long insertRows(ContentValues values, String tableName) {
long val = myDatabase.insert(tableName, null, values);
return val;
}
This method will then add values into the table row.
After that you can call this method from your main activity and since you are using cursor i believe you will call the method in a for loop
for(i=0;list.length();i++) // or may be its list.size :P
{
// Call the method here
}
and keep adding value in the database by calling the method in for loop