Actually i was trying JSON parsing example and the data which is parsed but not displaying in the listview.In the logcat the data is coming ,but it is not displaying in list.
I was running using an emulator. I am not able to find the mistake.Can anyone help?
Code below shows the custom list adapter.
public class ListAdapter extends BaseAdapter{
ArrayList<HashMap<String, String>> list = new ArrayList<HashMap<String,String>>();
Context context;
public ListAdapter(ArrayList<HashMap<String, String>> list,
Context context) {
Log.i("ListAdapter", "ListAdapter");
this.list = list;
this.context = context;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return list.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return null;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
Log.i("ListAdapter", "getView");
if(convertView == null){
convertView = LayoutInflater.from(context).inflate(R.layout.list, null);
}
HashMap<String, String> hashmap = new HashMap<String, String>();
TextView trank = null,tcountry = null,tpopulation = null;
ImageView image;
trank = (TextView) convertView.findViewById(R.id.rank);
tcountry = (TextView) convertView.findViewById(R.id.country);
tpopulation = (TextView) convertView.findViewById(R.id.population);
image = (ImageView) convertView.findViewById(R.id.flag);
hashmap = list.get(position);
Log.i("list", ""+list.get(position) + "hashmp " + hashmap + hashmap.get("rank"));
String rank = hashmap.get("rank").toString();
String country = hashmap.get("country").toString();
String population = hashmap.get("population").toString();
String image_url = hashmap.get("flag");
Log.i("ListAdapter", ""+rank + " "+ country + " " +population );
trank.setText(rank);
tcountry.setText(country);
tpopulation.setText(population);
return convertView;
}
}
Main activity class
public class MainActivity extends Activity {
TextView webpage,trank,tcountry,tpopulation;
ListView lv;
ArrayList<HashMap<String, String>> list = new ArrayList<HashMap<String,String>>();
String RANK = "rank";
String COUNTRY = "country";
String POPULATION = "population";
String FLAG = "flag";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lv = (ListView) findViewById(R.id.listview);
trank = (TextView) findViewById(R.id.rank);
tcountry = (TextView) findViewById(R.id.country);
tpopulation = (TextView) findViewById(R.id.population);
webpage = (TextView) findViewById(R.id.webpage);
webpage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String data = getDataFromWebPage();
list = parseDataFromWeb(data);
ListAdapter adapter = new ListAdapter(list, getApplicationContext());
lv.setAdapter(adapter);
}
});
}
custom list layout 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="horizontal" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
>
<TextView
android:id="#+id/rank"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="rank"
/>
<TextView
android:id="#+id/country"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="country"
/>
<TextView
android:id="#+id/population"
android:text="population"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
</LinearLayout>
<ImageView
android:id="#+id/flag"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
</LinearLayout>
I got solution, actually problem was with this layout file.When i removed the inner LinearLayout problem is solved.
Previously it was displayed like this after pressing the textview
But still i dont know why this layout file with inner LinearLayout doesnt work.
Make change in your code here :
#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;
}
You should return position in getItem() method:
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
you have to change:
ListAdapter adapter = new ListAdapter(getApplicationContext(),list);
try this
ListAdapter adapter = new ListAdapter( MainActivity.this,list);
lv.setAdapter(adapter);
Issue was with the custom list layout.Because of the inner linear layout data was not displaying.After removing the inner layout ,it worked
Related
I have been following this example on creating a multirow list-view on android. However, I get the error
Attempt to invoke virtual method 'void android.widget.ListView.setAdapter(android.widget.ListAdapter)' on a null object reference
in the line marked below. As far as I see I have followed the example as it is described, but maybe I have missed something obvious.
The relevant pieces of the code are as follows:
Excerpt of the code to show the view (when the user presses a button):
public void stat(View view) {
// First, sort the pile of entries
Map<Integer, Integer> testMap = new HashMap<Integer, Integer>();
for (int i = 0; i < quizIndex.size(); i++) {
testMap.put(i, quizIndex.get(i).getPriority());
}
MyComparator comparator = new MyComparator(testMap);
Map<Integer, Integer> sortedMap = new TreeMap<Integer, Integer>(comparator);
sortedMap.putAll(testMap);
// Then, fill out the lists of lists
ArrayList<HashMap<String,String>> adapterList = new ArrayList<HashMap<String,String>>();
int index;
for (Map.Entry<Integer, Integer> mapentry : sortedMap.entrySet())
{
System.out.println(mapentry.getKey() + "/" + mapentry.getValue());
index = mapentry.getKey();
Entry entry = quizIndex.get(index);
System.out.println(String.format("%30s %d %d %s %d %d %d",
entry.name(), entry.number_ok, entry.number_nok, entry.history, entry.randomIndex, entry.histIndex, entry.getPriority()));
HashMap<String,String> temp=new HashMap<String, String>();
temp.put(COLUMN_NAME, entry.name());
temp.put(COLUMN_OK, Integer.toString(entry.number_ok));
temp.put(COLUMN_NOK, Integer.toString(entry.number_nok));
temp.put(COLUMN_HIST, entry.history);
temp.put(COLUMN_PRANDOM, Integer.toString(entry.randomIndex));
temp.put(COLUMN_PHIST, Integer.toString(entry.histIndex));
temp.put(COLUMN_PTOT, Integer.toString(entry.getPriority()));
adapterList.add(temp);
}
// Finally, create the view
ListView listView=(ListView)findViewById(R.id.listview1);
StatViewAdapter adapter=new StatViewAdapter((Activity)this, adapterList);
listView.setAdapter(adapter); // ERROR HERE
}
And here is the complete StatViewAdapter:
public class StatViewAdapter extends BaseAdapter {
public ArrayList<HashMap<String, String>> list;
Activity activity;
TextView txtName;
TextView txtOK;
TextView txtNOK;
TextView txtHist;
TextView txtPrandom;
TextView txtPhist;
TextView txtPtotal;
public StatViewAdapter(Activity activity, ArrayList<HashMap<String, String>> list){
super();
this.activity=activity;
this.list=list;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return list.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return list.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater=activity.getLayoutInflater();
if(convertView == null){
convertView=inflater.inflate(R.layout.list_view, null);
txtName=(TextView) convertView.findViewById(R.id.listname);
txtOK=(TextView) convertView.findViewById(R.id.listok);
txtNOK=(TextView) convertView.findViewById(R.id.listnok);
txtHist=(TextView) convertView.findViewById(R.id.listhist);
txtPrandom =(TextView) convertView.findViewById(R.id.listprandom);
txtPhist=(TextView) convertView.findViewById(R.id.listphist);
txtPtotal=(TextView) convertView.findViewById(R.id.listptot);
}
HashMap<String, String> map=list.get(position);
txtName.setText(map.get(COLUMN_NAME));
txtOK.setText(map.get(COLUMN_OK));
txtNOK.setText(map.get(COLUMN_NOK));
txtHist.setText(map.get(COLUMN_HIST));
return convertView;
}
}
How can it be a null-reference error? I define a valid object, as far as I see, which is not-null...?
Addendum: The 'listview1`:
<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>
</RelativeLayout>
Most probably the line
ListView listView=(ListView)findViewById(R.id.listView1);
is returning null on listview.
Try this,
Replace line
ListView listView=(ListView)findViewById(R.id.listView1);
with
ListView listView=(ListView)view.findViewById(R.id.listView1);
Try to swap these lines below,
ListView listView=(ListView)findViewById(R.id.listview1);
StatViewAdapter adapter=new StatViewAdapter((Activity)this, adapterList);
So, you'll be referring to the same Content view when you set the adapter for the list.
As the error states, listView is null. Make sure you are setting the correct content view. Here is some code to help you:
public class MainActivity extends AppCompatActivity {
private ListView mListView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mListView = (ListView) findViewById(R.id.myListView);
//use mListView as normal
}
}
Better yet, use Butterknife:
public class MainActivity extends AppCompatActivity {
#Bind(R.id.myListView)
ListView mListView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Butterknife.bind(this);
//use mListView as normal
}
}
As an aside, you should probably be using a RecyclerView.
Hi in my application I am parse the json url and displaying the image and text Now I am going to adding the button. if i click the button i want to move to another activity.Now My problem is if i click the button nothing happened .can any one please help me.
ListViewAdapter class:
public class ListViewAdapter extends BaseAdapter {
// Declare Variables
Context context;
LayoutInflater inflater;
ArrayList<HashMap<String, String>> data;
ImageLoader imageLoader;
HashMap<String, String> resultp = new HashMap<String, String>();
public ListViewAdapter(Context context,
ArrayList<HashMap<String, String>> arraylist) {
this.context = context;
data = arraylist;
imageLoader = new ImageLoader(context);
}
#Override
public int getCount() {
return data.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
public View getView(final int position, View convertView, ViewGroup parent) {
// Declare Variables
TextView title;
ImageView thumb_url;
inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View itemView = inflater.inflate(R.layout.listview_item, parent, false);
// Get the position
resultp = data.get(position);
// Locate the TextViews in listview_item.xml
title = (TextView) itemView.findViewById(R.id.rank);
// Locate the ImageView in listview_item.xml
thumb_url = (ImageView) itemView.findViewById(R.id.flag);
// Capture position and set results to the TextViews
title.setText(resultp.get(MainActivity.TITLE));
// Capture position and set results to the ImageView
// Passes flag images URL into ImageLoader.class
imageLoader.DisplayImage(resultp.get(MainActivity.THUMB_URL), thumb_url);
// Capture ListView item click
Button Add = (Button) itemView.findViewById(R.id.add);
Add.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// Get the position
resultp = data.get(position);
Intent intent = new Intent(context, SingleItemView.class);
// Pass all data rank
intent.putExtra("title", resultp.get(MainActivity.TITLE));
// Pass all data country
/*intent.putExtra("country", resultp.get(MainActivity.COUNTRY));
// Pass all data population
intent.putExtra("population",resultp.get(MainActivity.POPULATION));
*/// Pass all data flag
intent.putExtra("thumb_url", resultp.get(MainActivity.THUMB_URL));
// Start SingleItemView Class
context.startActivity(intent);
Intent in = new Intent(getApplicationContext(), MainActivity.class);
startActivity(in);
}
private void startActivity(Intent in) {
// TODO Auto-generated method stub
}
private Context getApplicationContext() {
// TODO Auto-generated method stub
return context;
}
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
}
});
return itemView;
}
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
}
}
listview_item.xml:
<?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="fill_parent" >
<ImageView
android:id="#+id/flag"
android:layout_width="80dp"
android:layout_height="80dp"
android:layout_centerVertical="true"
android:layout_margin="5dp"
android:background="#444"
android:padding="3dp" />
<TextView
android:id="#+id/rank"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dip"
android:layout_toRightOf="#+id/flag"
android:maxLines="1"
android:textSize="15dip"
android:textStyle="bold" />
<!-- <TextView
android:id="#+id/ranklabel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
<TextView
android:id="#+id/rank"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
-->
<!-- <ImageView
android:id="#+id/flag"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:background="#000000"
android:layout_toRightOf="#+id/flag"
android:padding="1dp" />
-->
<Button
android:id="#+id/add"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_below="#+id/rank"
android:text="Add" />
</RelativeLayout>
MainActivity class:
public class MainActivity extends Activity {
// Declare Variables
JSONObject jsonobject;
JSONArray jsonarray;
ListView listview;
ListViewAdapter adapter;
ProgressDialog mProgressDialog;
ArrayList<HashMap<String, String>> arraylist;
static String TITLE = "title";
/*static String COUNTRY = "country";
static String POPULATION = "population";*/
static String THUMB_URL = "thumb_url";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Get the view from listview_main.xml
setContentView(R.layout.listview_main);
// Execute DownloadJSON AsyncTask
new DownloadJSON().execute();
}
// DownloadJSON AsyncTask
private class DownloadJSON extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Create a progressdialog
mProgressDialog = new ProgressDialog(MainActivity.this);
// Set progressdialog title
mProgressDialog.setTitle("Loading...");
// Set progressdialog message
mProgressDialog.setMessage("Loading...");
mProgressDialog.setIndeterminate(false);
// Show progressdialog
mProgressDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
// Create an array
arraylist = new ArrayList<HashMap<String, String>>();
// Retrieve JSON Objects from the given URL address
jsonobject = JSONfunction
.getJSONfromURL("http://indianpoliticalleadersmap.com/android/DemoSchool/json/json_item.php");
try {
// Locate the array name in JSON
jsonarray = jsonobject.getJSONArray("veg_food");
for (int i = 0; i < jsonarray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
jsonobject = jsonarray.getJSONObject(i);
// Retrive JSON Objects
map.put("title", jsonobject.getString("title"));
/*map.put("country", jsonobject.getString("country"));
map.put("population", jsonobject.getString("population"));*/
map.put("thumb_url", jsonobject.getString("thumb_url"));
// Set the JSON Objects into the array
arraylist.add(map);
}
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void args) {
// Locate the listview in listview_main.xml
listview = (ListView) findViewById(R.id.listview);
// Pass the results into ListViewAdapter.java
adapter = new ListViewAdapter(MainActivity.this, arraylist);
// Set the adapter to the ListView
listview.setAdapter(adapter);
// Close the progressdialog
mProgressDialog.dismiss();
}
}
}
Store the hashMap in the view tag.
Button Add = (Button) itemView.findViewById(R.id.add);
Add.setTag(resultp);
Then access it inside onClick() like this
instead of trying to access it by position which may not refer to the current view, access it by its tag. In your code, replace the line
resultp = data.get(position);
with
resultp = (HashMap<String, String>) view.getTag();
EDIT: After adding resultp = data.get(position); as shown above
Replace your onClick() with the following
#Override
public void onClick(View arg0) {
resultp = (HashMap<String, String>) view.getTag();
Intent intent = new Intent(context, SingleItemView.class);
intent.putExtra("title", resultp.get(MainActivity.TITLE));
intent.putExtra("population",resultp.get(MainActivity.POPULATION));
intent.putExtra("thumb_url", resultp.get(MainActivity.THUMB_URL));
context.startActivity(intent);
}
I am writing an android app, and I am having trouble getting a row's position in ListView with CheckBox.
Here is a screenshot on the emulator:
I already made the ListView with CheckBoxes. But I can't figure out how find the row's position for each checked entry. And once I get the checked positions, I want to implement a Remove Selected action.
Please help!
Here is my code:
public class ListTest extends ListActivity implements OnCheckedChangeListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
//--- Importing StringsArray---
Bundle gotBasketScanner = getIntent().getExtras();
String[] StringArrayHistory = gotBasketScanner.getStringArray("fromHistory");
// ---Make Adapter---
setListAdapter( new ArrayAdapter<String>(ListTest.this,
android.R.layout.simple_list_item_multiple_choice,
StringArrayHistory));
// ---Put Array into a ListView and add Checkboxes to Listview
ListView list = getListView();
list.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
}
}
hey check this it will help you...
http://windrealm.org/tutorials/android/listview-with-checkboxes-without-listactivity.php
Android ListView with Checkbox and all clickable
http://appfulcrum.com/2010/09/12/listview-example-3-simple-multiple-selection-checkboxes/
Use onItemClick() in instead of onCheckedChangeListener...
getListView().setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
getListView().setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
Toast.makeText(getApplicationContext(), "Item "+position+" is clicked",
Toast.LENGTH_SHORT).show();
}
}
This is the better way to get the clicked position and id.
I hope this will solve your problem.
EDIT
I have updated the following line:-
getListView().setOnItemClickListener(new AdapterView.OnItemClickListener() {
now try ur code.
You can use PrefrenceScreen with CheckBoxPreference for easier and scalellable implementation
You can use CheckedTextView to implement the same:
main.xml
<?xml version="1.0" encoding="utf-8"?>
<CheckedTextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:clickable="true"
android:focusable="true"
android:checkMark="?android:attr/listChoiceIndicatorMultiple">
</CheckedTextView>
addlist.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" >
<ListView
android:id="#+id/mainListView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
>
</ListView>
<Button android:id="#+id/click"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Click"/>
</LinearLayout>
And here is the activity GetCheckedTextPositionActivity. On click of the button you will get the positions of the listitem checked :
public class GetCheckedTextPositionActivity extends Activity {
private ListView myList;
private EfficientAdapter myAdapter;
private ArrayList<String> data;
private LayoutInflater mInflater;
private Button click;
private ArrayList<Integer> positions;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.addlist);
positions = new ArrayList<Integer>();
data = new ArrayList<String>();
data.add("Bangalore");
data.add("Delhi");
data.add("Patna");
data.add("Mumbai");
click = (Button)findViewById(R.id.click);
mInflater = LayoutInflater.from(getApplicationContext());
myList = (ListView) findViewById(R.id.mainListView);
myAdapter = new EfficientAdapter(data, getApplicationContext());
myList.setAdapter(myAdapter);
click.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(positions.size() != 0){
for(Integer pos : positions){
Log.e("Positions checked :"," Positions :"+pos);
}
}
}
});
}
public class EfficientAdapter extends BaseAdapter {
private ArrayList<String> myData;
public EfficientAdapter(ArrayList<String> mData, Context ctx) {
// TODO Auto-generated constructor stub
this.myData = mData;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return myData.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return myData.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final int currentPos = position;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.main, null);
}
((CheckedTextView) convertView).setText(myData.get(position));
((CheckedTextView) convertView).setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
((CheckedTextView) v).toggle();
if(((CheckedTextView) v).isChecked()){
positions.add(currentPos);
}
}
});
return convertView;
}
}
}
Hope this helps.
I have an xml with one textveiw and one edittext in it .I used this xml to get different rows in the list view of another xml file to list the data in that page.
The xml file that is used to list data in listview is as given below
<?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="wrap_content"
android:paddingTop="2dip"
android:paddingBottom="0dip">
<TextView
android:id="#+id/tv_Sort_Address"
android:layout_width="0dip"
style="#style/ListTextViewStyle"
android:layout_height="wrap_content"
android:text="No"
android:layout_weight="2"/>
<EditText
android:textColor="#000000"
android:layout_height="wrap_content"
android:layout_width="0dip"
android:inputType="number"
style="#style/EditTextStyle"
android:background="#android:drawable/editbox_background"
android:id="#+id/et_Sort_Order"
android:layout_weight="1">
</EditText>
</LinearLayout>
I filled the Listview with data on another xml fils as given below
simpleAdapter = new SimpleAdapter(this, alist,
R.layout.sort_order_list_row, new String[] { "Sort_Address",
"Sort_FKDeliveryStatus", "Sort_PKDelivery",
"Sort_DeliveryOrder" }, new int[] {
R.id.tv_Sort_Address, R.id.tv_Sort_FKDeliveryStatus,
R.id.tv_Sort_PKDelivery, R.id.et_Sort_Order });
listSortOrder.setAdapter(simpleAdapter);
The problem with me is that if i have two row in the listview and when i
placed a value in one of edit text row and move on to the another rows edit text the value placed in the first row got disappered.
<ListView android:id="#+id/lv_Sort_Order"
style="#style/ListTextBackGround"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1"
android:layout_marginLeft="5dip"
android:descendantFocusability="afterDescendants"
android:layout_marginRight="5dip" >
</ListView>
to solve this I placed android:descendantFocusability="afterDescendants" in the list view page to get focus on to the merged page. But it didn't solve the problem. Will anyone help me please.
Is there any property I need to be placed in the list view or in the merged Page?
Use this code :
public class ListViewDemo extends Activity {
private ListView listViewScore = null;
private ListViewAdapter listViewAdapter = null;
private String[] usernameArr = null;
private String[] scoreArr = null;
//ArrayList<String> usernameArrLst = null ,scoreArrLst = null;
//private Helper helper = null;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
listViewScore=(ListView)findViewById(R.id.listViewScore);
usernameArr = new String[]{"Alan","Bob","Carl","Doaniel","Evan","Fred","Gram"};
scoreArr = new String[usernameArr.length];
//usernameArrLst = new ArrayList<String>(Arrays.asList(usernameArr));
//scoreArrLst = new ArrayList<String>(Arrays.asList(scoreArr));
listViewAdapter = new ListViewAdapter();
listViewScore.setAdapter(listViewAdapter);
}
class ListViewAdapter extends BaseAdapter{
#Override
public int getCount() {
// TODO Auto-generated method stub
if(usernameArr==null){
return 0;
}
return usernameArr.length;
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return usernameArr[position];
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(int position, View view, ViewGroup parent) {
// TODO Auto-generated method stub
final ViewHolder viewHolder ;
View rowView=view;
if(rowView==null){
LayoutInflater layoutinflate =LayoutInflater.from(ListViewDemo.this);
rowView=layoutinflate.inflate(R.layout.listviewnewtext, parent, false);
viewHolder = new ViewHolder();
viewHolder.tv_Sort_Address = (TextView)rowView.findViewById(R.id.tv_Sort_Address);
viewHolder.et_Sort_Order = (EditText)rowView.findViewById(R.id.et_Sort_Order);
viewHolder.et_Sort_Order.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// TODO Auto-generated method stub
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
scoreArr[viewHolder.ref] = s.toString();
}
});
rowView.setTag(viewHolder);
}else{
viewHolder = (ViewHolder) rowView.getTag();
}
viewHolder.ref = position;
viewHolder.tv_Sort_Address.setText(usernameArr[position]);
viewHolder.et_Sort_Order.setText(scoreArr[position]);
return rowView;
}
}//class ends
class ViewHolder{
TextView tv_Sort_Address;
EditText et_Sort_Order;
int ref;
}
}
Is there any reason why you use SimpleAdapter? Can you try using ArrayAdapter or BaseAdapter.
Check this and any BaseAdapter example.
Iam trying to create a list view dynamically, Please provide me an example for list view in android...
Activity class......
public class UsersListActivity extends ListActivity{
RegisterUser registerUser;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String[] statesList = getListOfAllUsers();
Toast.makeText(getApplicationContext(),
"States Array lentgh is : " + statesList.length,
Toast.LENGTH_LONG).show();
setListAdapter(new ArrayAdapter<String>(this, R.layout.list_item,
statesList));
ListView lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(getApplicationContext(),
"You selected : "+((TextView) view).getText(), Toast.LENGTH_SHORT).show();
}
});
}}
and create an xml file named list_item.xml and paste the below code.
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="10dp"
android:textSize="16sp" android:textColor="#ffffff" android:textStyle="bold" android:background="#drawable/border_cell">
</TextView>
You can create your own List View by extending Base adapter class
public class ListAdapterDroidman extends BaseAdapter{
private ArrayList<ListitemDroidman> list = new ArrayList<ListitemDroidman>();
#SuppressWarnings("unused")
private Context context;
public ListAdapterDroidman(Context context) {
this.context = context;
}
public void addItem(ListitemDroidman item) {
list.add(item);
}
public void addItem(ListitemDroidman item,int pos)
{
list.add(pos, item);
}
public void removeItem(int pos)
{
list.remove(pos);
}
public void clearList()
{
list.clear();
}
public int getCount() {
// TODO Auto-generated method stub
return list.size();
}
public Object getItem(int position) {
// TODO Auto-generated method stub
return list.get(position);
}
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
return list.get(position);
}
}
Then create your own layout
public class ListitemDroidman extends LinearLayout {
TextView filename;
ImageView iv;
public ListitemDroidman(Context context) {
super(context);
}
public void setInfo(Context context, Bitmap icon, String fname,int colorId) {
iv=new ImageView(context);
iv.setImageBitmap(icon);
iv.setPadding(0, 0, 20, 0);
addView(iv);
filename = new TextView(context);
filename.setTextSize(20);
filename.setTextColor(getResources().getColor(colorId));
filename.setText(fname);
addView(filename);
}
}
Now create listitems in your activityClass
create object of the adapter that u have created
myListitem = new ListitemDroidman(this);
icon = BitmapFactory.decodeResource(getResources(),
R.drawable.folder_icon);
myListitem.setInfo(getApplicationContext(), icon, filelist[i],
R.color.color_white);
add the listitem to the adaper as in normal list
la_file.addItem(myListitem);
Try this tutorial to understand how to use ListView.
http://developer.android.com/resources/tutorials/views/hello-listview.html
Why don't you just take a look at the ApiDemos of your android SDK..
You can find 14 examples of ListActivities implementations..
Or just search here or on Google, you can find lots of examples
Then if you want to achieve something in particular you can ask a more specific question here, does it sound fair?