Can't display another column/TextView on a ListView - android

I am trying to display list of users from an online database
id username
1 aaaaa
2 bbbbb
3 ccccc
I'm getting the above result, now I want to add another column/TextView besides those username, perhaps firstname, or lastname,
id username lastname
1 aaaaa please
2 bbbbb help
3 ccccc me
I believe this part of the code populates the ListView
private void showEmployee(){
JSONObject jsonObject = null;
ArrayList<HashMap<String,String>> list = new ArrayList<HashMap<String, String>>();
try {
jsonObject = new JSONObject(JSON_STRING);
JSONArray result = jsonObject.getJSONArray(Config.TAG_JSON_ARRAY);
for(int i = 0; i<result.length(); i++){
JSONObject jo = result.getJSONObject(i);
String id = jo.getString(Config.TAG_ID);
String username = jo.getString(Config.TAG_UNAME);
//String firstname = jo.getString(Config.TAG_FNAME);
HashMap<String,String> employees = new HashMap<>();
employees.put(Config.TAG_ID,id);
employees.put(Config.TAG_UNAME,username);
// employees.put(Config.TAG_UNAME,username);
list.add(employees);
}
} catch (JSONException e) {
e.printStackTrace();
}
ListAdapter adapter = new SimpleAdapter(
act_viewAllusers.this, list, R.layout.list_item,
new String[]{Config.TAG_ID,Config.TAG_UNAME},
new int[]{R.id.id, R.id.username});
/*** ListAdapter adapter = new SimpleAdapter(
act_viewAllusers.this, list, R.layout.list_item,
new String[]{Config.TAG_ID,Config.TAG_UNAME,Config.TAG_FNAME},
new int[]{R.id.id, R.id.username,R.id.fname}); ***/
listView.setAdapter(adapter);
}
I have a separate Java class named Config.java which contains some URLs and JSON tags which currently I can't really understand.
Here's some part of it
//JSON Tags
public static final String TAG_JSON_ARRAY="result";
public static final String TAG_ID = "id";
public static final String TAG_UNAME = "username";
public static final String TAG_PWORD = "password";
public static final String TAG_FNAME = "firstname";
public static final String TAG_LNAME = "lastname";
public static final String TAG_BDAY = "birthday";
public static final String TAG_GENDER = "gender";
Here's the XML for my ListView
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http:// schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_marginRight="10dp"
android:id="#+id/id"
android:layout_width="40dp"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/username"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/fname"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/lname"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
Another XML file for the ListView
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_act_view_allusers"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.example.bayona.lesson1.act_viewAllusers">
<ListView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/listView" />
</LinearLayout>
Perhaps it's imposible to add another column or TextView; it's fine, but what bothers me is that I can't change the username displays.
For instance, I want to display lastname besides the id number

LinearLayout provides an android:weightSum attribute. You can set this to 4 to get even column distribution. Each TextView can be given a android:layout_weight and a android:width="0dp" in that case to fill the weight of the column.
Or you can use a GridLayout and put 4 cells in one row.
Or you can use a TableRow.
Point being, you have options. However, you shouldn't think of a ListView as a "spreadsheet". You can make each "row" as complex as you want.
Personally, maybe something like this in each row.
ID Username
Lastname, FirstName
Or don't even show the id and add # before the username...
Firstname Lastname
#Username
Just use the XML editor to create whatever layout you want.
As far as the Java code is concerned. You only have two values being set.
ListAdapter adapter = new SimpleAdapter(
act_viewAllusers.this,
list, // data
R.layout.list_item, // layout
new String[]{Config.TAG_ID,Config.TAG_UNAME}, // from[]
new int[]{R.id.id, R.id.username}); // to[]
So, you add more strings into the from array which are set into the XML id's in the to array from that layout.

