public List<Contact> getContacts()
{
SQLiteDatabase db;
String cmd;
List<Contact> name = new ArrayList<Contact>();
db = myDb.getReadableDatabase();
Cursor cursor = db.rawQuery("SELECT * FROM contact;" , null);
while(cursor.moveToNext())
{
int contactID = Integer.parseInt(cursor.getString(0));
String familyName = cursor.getString(1);
String firstName = cursor.getString(2);
int houseNumber = Integer.parseInt(cursor.getString(3));
String street = cursor.getString(4);
String town = cursor.getString(5);
String country = cursor.getString(6);
String postcode = cursor.getString(7);
int telephoneNumber = Integer.parseInt(cursor.getString(8));
Contact contact = new Contact(contactID,familyName,firstName,houseNumber,street,town,country,postcode,telephoneNumber);
}
Intent intent = new Intent(Database.this,MainActivity.class);
intent.putStringArrayListExtra("contacts", name);
startActivity(intent);
return name;
}
The method putStringArrayListExtra(String, ArrayList<String>) in the type Intent is not applicable for the arguments (String, List<Contact>)
in order to use putStringArrayListExtra(); method, i need to convert List<contact> name to List name, How do i convert it?
thank you
because list of object is actually not a list of strings, the best way as i know is to loop over list and convert each item into a new list of strings :
List<String> stringsList = new ArrayList<>(list.size());
for (Object object : list) {
stringsList.add(Objects.toString(object, null));
}
First Declare a new Array Of Strings.
List<String> newList = new ArrayList<String>(list.size());
newList.addAll(list);
This adds all elements into the new String List. Where list is your previous container.
Also to pass objects between components use Parceble, Android uses Binder to facilitate such communication in a highly optimized way. The Binder communicates with Parcels, which is a message container. The Binder marshals the Parcel to be sent, sends and receives it, and then unmarshals it on the other side to reconstruct a copy of the original Parcel.Please read up on it here.
Seems like you are trying to pass your List<Contacts> to via Intent -
No need to use putStringArrayListExtra() methods as there is putParcelableArrayList() method using which you can pass ArrayList<Contact> directly.
Simply use,
putParcelableArrayList("KEY", your ArrayList<Contact>); // Make sure Contact implementes Parcelable
You can get the ArrayList<Contact> in Receiver Activity -
Bundle b = getIntent().getExtras();
ArrayList<Contact> data = b.getParcelableArrayList("KEY");
However, You can use Serializable instead of Parcelable but Parcelable is recommended as it is like Flash. Here is why?
Related
In my application I want store ArrayList into sharedPreferences and get this list in another page!
For store this List i used this library : https://github.com/MrNouri/GoodPrefs
I write below codes, but when get this data I don't know how can get data!
My codes for store list :
for (int i : intList) {
stringBuilder.append("ID : ").append(testPlans.get(i).getId())
.append("Type : ").append(testPlans.get(i).getItemType())
.append("Content").append(steps.get(i).getStepData().toString()).append("-");
App.stepsBodyList.add(new DataItem(testPlans.get(i).getId(),
testPlans.get(i).getItemType(),
steps.get(i).getStepData().toString()));
}
GoodPrefs.getInstance().saveObjectsList(TEST_STEPS_STORED_LIST, App.stepsBodyList);
My codes for get data :
private List<DataItem> storedStepsBodyList = new ArrayList<>();
Toast.makeText(context, ""+
GoodPrefs.getInstance().getObjectsList(TEST_STEPS_STORED_LIST,).size()
, Toast.LENGTH_SHORT).show();
This library for get list give me 2 constructor, one is tag name and second value is default! (TEST_STEPS_STORED_LIST,)
But I don't know can i set default value for second item of constructor!
I write this GoodPrefs.getInstance().getObjectsList(TEST_STEPS_STORED_LIST,storedStepsBodyList) but show me error for this storedStepsBodyList .
How can i fix it?
Simple way, you can use Gson library, add it to build.gradle, it will serialize your list to JSON and save it to SharePreference
implementation 'com.google.code.gson:gson:2.8.6'
public void saveItems(List<Item> items) {
if (items != null && !items.isEmpty()) {
String json = new Gson().toJson(items);
mSharedPreferences.edit().putString("items", json).apply();
}
}
public List<Item> getItems() {
String json = mSharedPreferences.getString("items", "");
if (TextUtils.isEmpty(json)) return Collections.emptyList();
Type type = new TypeToken<List<Item>>() {
}.getType();
List<Item> result = new Gson().fromJson(json, type);
return result;
}
I have a data set. It is of the form
{
"name1": 123
"name2": 234
"name3": 345
.
.
.
}
Now, I am using a #RestController to read this through PostMan. I have a class test.java.
I have a function,
public void testController(#RequestBody String request)
I'm running this through a local host with the help of #RequestMapping. I need to save the above data set one by one in an object. The object is as follows.
public class OperatorClass implements Comparable<OperatorClass>{
private String name;
private ArrayList<String> id = new ArrayList<>();
OperatorClass(String name, String id)
{
add_id(id);
add_name(name);
}
I am trying to save this data in the following way, which by the way I have figured out is wrong.
try {
JSONObject array = new JSONObject(request);
Iterator<String> stringIterator1 = array.keys();
stringIterator1.next();
ArrayList<String> arrayList = new ArrayList<>();
OperatorClass oco = new OperatorClass(array.keys().,array.get(array.keys().toString()).toString());
System.out.println(oco.get_Name());
System.out.println(oco.get_Id());
} catch (Exception e) {
e.printStackTrace();
}
I know it is wrong because array.keys() gives all the name1, name2, name3 data. What I want to know is how to get just name 1 for this. And how to get it's following ID, to insert into a particular object.I was trying to save the object into a set of operator class.
Ok. I have got an answer to this problem. We use
String temp = stringIterator1.next();
And instead of
OperatorClass oco = new OperatorClass(array.keys().,array.get(array.keys().toString()).toString());
We use,
OperatorClass oco = new OperatorClass(temp, array.get(temp).toString);
Just remember that using string iterator will probably not display the values in the order of the data set, due to hash mapping.
I want to save data into master - details table.First portion is for master table and last portion is for details table.I have got java.lang.String cannot be cast to [Ljava.lang.String .How to recover from this problem.How to assign map.get("step_id[]") into a string array String[] WfIds. I want to assign each value into distinct string array.
Controller Code
Map<String,Object> wfManager = new HashMap<String,Object>();
//************************Master data sent from view******************************//
wfManager.put("workflow_code",(request.getParameter("workflow_code")).toUpperCase());
wfManager.put("workflow_name",request.getParameter("workflow_name"));
wfManager.put("workflow_descr",request.getParameter("workflow_descr"));
wfManager.put("object_type_code",request.getParameter("object_type_code"));
//*********************Detail item data sent from view********************************//
wfManager.put("wf_block_id[]", request.getParameter("wf_block_id[]"));
wfManager.put("step_code[]" , request.getParameter("step_code[]"));
wfManager.put("step_name[]", request.getParameter("step_name[]"));
wfManager.put("doa_type_code[]", request.getParameter("doa_type_code[]"));
wfManager.put("doa_type_name[]", request.getParameter("doa_type_name[]"));
Service Code
public Map<String, String> insert(Map<String, Object> map) {
//************************Master data sent from view******************************//
Map<String, String> data = new HashMap<String, String>();
Workflow wf = new Workflow();
wf.setWorkflowCode((String)map.get("workflow_code"));
wf.setWorkflowName((String)map.get("workflow_name"));
wf.setWorkflowDescr((String)map.get("workflow_descr"));
wf.setObjectTypeCode((String)map.get("object_type_code"));
String[] WfIds = (String[]) map.get("step_id[]");
String[] wfBlockIds = (String[]) map.get("wf_block_id[]");
String[] wfsCodes = (String[]) map.get("step_code[]");
String[] stepNames = (String[]) map.get("step_name[]");
String[] doaTypeCodes = (String[]) map.get("doa_type_code[]");
String[] doaTypeNames = (String[]) map.get("doa_type_name[]");
List<WorkflowDetails> wfDetailsList = new ArrayList<WorkflowDetails>();
for(int i = 0; i< wfsCodes.length; i++){
WorkflowDetails wfDetails = new WorkflowDetails();
wfDetails.setWorkflowCode(wf.getWorkflowCode());
wfDetails.setWorkflowName(wf.getWorkflowName());
wfDetails.setWorkflowDescr(wf.getWorkflowDescr());
wfDetails.setWorkflowObjectTypeCode(wf.getObjectTypeCode());
wfDetails.setWorkflowObjectTypeName(wf.getObjectTypeName());
wfDetailsList.add(i,wfDetails);
}
wf.setSteps(wfDetailsList);
id = workflowManagerDAO.insertDoc(wf);
data.put("id", id);
return data;
}
Code for DAO:
#Transactional
#Override
public String insertDoc(Workflow wfManager) {
for(int i = 0; i < wfManager.getSteps().size(); i++){
WorkflowDetails wfDetails = new WorkflowDetails();
wfDetails = wfManager.getSteps().get(i);
sessionfactory.getCurrentSession().save(wfDetails);
sessionfactory.getCurrentSession().flush();
}
String id = (String) sessionfactory.getCurrentSession().save(wfManager);
sessionfactory.getCurrentSession().flush();
return id;
}
If you absolutely need to use request.getParameter(), you will have to convert your arrays to strings using a delimiter character, e.g. convert this
String[] array = { "John", "Peter", "Paul" };
to this
String plainTextArray = "John#Peter#Paul";
Then you will be able to pass you array values as String (the only type that getParameter() understands).
You can then restore them like this
String[] restoredArray = request.getParameter("plainTextArray").split("#");
Maybe you want to have a look at setAttribute() and getAttribute() which let you store any objects (including arrays). You can start here Difference between getAttribute() and getParameter()
I have two variables (nom and marc) that come from a database (sqlite). I need to show these variables with a HashMap. I tried the following but it does not work:
private void populateList(String nom, String marc) {
list = new ArrayList<HashMap<String, String>>();
HashMap<String, String> temp = new HashMap<String, String>();
temp.put(FIRST_COLUMN, nom);
temp.put(SECOND_COLUMN, marc);
temp.put(THIRD_COLUMN, "1");
list.add(temp);
}
What am I doing wrong?
In a click event of a button I use a cursor to fetch data from the database:
Cursor c = db.rawQuery("Select * from prod where id_prod = " + id, null);
if (c.moveToFirst()){
do {
String nom = c.getString(1);
String marc = c.getString(2);
populateList(nom, marc);
} while(c.moveToNext());
}
As you can see PopulateList is a method different from the button that I need to send the variables. Maybe that I am doing wrong. Any answer will help. Thanks
Every time that a the populateList() method is called, you create a new instance of the list that you want to render!
Try to remove
list = new ArrayList<HashMap<String, String>>();
from the populateList(...)
I'm trying to get data from json. I can get data at first state.
But how to get data "ascending" and "descending" and show it on another activity in listview ?
Here's My Json
[{"category_name":"Food","filter_type":"Sort by","field_name":"","type":"VALUE","table_name":"","item_list":["Ascending","Descending"]}
And here's my Java code
if (jsonStr != null) {
try {
foods = new JSONArray(jsonStr);
// looping through All Contacts
for (int i = 0; i < foods.length(); i++) {
JSONObject c = foods.getJSONObject(i);
if(c.getString("category_name").equals("Food")) {
String category_name = c.getString(TAG_CATEGORY_NAME);
String table_name = c.getString(TAG_TABLE_NAME);
String item_list = c.getString(TAG_ITEM_LIST);
// tmp hashmap for single contact
HashMap<String, String> contact = new HashMap<String, String>();
// adding each child node to HashMap key => value
contact.put(TAG_CATEGORY_NAME, category_name);
contact.put(TAG_TABLE_NAME, table_name);
contact.put(TAG_ITEM_LIST, item_list);
// adding contact to contact list
foodlistfilter.add(contact);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
I'm trying to follow this tutorial http://www.androidhive.info/2012/01/android-json-parsing-tutorial/, but i still don't fully understand.
Let me explain this.
[ means its an array.
{ is an object.
In your case it's an array whcih contains an -JSONObject with name category_name, filter_type and field_name. type and table_name and a new jsonarray with object item_list.
How can you parse this string?
Here is an example:
String str = "[{"category_name":"Food","filter_type":"Sort by","field_name":"","type":"VALUE","table_name":"","item_list":["Ascending","Descending"]}";
JSONArray jsonArray = new JSONArray(str);
//now it holds the JSONObject.
for (int i = 0; i<= jsonArray.length(); i++) {
//now we loop through and get the jsonObject
JSONObject jsonObj = new JSONObject(jsonArray.getJsonObject(i));
//now it contains your data.
Log.d("Category_nameValue=", jsonObj.getString("category_name"));
//now we want to get the array from the item_list.
JSONArray itemList = new JSONArray(jsonObj.getString("item_list"));
//now itemList.getString(1); === Ascending while itemList.getString(2) == Descending
//now itemList contains several new objects which can also be looped as the parent one.
}
Since you now know how to create an JSONArray, you can start sorting it.
This has been answered already at Android how to sort JSONArray of JSONObjects
If you want to send those data to another Activity you can use the JSONArray.toString() method and send it via Intents.
This is easy explained at Pass a String from one Activity to another Activity in Android
Hope this helps.
If you're new, I would recommend you think about using Gson to parse your Json response directly to a java entity class. So you will avoid to manually parse all your responses.
Your JSON response
[{"category_name":"Food","filter_type":"Sort by","field_name":"","type":"VALUE","table_name":"","item_list":["Ascending","Descending"]}
The entity representing the response
public class MyEntity {
String category_name;
String filter_type;
String field_name;
String type;
String table_name;
String [] item_list;
// getters / setters ...
}
Parsing the response
Gson gson = new Gson();
MyEntity myEntity = gson.fromJson(response, MyEntity.class);
Finally, to send the data, start the new Activity with extras
Intent intent = new Intent(this, AnotherActivity.class);
intent.putExtra("EXTRA_DATA", myEntity.getCategoryName());
startActivity(intent);
Now you recover the extra data on your AnotherActivity
Intent intent = getIntent();
String categoryName = intent.getStringExtra("EXTRA_DATA");
And you can fill the ListView using an ArrayAdapter: Example
To get a JSONArray from your JSONObject c
simply write:
JSONArray itemList = c.getJSONArray(name);
then you can iterate through that data like any other array
for (int i = 0; i < itemList.length(); i++) {
// do something
}