Is it possible to transfer values from SimpleAdapter to array[]. I am getting values in SimpleAdapter from ArrayList<HashMap<String, String>> and want to pass these values from SimpleAdapter to array[].
static ArrayList<HashMap<String, String>> contactList = new ArrayList<HashMap<String, String>>();
SimpleAdapter adapter = new SimpleAdapter(this, contactList,R.layout.list_item,new String[] {android_H_NAME}, new int[] {R.id.name});
String[] hospFields = //want to get values here from adapter
Modify and use this:
ArrayList<String> listItems = new ArrayList<String>();
for (int i = 0; i < result.length(); i++) {
try {
listItems
.add(result.getJSONObject(i)
.getString(BsharpConstant.NAME_CONSTANT)
.toString());
} catch (Exception ex) {
ex.printStackTrace();
}
}
Inside oncreate method:
ListView list = (ListView) findViewById(R.id.idOfUrView);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(
ActivityName.this,
android.R.layout.simple_list_item_1, listItems);
list.setAdapter(adapter);
list.setOnItemClickListener(this);//if u need this until not required
Use this want to stores the value in item click:
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
String clickedItemName = (String) listOfProductsCategory
.getItemAtPosition(position);
int clickedItemId = (int) listOfProductsCategory
.getItemIdAtPosition(position);
// implement your login to store the value
//by using for loop listItems[i] ,i++
Toast.makeText(this.getActivity(),
"Custom text : " + clickedItemName,
Toast.LENGTH_SHORT).show();
//call your method if u want
}
There is no possibility to access the data directly, but you can use (in general):
Object[] o = new Object[adapter.getCount()];
for (int i = 0; i < adapter.getCount(); i++) {
o[i] = adapter.getItem(i);
}
to create a copy of your Adapter data. If you want just to extract specific values use:
String[] hospFields = new String[adapter.getCount()];
for (int i = 0; i < adapter.getCount(); i++) {
HashMap<String, String> rowData = adapter.getItem(i); //gets HashMap of a specific row
String name = rowData.get("name"); //gets the field name of that row
hospFields[i] = name; // copies field into your array
}
Related
I am currently working on an application for my company.
The App is working with a sqlite Database, stored on the external Storage.
Now I want to Display all Table Names of the Database in a ListView
The Part where I get the Table Names looks like this:
public ArrayList < String[] > getDBTables() {
SQLiteDatabase db = this.getReadableDatabase();
Cursor c = db.rawQuery(
"SELECT name FROM sqlite_master WHERE type='table'", null);
ArrayList < String[] > result = new ArrayList < String[] > ();
int i = 0;
result.add(c.getColumnNames());
for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) {
String[] temp = new String[c.getColumnCount()];
for (i = 0; i < temp.length; i++) {
temp[i] = c.getString(i);
System.out.println("TABLE - " + temp[i]);
}
result.add(temp);
}
return result;
}
And it is working just fine.
But now I have to display it in a ListView and there the problems began.
I tried it like that:
dbTablesView = (ListView) findViewById(R.id.listView);
ArrayList<String[]> tables;
tables=datasource.getDBTables();
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, tables );
dbTablesView.setAdapter(arrayAdapter);
But it tells me, that I cant use java.util.ArrayList to create the Adapter.
I would really appreciate your help.
I am developing an application, that sends a string array with putStringArrayListExtra. In the second activity I am receiving. The problem, if I send 2 item, 2 activity will open. The second element is on the listview(shows just one), when i click back, there is now the first item. I want the 2 item in the SAME listview. What am I doing wrong?
First activity
final int len = thumbnailsselection.length;
int cnt = 0;
String selectImages = "";
// String result = "";
String ar="";
for (int i =0; i<len; i++)
{
if (thumbnailsselection[i])
{
cnt++;
ar = nev[i];
selectImages = nev[i] + "|";
// List<String> myList = new ArrayList<String>(Arrays.asList(selectImages));
ArrayList<String> arr = new ArrayList<String>();
arr.add(selectImages);
Intent intent = new Intent(Gallery.this,Upload.class);
intent.putStringArrayListExtra("array_list", arr);
startActivity(intent);
// Log.i("adat","galleri:" + arr);
}
}
if (cnt == 0){
Toast.makeText(getApplicationContext(),
"Please select at least one image",
Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(),
"You've selected Total " + cnt + " image(s).",
Toast.LENGTH_LONG).show();
}
}
});
Second activity
ListView listView;
ArrayAdapter<String> adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_upload);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
listView = (ListView) findViewById(R.id.list);
Bundle b = getIntent().getExtras();
// ArrayList<String> arr = (ArrayList<String>)b.getStringArrayList("array_list");
ArrayList<String> arr = b.getStringArrayList("array_list");
Log.i("adat","UPLOAD:"+arr);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, android.R.id.text1, arr);
listView.setAdapter(adapter);
}
Do like below while you are creating new arraylist everytime when you loop thats why you are not getting correct values.
And also take you intent outside the loop too.
ArrayList<String> arr = new ArrayList<String>();
for (int i =0; i<len; i++){
if (thumbnailsselection[i]){
cnt++;
ar = nev[i];
selectImages = nev[i] + "|";
arr.add(selectImages);
}
}
Intent intent = new Intent(Gallery.this,Upload.class);
intent.putStringArrayListExtra("array_list", arr);
startActivity(intent);
I'm having this problem a little while, I need to load 25+ items from a database in json. When I load all of the including images etc. the app takes ages to load all of them. So I thought could I load the first five and when I scroll to the bottom the second five and so on. But it does not work. Here is my code:
Scroll listener:
rec.addOnScrollListener(new RecyclerView.OnScrollListener() {
#Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
visible = lin.getChildCount();
total = lin.getItemCount();
past = lin.findFirstVisibleItemPosition();
if ((visible + past) >= total){
new HttpAsyncTask().loadMore();
}
}
});
AsyncTask:
private class HttpAsyncTask extends AsyncTask<String, Void, List<PostsData>> {
int next;
#Override
protected List<PostsData> doInBackground(String... params) {
try {
//get json from url
JSONObject object = new JSONObject("{'posts':"+GET("http://www.website.com/json")+"}");
//get json array
JSONArray array = object.getJSONArray("posts");
for (int i = 0; i < 5; i++) {
next = i;
PostsData data = new PostsData();
//get object from array
JSONObject jsonObject = array.getJSONObject(i);
//title
data.setTitle(jsonObject.getString("name"));
//id
data.setId(jsonObject.getInt("id"));
JSONObject cat = jsonObject.getJSONObject("category");
//category name
data.setCatagorie(cat.getString("name"));
JSONObject img = jsonObject.getJSONObject("thumbnails");
//image url
String imgUrl = img.getString("preview_url");
//convert url into bitmap
data.setImage(getBitmap(imgUrl));
//get the post submitter name from array 'makers'
String makerFullname = "";
JSONArray userArray = jsonObject.getJSONArray("makers");
for (int j = 0; j < userArray.length(); j++) {
JSONObject user = userArray.getJSONObject(j);
//submitter full name
makerFullname = user.getString("full_name");
data.setUser(makerFullname);
}
data.setSubmitUser(jsonObject.getJSONObject("submitter").getString("full_name"));
//get the like count of the post
data.setLikeCount(jsonObject.getString("upvotes_count"));
list.add(data);
}
}catch (JSONException e){
e.printStackTrace();
}
return list;
}
// onPostExecute displays th
// results of the AsyncTask.
#Override
protected void onPostExecute(List<PostsData> result) {
adapter = new PostsAdapter(result, getContext());
rec.setAdapter(adapter);
}
public void loadMore(){
try {
//get json from url
JSONObject object = new JSONObject("{'posts':" + GET("http://www.materialup.com/api/v1/posts") + "}");
//get json array
JSONArray array = object.getJSONArray("posts");
if (array.length() <= next) {
for (int i = 0; i < next + 5; i++) {
next = i;
PostsData data = new PostsData();
//get object from array
JSONObject jsonObject = array.getJSONObject(i);
//title
data.setTitle(jsonObject.getString("name"));
//id
data.setId(jsonObject.getInt("id"));
JSONObject cat = jsonObject.getJSONObject("category");
//category name
data.setCatagorie(cat.getString("name"));
JSONObject img = jsonObject.getJSONObject("thumbnails");
//image url
String imgUrl = img.getString("preview_url");
//convert url into bitmap
data.setImage(getBitmap(imgUrl));
//get the post submitter name from array 'makers'
String makerFullname = "";
JSONArray userArray = jsonObject.getJSONArray("makers");
for (int j = 0; j < userArray.length(); j++) {
JSONObject user = userArray.getJSONObject(j);
//submitter full name
makerFullname = user.getString("full_name");
data.setUser(makerFullname);
}
data.setSubmitUser(jsonObject.getJSONObject("submitter").getString("full_name"));
//get the like count of the post
data.setLikeCount(jsonObject.getString("upvotes_count"));
list.add(data);
adapter.notifyDataSetChanged();
}
}
}catch(JSONException e){
e.printStackTrace();
}
}.....
It just won't load the next 5 items in the recyclerview. I searched on google but I did not really understand how load more works.
Thanks in advance, Sven.
This is the tutorial I followed: here
Make the next variable a static variable and start the loadMore method for statement with i=next+1,i <next+6 to avoid loading the same data again
I get data from Json and there's a Json array. I want to convert that Json array into String array, so I can send it into another activity and show it in ListView.
Here's My java code
if (jsonStr != null) {
try {
foodsFilter = new JSONArray(jsonStr);
// looping through All Contacts
for (int i = 0; i < foodsFilter.length(); i++) {
JSONObject c = foodsFilter.getJSONObject(i);
if(c.getString("category_name").equals("Food")) {
String category_name = c.getString(TAG_CATEGORY_NAME);
String filter_type = c.getString(TAG_FILTER_TYPE);
//String item_list = c.getString(TAG_ITEM_LIST);
JSONArray itemList = new JSONArray(c.getString("item_list"));
String item_list = itemList.toString();
// tmp hashmap for single contact
HashMap<String, String> filter = new HashMap<String, String>();
// adding each child node to HashMap key => value
filter.put(TAG_CATEGORY_NAME, category_name);
filter.put(TAG_FILTER_TYPE, filter_type);
filter.put(TAG_ITEM_LIST, item_list);
// adding contact to contact list
foodsFilterList.add(filter);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
I try that code to convert the JSONarray, but I realized that code is for convert the JSONArray into String.
Here's my JSON data
[{"category_name":"Food","filter_type":"Sort by","field_name":"","type":"VALUE","table_name":"","item_list":["Ascending","Descending"]}]
I want to convert the item_list Array into like this
item_list = {"Ascending", "Descending"}
So I can send it into another activity use Intent and show it in ListView
What you have
String item_list = itemList.toString();
You need to parse items_list which is a JSONArray.
JSONArray itemList = new JSONArray(c.getString("item_list"));
// loop through the array itemList and get the items
for(int i=0;i<itemList.length();i++)
{
String item = itemList.getString(i); // item at index i
}
Now you can add the strings to a list/array and then do what is required.
Please have a look on this tutorial.
http://www.androidhive.info/2012/01/android-json-parsing-tutorial/
Maybe this would help you.
ArrayList<String> stringArray = new ArrayList<String>();
JSONArray jsonArray = new JSONArray();
for(int i = 0, count = jsonArray.length(); i< count; i++)
{
try {
JSONObject jsonObject = jsonArray.getJSONObject(i);
stringArray.add(jsonObject.toString());
}
catch (JSONException e) {
e.printStackTrace();
}
}
I am getting invalid value in ListView. My code is below.
final ArrayList<HashMap<String, String>> placesListItems = new ArrayList<HashMap<String, String>>();
runOnUiThread(new Runnable() {
public void run() {
try {
HashMap<String, String> map = new HashMap<String, String>();
for (int i = 0; i < dealList.size(); i++) {
map.put(DealItem.DEAL_ID, dealList.get(i).deal_id);
map.put(DealItem.DEAL_NAME, dealList.get(i).deal_name);
System.out.println("DEAL NAME = "+dealList.get(i).deal_name);
placesListItems.add(map);
}
new PlacesMapActivity(SinglePlaceActivity.this, lon, lat, name, add);
ListView lv = (ListView) findViewById(R.id.listView);
simpleAdapter = new SimpleAdapter(SinglePlaceActivity.this, placesListItems, R.layout.list_item_deal, new String[] {
DealItem.DEAL_ID, DealItem.DEAL_NAME }, new int[] { R.id.reference, R.id.name });
lv.setAdapter(simpleAdapter);
when i run this code i am getting answer like this
10-03 18:37:29.429: I/System.out(3957): DEAL NAME = Sinbad Cafe
10-03 18:37:52.369: I/System.out(3957): DEAL NAME = Coffee,Tea, Hot Milk
10-03 18:37:55.189: I/System.out(3957): DEAL NAME = Httpss
But I do not understand why I am getting an invalid value in ListView
Like below:
Httpss
Httpss
Httpss
The same map is added to the list several times.
Try moving the new HashMap<...>-line into the for-loop:
for (int i = 0; i < dealList.size(); i++) {
--> HashMap<String, String> map = new HashMap<String, String>();
map.put(DealItem.DEAL_ID, dealList.get(i).deal_id);
map.put(DealItem.DEAL_NAME, dealList.get(i).deal_name);
System.out.println("DEAL NAME = "+dealList.get(i).deal_name);
placesListItems.add(map);
}
+-------- HashMap<String, String> map = new HashMap<String, String>();
|
| for (int i = 0; i < dealList.size(); i++) {
+--------------->
map.put(DealItem.DEAL_ID, dealList.get(i).deal_id);
map.put(DealItem.DEAL_NAME, dealList.get(i).deal_name);
System.out.println("DEAL NAME = "+dealList.get(i).deal_name);
placesListItems.add(map);
}
Since you have your "HashMap" initialization outside your loop, you are actually overwriting the same hashmap and putting it back to the arraylist..
Try to move your HashMap initialization inside for-loop..
change code with following code it will solve your error.....
try {
for (int i = 0; i < dealList.size(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
map.put(DealItem.DEAL_ID, dealList.get(i).deal_id);
map.put(DealItem.DEAL_NAME, dealList.get(i).deal_name);
System.out.println("DEAL NAME = "+dealList.get(i).deal_name);
placesListItems.add(map);
}