Try Like This
ListAdapter adapter = new SimpleAdapter(
act_viewAllusers.this, list, R.layout.list_item,
new String[]{Config.TAG_ID,Config.TAG_UNAME,
Config.NextTAg,Config.NextTag2},
new int[]{R.id.id, R.id.username,R.id.id1,R.id.id2});
Check this if not done
try {
jsonObject = new JSONObject(JSON_STRING);
JSONArray result = jsonObject.getJSONArray(Config.TAG_JSON_ARRAY);
for(int i = 0; i<result.length(); i++){
JSONObject jo = result.getJSONObject(i);
String id = jo.getString(Config.TAG_ID);
String username = jo.getString(Config.TAG_UNAME);
//-----------------
String varName=jo.getString(Config.REQ_TAG);
//-------------
//String firstname = jo.getString(Config.TAG_FNAME);
HashMap<String,String> employees = new HashMap<>();
employees.put(Config.TAG_ID,id);
employees.put(Config.TAG_UNAME,username);
//--------------
employees.put(Config.REQ_TAG,varName);
//-----------
// employees.put(Config.TAG_UNAME,username);
list.add(employees);
}

Related

Use Custom INFOWINDOW with MySQL

I have a map where i display markers that are stored in a db (MySQL),each marker have different fields with it (for example: name, email, addres, etc), since "MarkerOptions" only let me use ".tittle",".snippet"some of the fields that i want to attach are left out, i know now that i have to use a custom infowindow to show all the fields that i want to. How can i do this?
My code:
Main:
ArrayList<HashMap<String, String>> location = null;
String url = "http://appserver.eco.mx/movil/getLanLong.php";
try {
JSONArray data = new JSONArray(getHttpGet(url));
location = new ArrayList<HashMap<String, String>>();
HashMap<String, String> map;
for(int i = 0; i < data.length(); i++){
JSONObject c = data.getJSONObject(i);
map = new HashMap<String, String>();
map.put("id", c.getString("id"));
map.put("campo_latitud", c.getString("campo_latitud"));
map.put("campo_longitud", c.getString("campo_longitud"));
map.put("campo_categoria", c.getString("campo_categoria"));
map.put("campo_estado", c.getString("campo_estado"));
location.add(map);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String campouno = "";
if(!TextUtils.isEmpty(campouno)){
double campo_latitud = Double.parseDouble(campouno);
}
//campo_latitud = Double.parseDouble(location.get(0).get("Latitude").toString());
String campodos = "";
if(!TextUtils.isEmpty(campodos)){
double campo_longitud = Double.parseDouble(campodos);
}
for (int i = 0; i < location.size(); i++) {
if(!TextUtils.isEmpty(location.get(i).get("campo_latitud").toString())&&!TextUtils.isEmpty(location.get(i).get("campo_longitud").toString())) {
campo_latitud = Double.parseDouble(location.get(i).get("campo_latitud").toString());
campo_longitud = Double.parseDouble(location.get(i).get("campo_longitud").toString());
}
String name = location.get(i).get("campo_categoria").toString();
//String des = location.get(i).get("campo_descripcion").toString();
if(location.get(i).get("campo_categoria").toString().equals("Obras publicas")){
//System.out.println(location.get(i).get("campo_descripcion").toString());
googleMap.addMarker(new MarkerOptions().position(new LatLng(campo_latitud, campo_longitud)).title(name).icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_op)));
}
}}
XML:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#android:color/white">
<TextView
android:id="#+id/info_window_nombre"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:paddingLeft="5dp"
android:text="Carlo Estrada Solano" />
<TextView
android:id="#+id/info_window_placas"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textStyle="bold"
android:textSize="20sp"
android:layout_below="#id/info_window_nombre"
android:paddingLeft="5dp"
android:text="Placas: SX5487" />
<TextView
android:id="#+id/info_window_estado"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#id/info_window_placas"
android:paddingLeft="5dp"
android:text="Estado: Activo" />
</LinearLayout>
InfoWindow class:
public class AdaptadorInforWindow implements GoogleMap.InfoWindowAdapter {
private static final String TAG = "CustomInfoWindowAdapter";
private LayoutInflater inflater;
public AdaptadorInforWindow(LayoutInflater inflater){
this.inflater = inflater;
}
#Override
public View getInfoWindow(Marker marker) {
//Carga layout personalizado.
View v = inflater.inflate(R.layout.infowindow_layout, null);
String[] info = marker.getTitle().split("&");
String url = marker.getSnippet();
((TextView)v.findViewById(R.id.info_window_nombre)).setText("Lina Cortés");
((TextView)v.findViewById(R.id.info_window_placas)).setText("Placas: SRX32");
((TextView)v.findViewById(R.id.info_window_estado)).setText("Estado: Activo");
return v;
}
#Override
public View getInfoContents(Marker marker) {
return null;
}
}
set googlemap:
myGoogleMap.setInfoWindowAdapter(new CustomInfoWindowAdapter(LayoutInflater.from(getActivity())));
Store markers in Hashmap by Using the marker key. Then use the Custom infowindow using hashmap object to retrieve the others information.
When you will click marker it will show the related information.
or you can watch this video from 8:00 on wards.
Click Here
So I've just made a CustomInfoWindow for my app. Here's how you can achieve this.
First Create a method in your database file just to access all the data related to your marker and the code is as follows:
Cursor getDetails(Marker marker){
db = getReadableDatabase();
String query = "select Name, Email, Address from YourTableName where Name = '"+marker.getTitle()+"';";
return db.rawQuery(query,null);
}
Then tune your AdaptadorInforWindow's code as follows:
YourDatabaseClass db = new YourDatabaseClass(context);
Cursor c = db.getDetails(); //Method you'll create in database class
((TextView)v.findViewById(R.id.info_window_name)).setText(c.getString(0));
((TextView)v.findViewById(R.id.info_window_email)).setText(c.getString(1));
((TextView)v.findViewById(R.id.info_window_address)).setText(c.getString(2));
c.close();
See, getString is used because I guess you've used Text/String datatype to store your Name, Email and Address Values. Remember if datatype changes, then you have to use the appropriate method as c.getInt(index) for int and so on.
Also, Indices 0,1,2 are same as in query: Name Email Address.
This way you'll have your data shown in your CustomInfoWindow.
Same is working in mine superbly and I'm pretty sure this will work.

