XML Parsing in Android Programming - android

I am new to Android Programming, I had also asked this question before but didn't got quite satisfactory answers.
I need to implement parsing in my particular application. Can any body demistify the Parsing regarding the simple parsing of an XML String with an appropriate example.
Hoping I could get something vital this time.
Thanks,
david

MainActivity.java
public class MainActivity extends Activity implements OnClickListener {
ListView list;
MyAdapter listadapter;
ArrayList<String> names=new ArrayList<String>();
ArrayList<String> addresses=new ArrayList<String>();
DocumentBuilderFactory dbf;
DocumentBuilder db;
Document doc;
String value;
Context cxt;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.main);
list=(ListView) findViewById(R.id.listid);
cxt=this;
try {
InputStream is=getResources().openRawResource(R.raw.events);
dbf=DocumentBuilderFactory.newInstance();
db=dbf.newDocumentBuilder();
doc=db.parse(is,null);
NodeList main_nl=doc.getElementsByTagName("event");
for(int i=0;i<main_nl.getLength();i++){
Node st_node=main_nl.item(i);
NodeList sub_nl=st_node.getChildNodes();
for(int j=0;j<sub_nl.getLength();j++){
Node sub_node=sub_nl.item(j);
String name=sub_node.getNodeName();
if(name.equals("ename")){
value=sub_node.getFirstChild().getNodeValue();
names.add(value);
}
else if(name.equals("address")){
value=sub_node.getFirstChild().getNodeValue();
addresses.add(value);
}
}
}
}
catch (Exception e) {
System.out.println("XML Parsing Excpetion = " + e);
}
listadapter=new MyAdapter(getApplicationContext(),names,addresses);
list.setAdapter(listadapter);
} }
MyAdapter
public class MyAdapter extends BaseAdapter{
LayoutInflater inflater;
ArrayList<String> namess;
ArrayList<String> addressess;
public MyAdapter(Context c) {
// TODO Auto-generated constructor stub
con = c;
}
public MyAdapter(Context c, ArrayList<String> names,
ArrayList<String> addresses) {
// TODO Auto-generated constructor stub
namess= null;
this.addressess=null;
con=c;
this.addressess=addresses;
this.namess=names;
inflater = (LayoutInflater)con.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public int getCount()
{
return namess.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public static class ViewHolder
{
public TextView nam;
public TextView add;
}
public View getView(int position, View convertView, ViewGroup parent)
{
View v=convertView;
ViewHolder holder;
try
{
if (convertView == null)
{
v=inflater.inflate(R.layout.listitem,parent,false);
holder=new ViewHolder();
holder.nam=(TextView)v.findViewById(R.id.name);
holder.add = (TextView)v.findViewById(R.id.address);
v.setTag(holder);
}
else{
holder=(ViewHolder)v.getTag();
}
holder.nam.setText(namess.get(position).toString());
holder.add.setText(addressess.get(position).toString());
}
catch(OutOfMemoryError e)
{
System.gc();
}
return v;
}
private Context con;
}
main.xml
<?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/listid"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
</ListView>
listitem.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/name"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
<TextView android:id="#+id/address"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
create floder raw. In that create an events.xml
<?xml version="1.0" encoding="UTF-8"?>
<events>
<event>
<ename>Network Connect Grow</ename>
<address>Panera Bread, Orlando, Fl</address>
</event>
<event>
<ename>SRB Networking Meeting</ename>
<address>Mimi’s Café, Orlando, Fl</address>
</event>
</events>

Related

the following android CustomAdapter does not work?

Here is my completed android studio project coding:
i know i was made multiple errors but where??
i am very beginner
It is my MainActivity class:
public class MainActivity extends AppCompatActivity{
public Elements titles;
public ArrayList<String> news_list = new ArrayList<>();
private CustomAdapter customAdapter;
private ListView lv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lv = (ListView) findViewById(R.id.listView1);
customAdapter = new CustomAdapter(this,news_list);
new NewThread().execute();
}
public class NewThread extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... arg) {
Document doc;
try {
doc = Jsoup.connect("http://www.varzesh3.com").get();
titles = doc.getElementsByClass("small-news-link");
news_list.clear();
for (Element news : titles) {
news_list.add(news.text());
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
lv.setAdapter(customAdapter);
}
}
}
And it is my CustomAdapter class
public class CustomAdapter extends ArrayAdapter<String> {
List<String> listString;
Activity context;
Typeface typeFace;
public CustomAdapter(MainActivity mainActivity, List<String> listString) {
super(mainActivity, R.layout.list_item,listString);
this.context = mainActivity;
this.listString = listString;
}
static class ViewHolder {
public TextView textView;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View vi = convertView;
if (vi == null) {
LayoutInflater inflater = context.getLayoutInflater();
vi = inflater.inflate(R.layout.list_item, null);
ViewHolder viewHolder = new ViewHolder();
viewHolder.textView = (TextView) vi.findViewById(R.id.news);
vi.setTag(viewHolder);
}
ViewHolder holder = (ViewHolder) vi.getTag();
typeFace = Typeface.createFromAsset(context.getAssets(), "fonts/IRANSans.ttf");
holder.textView.setTypeface(typeFace);
return vi;
}
}`
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<ListView
android:id="#+id/listView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true" >
</ListView>
list_item.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView android:id="#+id/news"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="10dip"
android:textSize="15dip"
android:textStyle="bold"
android:textColor="#000000"/>
In your getView() method of CustomAdapter, you never actually display any text. You inflate the view, create the ViewHolder, set the Typeface... but don't display any text. Add code that looks something like this:
String s = listString.get(position);
holder.textView.setText(s);
#Ben P. Gave You the exact answer, You dont get the Strings from anywhere, You have just inflated the list_row without getting any acsual Strings.
I would advise You openinng a new class to handle the Strings/Objetcs with an outside class lets say StringClass with getters and setters and put the ArrayList<StringClass> list; in the above and connect it to the adapter and after that just use it in the asynctask, easier and with OOP...
Cheers and good luck!

SherlockFragment and BaseAdapter: never call getView and getItem

I already saw a bunch of questions but i didn't found an solution! What im doing wrong? Why getView is never called?!
Here`s my adapter:
public class ConteudoAdapter<T extends IProgramacao> extends BaseAdapter {
private Context context;
private List<T> list;
private int resourceId;
public ConteudoAdapter(Context context, int resourceId, List<T> list){
this.context = context;
this.list = list;
this.resourceId = resourceId;
}
#Override
public int getCount() {
Log.v("test", "Returning count " + (this.list.size() != 0 ? this.list.size() : 0));
return list.size();
}
#Override
public Object getItem(int position) {
return list.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View view, ViewGroup parent) {
View row = view;
ViewHolder holder = null;
T entidade = list.get(position);
if(row == null)
{
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
row = inflater.inflate(resourceId, parent, false);
holder = new ViewHolder();
holder.tvTitle = (TextView) row.findViewById(R.id.tvTitle);
holder.tvTitle.setText(entidade.getTitulo());
holder.tvConteudo = (TextView) row.findViewById(R.id.tvConteudo);
holder.tvConteudo.setText(entidade.getChamada());
row.setTag(holder);
}
// holder.ivImg = (ImageView) layout.findViewById(R.id.nivImg);
// holder.ivImg.setImageResource(entidade.);
// IMAGE VIEW
// holder.ivImg.setVisibility(View.VISIBLE);
// il.get(list.get(position).getUrlImage(), il.getImageListener(holder.ivImg, R.drawable.load, R.drawable.error));
//tvTitle.setText(entidade.getTitulo());
return view;
}
public static class ViewHolder{
//public NetworkImageView nivImg;
//public ImageView ivImg;
public TextView tvTitle;
public TextView tvConteudo;
}
}
Here`s how i call my adapter (inside an asynctask because im getting values from web (JSON):
public class CategoriaEventoFragment extends SherlockFragment {
private View rootView;
private EventoBO evento;
private ListView lv;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
rootView = (View) inflater.inflate(R.layout.categoria, container, false);
CarregaDadosCategoriaEventoCaller carregaDadosCategoriaEventoCaller = new CarregaDadosCategoriaEventoCaller();
carregaDadosCategoriaEventoCaller.execute((Void[]) null);
return super.onCreateView(inflater, container, savedInstanceState);
}
public class CarregaDadosCategoriaEventoCaller extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
evento = new EventoBO("http://urlhere");
evento.popularListaImagemChamada("http://urlhere");
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
lv = (ListView) rootView.findViewById(R.id.listViewCategoria);
lv.setAdapter(new ConteudoAdapter<Evento>(rootView.getContext(), R.layout.item, evento.getLista()));
}
}
}
}
XML FILES:
item.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#drawable/home_bg_branco"
android:orientation="horizontal" >
<TextView
android:id="#+id/tvTitle"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
<TextView
android:id="#+id/tvConteudo"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
</LinearLayout>
categoria.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical" >
<ListView
android:id="#+id/listViewCategoria"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#drawable/home_bg_branco" >
</ListView>
</LinearLayout>
My LogCat Returns this for my verbose test:
09-02 17:13:27.322: V/test(24961): Returning count 5
09-02 17:13:27.322: V/test(24961): Returning count 5
Thanks in advance!!!
In onCreateView() you should be returning the rootView instead of the super.

Minimize the listview row into a single line

I'm using listview to show the messages from the database..when i add a message it
takes all the string and showing on the listview..here is my xml file and java..
I need to get the message in a singline per rows with '...'. I researched for this question and i found,type
android:singleLine="true" in textview,but i don't know what they mean 'in textview'.becauz i'm using listview.please help.
<?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"
android:background="#drawable/wave" >
<ListView
android:id="#+id/list"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentLeft="true"
android:layout_below="#+id/SearchMessageExit"
android:focusableInTouchMode="true"
>
</ListView>
</LinearLayout>
message.java
public void detailsOfMessage(){
try{
Database_message info = new Database_message(this);
String data = info.getData();
info.close();
if(data.equals(""))
{
Toast.makeText(getApplicationContext(), "Empty Message", Toast.LENGTH_LONG).show();
}
StringTokenizer token = new StringTokenizer(data,"\t");
int rows = token.countTokens();
classes = new String[rows];
int i=0;
while (token.hasMoreTokens())
{
classes[i]=token.nextToken();
i++;
}
listView = (ListView) findViewById(R.id.list);
listView.setOnItemClickListener(this);
listView.setOnLongClickListener(this);
inAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,0);
listView.setAdapter(inAdapter);
for (int r = 0; r < classes.length; r++) {
inAdapter.add(classes[r]);
}
}catch(Exception e){
Toast.makeText(getApplicationContext(), "Empty Message", Toast.LENGTH_LONG).show();
}
}
you are using default layout android.R.layout.simple_list_item_1 for listview item. instead create one layout with textview with single line enable. and pass it to listview. and use custom array adapter for listview.
Do like this:
create list itemview XML
listview_item_row.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="10dp">
<TextView android:id="#+id/txtTitle"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center_vertical"
android:layout_alignParentTop="true"
android:layout_alignParentBottom="true"
android:textStyle="bold"
android:textSize="22dp"
android:textColor="#000000"
android:layout_marginTop="5dp"
android:layout_marginBottom="5dp" />
</LinearLayout>
One class like
Weather.java
public class Weather {
public String title;
public Weather(){
super();
}
public Weather(String title) {
super();
this.title = title;
}
}
and then create array adapter class
public class WeatherAdapter extends ArrayAdapter<Weather>{
Context context;
int layoutResourceId;
Weather data[] = null;
public WeatherAdapter(Context context, int layoutResourceId, Weather[] data) {
super(context, layoutResourceId, data);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.data = data;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
WeatherHolder holder = null;
if(row == null)
{
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new WeatherHolder();
holder.txtTitle = (TextView)row.findViewById(R.id.txtTitle);
row.setTag(holder);
}
else
{
holder = (WeatherHolder)row.getTag();
}
Weather weather = data[position];
holder.txtTitle.setText(weather.title);
return row;
}
static class WeatherHolder
{
TextView txtTitle;
}
}
And use like this in your activity:
Weather weather_data[] = new Weather[]
{
new Weather("Cloudy"),
new Weather("Showers"),
new Weather("Snow"),
new Weather("Storm"),
new Weather("Sunny")
};
WeatherAdapter adapter = new WeatherAdapter(this,
R.layout.listview_item_row, weather_data);
listView1.setAdapter(adapter);
Hope it Helps!!!
You need to implement a custom adapter for your ListView.
Along with that you should also implement, a custom_row.xml file for each row of your List View.
For Example:
1. Custom Adapter:
public class CustomAdapterListView extends BaseAdapter
{
private Activity activity;
private static LayoutInflater inflater=null;
private YOUR_DATA_TYPE data;
public CategoryDetailsCustomGridviewAdapter(Activity a, ArrayList<YOUR_DATA_TYPE> d)
{
activity = a;
data=d;
inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount()
{
// TODO Auto-generated method stub
return data.size();
}
#Override
public Object getItem(int position)
{
// TODO Auto-generated method stub
return position;
}
#Override
public long getItemId(int position)
{
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
// TODO Auto-generated method stub
View vi=convertView;
if(convertView==null)
{
vi = inflater.inflate(R.layout.YOUR_LISTVIEW_ROW_XML_FILE, null);
}
//Fetching the Data from ArrayList for each row.
TextView custom_row_tv = vi.findViewById(R.id.YOUR_TEXT_VIEW_ID)
YOUR_DATA_TYPE dataToBePopulated = new YOUR_DATA_TYPE;
custom_row_tv.setText(YOUR_DATA_TYPE.ToString());
dataToBePopulated = data.get(position);
return vi;
}
}
2. YOUR_LISTVIEW_ROW_XML_FILE.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="#+id/YOUR_TEXT_VIEW_ID"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:singleLine="true" >
</TextView>
</RelativeLayout>
3. Setting up Your Custom Adapter:
Public Class YourClass extends Activity
{
onCreate(....)
{
setContentView(R.Layout.YOUR_LAYOUT_FILE);
ArrayList<YOUR_DATA_TYPE> data = new ArrayList<YOUR_DATA_TYPE>();
data.add(...) //Fetch your Data from Data source into this ArrayList.
ListView yourListView = (ListView)findViewById(R,id.YOUR_LISTVIEW_ID);
CustomAdapterListView adapter = new CustomAdapterListView (YourClass.this, data);
yourListView.setAdapter(adapter);
adapter.notifyDataSetChanged();
//YOUR OTHER FUNCTIONALITY......
}
//YOUR OTHER METHODS.....
....
....
}
This way you can simply implement a custom ListView with the Attribute of Single line attached to your TextView embedded within your ListView.
I hope this solves your problem.

Blank activity using ListView and Adapter

I am learning to use ListViews with Adapters.
The codes I am posting here are from one of the tutorials from
Here
This is my class(Equivalent to MainActvity class in tutorial) in which I am intialising a ListView and providing data to adapter.
setContentView(R.layout.searchresultrowlayout);
try {
jsonarray1=searchscreen.searchresults();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ArrayList<HashMap<String, String>> propertylist=new ArrayList<HashMap<String, String>> ();
for(int i=0;i<jsonarray1.length();i++){
HashMap<String,String> propertymap=new HashMap<String,String> ();
try {
jsonobject=jsonarray1.getJSONObject(i);
Log.d("json", jsonobject.getString("id"));
propertymap.put("propertytype",jsonobject.getString("propertytype") );
propertylist.add(propertymap);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
list=(ListView)findViewById(R.id.list);
adapter=new PropertySearchArrayAdapter(this,propertylist);
// Log.d("adapter", propertylist.get(1).get("price").toString());
list.setAdapter(adapter);
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
}
});
and this is my adapter class
public class PropertySearchArrayAdapter extends BaseAdapter{
private Activity activity;
private ArrayList<HashMap<String,String>> data;
private static LayoutInflater inflater=null;
//public ImageLoader imageloader;
public PropertySearchArrayAdapter(Activity context, ArrayList<HashMap<String,String>> d){
activity=context;
data=d;
inflater=(LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public View getView(int position,View convertview, ViewGroup parent){
View rowview=convertview;
if(convertview==null){
rowview=inflater.inflate(R.layout.searchlist_row, null);}
//ViewHolder viewholder=new ViewHolder();
TextView propertyType=(TextView) rowview.findViewById(R.id.propertytype); //propertytype
HashMap<String,String> property= new HashMap<String,String> ();
property= data.get(position);
propertyType.setText(property.get("propertytype"));
Log.d("adaptertext", property.get("propertytype"));
return rowview;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return 0;
}
#Override
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return 0;
}
}
These are XMLs
searchresultrowlayout
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<ListView
android:id="#+id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:divider="#b5b5b5"
android:dividerHeight="1dp"
android:listSelector="#drawable/list_selector" />
</LinearLayout>
searchlist_row
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#FFFFFF"
android:orientation="horizontal"
android:padding="5dip" >
<!-- Property type-->
<TextView
android:id="#+id/propertytype"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#040404"
android:typeface="sans"
android:textSize="15dip"
android:textStyle="bold"/>
</RelativeLayout>
The other XMLs list_selector,gradient_bg.xml,gradient_bg_hover.xml I have taken from the tutorial itself.
My problem is when I am pushing my activity which is supposed to show list view(by intent from previous activity on button click), the screen that appears is completely black and blank.
Please help me out.
If you want the ListView to show the data your adapter must return the number of items it contains(or wants to show) with the getCount() method and not 0(in which case the adapter will be considered empty and nothing will be shown):
#Override
public int getCount() {
return data.size();
}

I have created a dynamic ListView - how do I connect it to my XML layout file?

Hi all and thank you for taking a look at this. I have created a dynamic ListView using android's developer guide. Currently, the ListView activity seems to display itself on screen without the need for an XML file or setContentView...which is a problem.
I would like to use an XML layout, so I can go and add other Views to the screen, rather than dedicating an entire Activity to just displaying the list. I created an XML layout, that contains a blank ListView, amongst other things and I want my list to go into that allotted space...so my question: How do I get my ListActivity to use my layout XML file?
public class MainList extends ListActivity {
static SharedPreferences statusSettings;
String jsonString;
static JSONObject json;
static JSONArray arrayTest;
static int bob = 3;
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
// TODO Auto-generated method stub
super.onListItemClick(l, v, position, id);
try {
JSONObject e = arrayTest.getJSONObject(position);
Intent intent = new Intent();
intent.putExtra("clientName", e.getString("proj_name"));
intent.putExtra("clientAddress", e.getString("c_address"));
intent.putExtra("clientComments", e.getString("comments"));
intent.putExtra("clientOrder", e.getString("order"));
intent.setClass(MainList.this, ClientDetails.class);
MainList.this.startActivity(intent);
} catch (JSONException e) {
// TODO Auto-generated catch block
Log.e("JSON", "Problem creating object from array!");
e.printStackTrace();
}
}
private static class EfficientAdapter extends BaseAdapter {
private LayoutInflater mInflater;
public EfficientAdapter(Context context) {
// Cache the LayoutInflate to avoid asking for a new one each time.
mInflater = LayoutInflater.from(context);
}
public int getCount() {
return arrayTest.length();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.mainlist, null);
holder = new ViewHolder();
holder.textName = (TextView) convertView.findViewById(R.id.tvMainName);
holder.textAddress = (TextView) convertView.findViewById(R.id.tvMainAddress);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
JSONObject e;
try {
e = arrayTest.getJSONObject(position);
holder.textName.setText(e.getString("proj_name"));
holder.textAddress.setText(e.getString("c_address"));
switch (statusSettings.getInt(e.getString("order"), 0)){
case 1:
convertView.setBackgroundColor(0x00000000);
break;
case 2:
if(bob == 3){
convertView.setBackgroundColor(0xFFFF6600);
bob = 5;
}
break;
case 3:
convertView.setBackgroundColor(0xFF00CC00);
break;
case 4:
convertView.setBackgroundColor(0xFFCC0000);
break;
}
} catch (JSONException e1) {
// TODO Auto-generated catch block
Log.e("JSON", "Couldn't put one of JSON arrays into object");
e1.printStackTrace();
}
return convertView;
}
static class ViewHolder {
TextView textName;
TextView textAddress;
}
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
jsonString = getIntent().getExtras().getString("jsonString");
try {
json = new JSONObject(jsonString);
arrayTest = json.getJSONArray("client_list");
} catch (JSONException e) {
// TODO Auto-generated catch block
Log.e("JSON", "Couldn't create the JSON Array");
e.printStackTrace();
}
setListAdapter(new EfficientAdapter(this));
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
bob = 3;
statusSettings = getSharedPreferences("status", 0);
setListAdapter(new EfficientAdapter(this));
}
}
XML File:
<?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/list"
android:layout_width="match_parent"
android:layout_height="wrap_content" android:layout_weight="1">
</ListView>
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button" />
</LinearLayout>
The thing is, they create it without using any XML layout - I don't fully understand how, but I assume it has something to do with the LayoutInflater. I tried:
convertView = mInflater.inflate(R.id.list, null);
instead of
convertView = mInflater.inflate(R.layout.mainlist, null);
and I placed setContentView(R.layout.test);
in my onCreate...but didn't work. Any help you offer would be much appreciated, thank you!
This is pretty Simple. I have quick generated some code for your reference.
public class ListandtextActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final String [] str = {"ONE","TWO","THREE"};
final ListView lv = (ListView) findViewById(R.id.listView1);
final TextView tv = (TextView)findViewById(R.id.tv1);
lv.setAdapter(new ArrayAdapter<Object>(getApplicationContext(), android.R.layout.simple_list_item_1, str));
lv.setOnItemClickListener(new OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
tv.setText("You Clicked Something");
}
});
}
}
And in your XML
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/tv1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/hello" />
<ListView
android:id="#+id/listView1"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</ListView>
</LinearLayout>
Feel free to ask if you have any doubts.

Categories

Resources