How to populate Layout with multiple HorizontalListView

I have a horizontal Listview. It works fine. My ArrayList eList will show a ListView going across the screen. That's great. My problem is that eList has multiple rows meaning eList might be planes, cars, and boats, or an infinite number of objects. Currently this Horizontal ListView will show only all the kinds of planes OR cars OR boats in the Database. How do show multiple or an infinite number of hListViews going down the screen vertically based upon how many object types(planes,cars,boats,tacos,people).
IN ACTIVITY
HorizontalListView hListView = (HorizontalListView) findViewById(R.id.hlistview1);
hListView.setAdapter(new ItemAdapter());
ArrayList<HashMap<String, String>> eList = controller.getAllts();
ListAdapter adapter = new SimpleAdapter(Su.this,eList,R.layout.view_m_ts, images, ins);
hListView.setAdapter(adapter);
IN DATABASE
public ArrayList<HashMap<String, String>> getAllts() {
ArrayList<HashMap<String, String>> List3;
List3 = new ArrayList<HashMap<String, String>>();
String selectQuery3 = "SELECT DISTINCT * FROM INV where p2 IS NOT NULL ORDER BY p2 COLLATE NOCASE ASC";
SQLiteDatabase database = this.getWritableDatabase();
Cursor cursor3 = database.rawQuery(selectQuery3, null);
HashMap<String, String> map = new HashMap<String, String>();
if (cursor3.moveToFirst()) {
do {
map.put("iImageL", cursor3.getString(13));
map.put("p2", cursor3.getString(2));
map.put("se2", cursor3.getString(10));
map.put("te", cursor3.getString(17));
List3.add(map);
} while (cursor3.moveToNext());
}
close();
return List3;
}
IN XML
<LinearLayout
android:id="#+id/LinearViewa"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight=".1"
android:orientation="vertical" >
<com.devsmart.android.ui.HorizontalListView
android:id="#+id/hlistview1"
android:layout_width="fill_parent"
android:layout_height="10dp"
android:layout_weight=".1"
android:background="#000000" />
</LinearLayout>
I'm going to assume that all objects of different types are in one SQLite table, with the type stored in one of the columns as a string, and you don't have a different table for each type.
Change your getAllts() function to return a HashMap of ArrayLists of HashMaps instead of an ArrayList of HashMaps, so that you can create multiple HorizontalListViews, one for each ArrayList of HashMaps, each one for a particular type. As you iterate through the rows returned in the cursor, get the type and check if there is already an ArrayList for it in your big HashMap, if not then create one and if so then add to the existing one:
public HashMap<String, ArrayList<HashMap<String, String>>> getAllts() {
HashMap<String, ArrayList<HashMap<String, String>>> hashMap = new HashMap<String, ArrayList<HashMap<String, String>>>();
String selectQuery3 = "SELECT DISTINCT * FROM INV where p2 IS NOT NULL ORDER BY p2 COLLATE NOCASE ASC";
SQLiteDatabase database = this.getWritableDatabase();
Cursor cursor3 = database.rawQuery(selectQuery3, null);
int typeColumnIndex = 18; // <- You need to set the correct column here, possibly using cursor3.getColumnIndexOrThrow()
if (cursor3.moveToFirst()) {
do {
// create this HashMap inside the loop because we need a new one each time:
HashMap<String, String> map = new HashMap<String, String>();
ArrayList<HashMap<String, String>> List3;
// get the type of this entry as a string
String typename = cursor3.getString(typeColumnIndex);
// check if there already is an ArrayList for this type:
if(hashMap.containsKey(typename))
{
// get existing ArrayList for this type:
List3 = hashMap.get(typename);
}
else
{
// create new ArrayList for this type:
List3 = new ArrayList<HashMap<String, String>>();
hashMap.put(typename, List3);
}
map.put("iImageL", cursor3.getString(13));
map.put("p2", cursor3.getString(2));
map.put("se2", cursor3.getString(10));
map.put("te", cursor3.getString(17));
List3.add(map);
} while (cursor3.moveToNext());
}
close();
return hashMap;
}
Change your XML so that you have an empty LinearLayout in your activity XML:
<LinearLayout
android:id="#+id/LinearViewa"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight=".1"
android:orientation="vertical" >
</LinearLayout>
and create a separate XML for the horizontal list view that you can create multiple times and add to your LinearLayout dynamically, in horiz_listview.xml or something like that. You can set up your own custom layout with the type name as a TextView header etc:
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<!-- Add type name here if you like-->
<com.devsmart.android.ui.HorizontalListView
android:id="#+id/hlistview1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#000000" />
</LinearLayout>
Then in your activity, get the massive hash map containing all the ArrayLists and iterate through it creating a HorizontalListView for each one and add it to the LinearLayout:
LinearLayout layout = (LinearLayout)findViewById(R.id.LinearViewa);
HashMap<String, ArrayList<HashMap<String, String>>> eHash = controller.getAllts();
LayoutInflater inflater = getLayoutInflater();
for(Map.Entry<String, ArrayList<HashMap<String, String>>> entry : eHash.entrySet())
{
// get the type name and ArrayList of Hashmaps for this type:
String typename = entry.getKey();
ArrayList<HashMap<String, String>> eList = entry.getValue();
// inflate a horizonal list view and add it to the layout:
View view = inflater.inflate(R.layout.horiz_listview, null, false);
layout.addView(view);
// set up the horizontal list view like before:
HorizontalListView hListView = (HorizontalListView) view.findViewById(R.id.hlistview1);
ListAdapter adapter = new SimpleAdapter(Su.this,eList,R.layout.view_m_ts, images, ins);
hListView.setAdapter(adapter);
}
If you have more HorizontalListViews than you can fit on screen then you might need to wrap your main LinearLayout in a ScrollView, however be warned that you might run into trouble with that, see this question.

Android: ListView not displaying as intended?

In the following code I intend to produce both an ouput on the item line and the subitem line but the code is just bringing me up an empty listview. How can I rectify this?
The game is a multiplication times tables game with the intention that when the user enters answers (on prev activity) the answer they entered are shown in the item (i.e. 12 items) and the correct answer for each is shown in each sub-item.
.Java code:
public class Results extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.results);
ListView itemList = (ListView) findViewById(R.id.lvresults);
//gets array from prev act
int[] results = getIntent().getIntArrayExtra("results");
int numberPassed = getIntent().getIntExtra("numberPassed", 0);
ArrayList < HashMap <String, String> > list = new ArrayList < HashMap <String, String> > ();
// loop to give list view
for (int i = 1; i <= 12; ++i)
{
int userAnswer = results[i - 1];
int expectedAnswer = numberPassed * i;
String userString = numberPassed + "x" + i + "=" + userAnswer;
String expectedString = "" + expectedAnswer;
HashMap <String, String> map = new HashMap <String, String> ();
map.put("user", userString);
map.put("expected", expectedString);
list.add(map);
}
String[] keys = {"user", "expected"};
int[] ids = {R.id.user_answer, R.id.expected_answer};
SimpleAdapter adapter = new SimpleAdapter(this, list, android.R.layout.simple_list_item_2, keys, ids);
itemList.setAdapter(adapter);
}
}
XML code:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<ListView
android:id="#+id/lvresults"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
</ListView>
<TextView
android:id="#+id/user_answer"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="15dp" />
<TextView
android:id="#+id/expected_answer"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="15dp" />
</LinearLayout>
int[] ids={android.R.id.text1,android.R.id.text2}
and remove the two TextView from the layout

Android: Line break not working in text from plist(XML) file

I'm creating a view that displays data that is parsed from a plist (XML) file. My parsing routine stores the data as an Object in a hashmap that I later retrieve with a key. My textview does display the data, but it does not process the \n into line breaks. Instead, the \n displays along with the text. Here is the code I use to retrieve my data from the hashmap:
String contactData = dict.get("Data").toString();
I have tried variations without success:
Object obj = dict.get("Data");
String contactData = obj.toString();
and
contactData = (String)dict.get("Data");
My text is lengthy with \n imbedded to force line breaks. I set my text as follows:
TextView data = (TextView) getActivity().findViewById(R.id.data);
data.setText(contactData);
Here is my layout:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#color/light_grey"
android:orientation="vertical" >
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#color/midnight_blue"
android:gravity="center"
android:text="Contacts"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textColor="#color/white"
android:textStyle="bold" />
<TextView
android:id="#+id/country"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#color/white"
android:gravity="center"
android:textColor="#color/midnight_blue"
android:textSize="16dp" />
<TextView
android:id="#+id/name"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:background="#color/white"
android:gravity="center"
android:textColor="#color/midnight_blue"
android:textSize="16dp" />
<TextView
android:id="#+id/data"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#color/white"
android:gravity="center"
android:singleLine="false"
android:textColor="#color/black"
android:textSize="12dp"
android:text="Line one\nLine two\nLine3"/>
\n works fine if I hard code the text to my variable (contactData) or I use the default text in the layout XML file. It does not work when I convert my object data toString??
Please do not suggest converting to \r\n. \n is the line separator. I've gone down that line in a previous question and it wasn't the resolution. The following code returns \n:
System.getProperty("line.separator");
My problem is related to how I'm retrieving my text from the hashmap and converting it to String. Any thoughts or suggestions would be appreciated!!!
* Update
Here is my parse routine for the plist file:
public void parse(InputStream inputStream) throws XmlPullParserException, IOException {
final XmlPullParserFactory xppf = XmlPullParserFactory.newInstance();
final XmlPullParser parser = xppf.newPullParser();
parser.setInput(inputStream, null);
final Stack<List<Map<String, Object>>> arrayStack = new Stack<List<Map<String, Object>>>();
final Stack<Map<String, Object>> dictStack = new Stack<Map<String, Object>>();
final Stack<String> keyStack = new Stack<String>();
int eventType = parser.getEventType();
boolean done = false;
while (!done) {
final String name = parser.getName();
switch (eventType) {
case XmlPullParser.START_DOCUMENT:
break;
case XmlPullParser.START_TAG:
if ("array".equalsIgnoreCase(name)) {
final List<Map<String, Object>> array = new ArrayList<Map<String,Object>>();
arrayStack.push(array);
} else if ("dict".equalsIgnoreCase(name)) {
final Map<String, Object> dict = new HashMap<String, Object>();
dictStack.push(dict);
} else if ("key".equalsIgnoreCase(name)){
keyStack.push(parser.nextText()); // assign current key
} else if ("string".equalsIgnoreCase(name)) {
final Map<String, Object> dict = dictStack.peek();
final String string = parser.nextText();
final String key = keyStack.pop();
dict.put(key, string);
} else if ("integer".equalsIgnoreCase(name)) {
final Map<String, Object> dict = dictStack.peek();
final String integerStr = parser.nextText();
final Integer integer = new Integer(integerStr);
final String key = keyStack.pop();
dict.put(key, integer);
} else if ("false".equalsIgnoreCase(name)) {
final Map<String, Object> dict = dictStack.peek();
final Boolean booleanValue = new Boolean(false);
final String key = keyStack.pop();
dict.put(key, booleanValue);
} else if ("true".equalsIgnoreCase(name)) {
final Map<String, Object> dict = dictStack.peek();
final Boolean booleanValue = new Boolean(true);
final String key = keyStack.pop();
dict.put(key, booleanValue);
}
break;
case XmlPullParser.END_TAG:
if ("array".equalsIgnoreCase(name)) {
final List<Map<String, Object>> array = arrayStack.pop();
if (arrayStack.isEmpty()) {
// return array;
mPlistHashMap.put("array",array);
break;
}
// If not end of array, means it's an array within a dict
final String key = keyStack.pop();
dictStack.peek().put(key, array);
} else if ("dict".equalsIgnoreCase(name)) {
final Map<String, Object> dict = dictStack.pop();
if (!arrayStack.empty())
arrayStack.peek().add(dict);
else
mPlistHashMap = dict;
}
break;
case XmlPullParser.END_DOCUMENT:
done = true;
break;
}
eventType = parser.next();
}
}
My plist consists of an Array of Dictionary items with three strings. Here is a snippet of my plist XML file:
<array>
<dict>
<key>Country</key>
<string>Mexico</string>
<key>Name</key>
<string>Mexico City</string>
<key>Data</key>
<string>Line one\nLine two\nLine three</string>
</dict>
Wrap your text in and use actual newlines. Then the parser should give you the data exactly as written. Something like:
<array>
<dict>
<key>Country</key>
<string>Mexico</string>
<key>Name</key>
<string>Mexico City</string>
<key>Data</key>
<string>
<![CDATA[
Line one
Line two
Line three
]]>
</string>
</dict>
</array>
Thanks to Nikolay's suggestions, I discovered that my text was somehow embedding and extra backslash to my line break character. So my text had "\n" instead of "\n". I had tried using .replaceAll("\n","\n"), but for some reason that was not working. Here is the code that worked for me:
contactData = dict.get("Data").toString().replace("\\n", "\n");

Binding strings to TableView/TextView IDs

I have an Android activity that displays a list of log entries (using a cursor adapter and listview). When one of the entries is touched it kicks off an intent (passed with a bundle object containing the log details as strings) to another activity. The new activity is supposed to display the details in a custom TableView xml file I created, but I can not figure out how to bind the bundle strings to the id's defined in the TextView of the TableView.
I have included most my code below so you can see what I am trying to accomplish.
ViewEntry Class:
public class ViewEntry extends Activity{
public void onCreate(Bundle icicle)
{
super.onCreate(icicle);
setContentView(R.layout.view_list);
setTitle(R.string.view_entry_title);
TableView lv= (TableView)findViewById(R.id.viewlayout);
Bundle extras = getIntent().getExtras();
if (extras != null){
String date = extras.getString(plbDbAdapter.KEY_DATE);
String ident = extras.getString(plbDbAdapter.KEY_IDENT);
String type = extras.getString(plbDbAdapter.KEY_TYPE);
String from = extras.getString(plbDbAdapter.KEY_FROM);
String to = extras.getString(plbDbAdapter.KEY_TO);
String remark = extras.getString(plbDbAdapter.KEY_REMARK);
String[] from = new String[] { "date_h", "ident_h", "type_h", "from_h", "to_h", "remark_h"};
int[] to = new int[] { R.id.v_date, R.id.v_ident, R.id.v_type, R.id.v_from, R.id.v_to, R.id.v_remark };
ArrayAdapter details = new ArrayAdapter(this, R.layout.view_list, from, to);
setAdapter(details);
List<HashMap<String, String>> fillList = new ArrayList<HashMap<String, String>>();
HashMap<String, String> map = new HashMap<String, String>();
map.put("date_h", date);
map.put("ident_h", ident);
map.put("type_h", type);
map.put("from_h", from);
map.put("to_h", to);
map.put("remark_h", remark);
fillList.add(map);
SimpleAdapter viewadapt = new SimpleAdapter(this, fillList, R.layout.view_list, from, to);
lv.setAdapter(viewadapt);
}
}
Here is view_list.xml I am trying to bind to:
<?xml version="1.0" encoding="utf-8"?>
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="#+id/viewlayout"
android:stretchColumns="1">
<TableRow>
<TextView
android:gravity="left"
android:text="Date:"
android:padding="3dip" />
<TextView
android:id="#+id/v_date"
android:gravity="right"
android:padding="3dip" />
I know what I am trying to do isn't right but hopefully it helps illustrate my intention.
I never did find out if my approach above is possible, but I went a different direction to get the intended results. The solution I ended up using was to get the specific textview id and then set the the text with a string by using the setText() method in the code. This is probably the accepted way to approach this design issue, but it would be nice to be able to bind strings to xml instead of manipulating it with code.
I have pasted the code below for future coders reference to a solution:
public class ViewEntry extends Activity{
public void onCreate(Bundle icicle)
{
super.onCreate(icicle);
setContentView(R.layout.view_list);
setTitle(R.string.view_entry_title);
TextView tv_date = (TextView)findViewById(R.id.tv_date);
TextView tv_ident = (TextView)findViewById(R.id.tv_ident);
TextView tv_type = (TextView)findViewById(R.id.tv_type);
TextView tv_from = (TextView)findViewById(R.id.tv_from);
TextView tv_to = (TextView)findViewById(R.id.tv_to);
TextView tv_remark = (TextView)findViewById(R.id.tv_remark);
Bundle extras = getIntent().getExtras();
if (extras != null){
String date = extras.getString(plbDbAdapter.KEY_DATE);
String ident = extras.getString(plbDbAdapter.KEY_IDENT);
String type = extras.getString(plbDbAdapter.KEY_TYPE);
String from = extras.getString(plbDbAdapter.KEY_FROM);
String to = extras.getString(plbDbAdapter.KEY_TO);
String remark = extras.getString(plbDbAdapter.KEY_REMARK);
tv_date.setText(date);
tv_ident.setText(ident);
tv_type.setText(type);
tv_from.setText(from);
tv_to.setText(to);
tv_remark.setText(remark);
}
}

Categories

Resources