I'm using a custom listview which I want to add an item to my listview. But it seems to be skipping all the code to add the item. Can someone please tell me how I should adjust my code to achieve this.
Thank you in advance.
This is my Main Activity in which I call a custom Dialog
public class MainActivity extends ActionBarActivity {
TextView threadId;
ArrayList<MessageItem> items = new ArrayList<MessageItem>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button newMessage = (Button) findViewById(R.id.new_message_button);
final Context context = this;
final ListView listView = (ListView) this.findViewById(R.id.messagingListView);
final ActivityAdapter itemAdapter = new ActivityAdapter(getApplicationContext(), this.MessageFeedData());
listView.setAdapter(itemAdapter);
listView.setTextFilterEnabled(true);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
listView.getAdapter().getItem(position);
MessageItem itemAtPos = (MessageItem) parent.getItemAtPosition(position);
Intent intent = new Intent(MainActivity.this, ConversationView.class);
intent.putExtra("threadId", String.valueOf(itemAtPos.ThreadId));
startActivity(intent);
}
});
newMessage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// custom dialog
final Dialog dialog = new Dialog(context);
dialog.setContentView(R.layout.write_message_layout);
dialog.setTitle("Title...");
// set the custom dialog components - text, image and button
final Button post_button = (Button) dialog.findViewById(R.id.button_post);
final EditText new_write_message = (EditText) dialog.findViewById(R.id.messge_msg);
final EditText to_message = (EditText) dialog.findViewById(R.id.to_newmsg);
post_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
items.add(new MessageItem(5458, to_message.getText().toString(), "imh", DateTime.now(), new_write_message.getText().toString()));
itemAdapter.notifyDataSetChanged();
if (v.getId() == R.id.button_post);
to_message.setText("");
new_write_message.setText("");
}
});
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(MainActivity.this, "Clicked", Toast.LENGTH_LONG)
.show();
}
});
dialog.show();
}
});
}
public ArrayList<MessageItem> MessageFeedData() {
ArrayList<MessageItem> items = new ArrayList<MessageItem>();
//recieved_item_click_actions fields
items.add(new MessageItem(1, "Bob Doe", "image", DateTime.now(), "Hello how are you?"));
items.add(new MessageItem(200, "Simon Pink", "image", DateTime.now(), "Hello what are you doing"));
return items;
}
class ActivityFeedTask extends AsyncTask<Integer, Void, Void> {
ArrayList<MessageItem> recentTracks;
#Override
protected Void doInBackground(Integer... page) {
try {
recentTracks = new ArrayList<MessageItem>();
Thread.sleep(3000);
MessageItem data = null;
for (int i = 0; i < 10; i++) {
recentTracks.add(data);
}
} catch (Exception e) {
}
return null;
}
}
public class ActivityAdapter extends ArrayAdapter<MessageItem> {
private final Context context;
private final ArrayList<MessageItem> items;
//private int currentPage = 0;
public ActivityAdapter(Context context, ArrayList<MessageItem> recentTrackArrayList) {
super(context, 0, recentTrackArrayList);
this.context = context;
this.items = recentTrackArrayList;
}
public View getView(int position, View convertView, ViewGroup parent) {
View rowView;
{
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = getLayoutInflater().inflate
(R.layout.message_list_item, parent, false);
rowView = convertView;
TextView comment2 = (TextView) rowView
.findViewById(R.id.messaging_username);
comment2.setText(items.get(position).Username);
ImageView comment3 = (ImageView) rowView
.findViewById(R.id.messaging_photo);
if (items.get(position).Image == null) {
comment3.setImageResource(R.drawable.ic_launcher);
}
TextView comment4 = (TextView) rowView
.findViewById(R.id.messaging_date);
comment4.setText(items.get(position).DateTimeStamp.toString());
TextView comment5 = (TextView) rowView
.findViewById(R.id.messaging_string);
comment5.setText(items.get(position).MessageString);
}
return convertView;
}
}
}
This is my custom Dialog
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<EditText
android:id="#+id/to_newmsg"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="TO" />
<EditText
android:id="#+id/messge_msg"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/to_newmsg"
android:text="MESSAGE" />
<Button
android:id="#+id/button_post"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/messge_msg"
android:text="Send" />
</RelativeLayout>
You have this
ArrayList<MessageItem> items = new ArrayList<MessageItem>();
before onCreate
while this
ArrayList<MessageItem> items = new ArrayList<MessageItem>();
in MessageFeedData() is local.
Use a single list and add items to the same then call notifyDateSetChanged() to refresh listview.
As you can see you do not use items as an arg to constructor
final ActivityAdapter itemAdapter = new ActivityAdapter(getApplicationContext(), this.MessageFeedData());
Edit:
final ListView listView = (ListView) this.findViewById(R.id.messagingListView);
items = this.MessageFeedData());
final ActivityAdapter itemAdapter = new ActivityAdapter(getApplicationContext(), items);
Related
Hi guys I am implementing a listview with a clickable button through this tutorial -> https://www.youtube.com/watch?v=ZEEYYvVwJGY
and I want to achieve the same output.
But I have a slight problem, since my list view is populated from mysql database but in the tutorial is not populated from mysql database so we have a different adapter.
Codes in the tutorial
public class MainActivity extends AppCompatActivity{
private ArrayList<String> data = new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_attendance);
ListView lv = (ListView) findViewById(R.id.listview);
lv.setAdapter(new MyListAdapter(this, R.layout.list_item, data));
}
}
Then lets assume that this is the tutorials MyListAdapter
private class MyListAdapter extends ArrayAdapter<String>{
private int layout;
public MyListAdapter(Context context, int resource, List<String> objects) {
super(context, resource, objects);
layout = resource;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder mainViewHolder = null;
if (convertView == null){
LayoutInflater inflater = LayoutInflater.from(getContext());
convertView = inflater.inflate(layout, parent, false);
ViewHolder viewHolder = new ViewHolder();
viewHolder.tvid = (TextView) convertView.findViewById(R.id.studId);
viewHolder.tvname = (TextView) convertView.findViewById(R.id.studName);
viewHolder.btnP = (Button) convertView.findViewById(R.id.present);
viewHolder.btnA = (Button) convertView.findViewById(R.id.absent);
viewHolder.btnP.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getContext(),"Button Clicked " + position, Toast.LENGTH_LONG).show();
}
});
convertView.setTag(viewHolder);
}
return convertView;
}
}
and my problem is in this part
the setAdapter
mylistView = (ListView) findViewById(R.id.list);
final ListAdapter adapter = new SimpleAdapter(Attendance.this,
studentList, R.layout.list_att, new String[]{
TAG_ID, TAG_NAME}, new int[]{
R.id.studId, R.id.studName});
mylistView.setAdapter(adapter);
what should I do? any help would be appreciated thanks in advance :)
this is my code
public class Attendance extends AppCompatActivity {
TextView Date;;
ListView mylistView;
private ArrayList<HashMap<String, String>> studentList = new ArrayList<HashMap<String, String>>();
TextView Name;
private static String url = "http://10.0.2.2/MobileClassRecord/getStudent.php";
private static final String TAG_STUDENTS = "students";
private static final String TAG_ID = "stud_id";
private static final String TAG_NAME = "stud_name";
JSONArray students = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_attendance);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
Date = (TextView) findViewById(R.id.tvDate);
final Calendar calendar = Calendar.getInstance();
int dd = calendar.get(Calendar.DAY_OF_MONTH);
int mm = calendar.get(Calendar.MONTH);
int yy = calendar.get(Calendar.YEAR);
Date.setText(new StringBuilder().append(yy).append("-").append(mm + 1).append("-").append(dd));
new JSONParse().execute();
studentList = new ArrayList<HashMap<String, String>>();
}
private class JSONParse extends AsyncTask<String, String, JSONObject>{
private ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
Name =(TextView) findViewById(R.id.studName);
pDialog = new ProgressDialog(Attendance.this);
pDialog.setMessage("Getting Data from Database...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected JSONObject doInBackground(String... params) {
JSONParser jParser = new JSONParser();
JSONObject json = jParser.getJSONFromUrl(url);
return json;
}
#Override
protected void onPostExecute(JSONObject jsonObject) {
pDialog.dismiss();
try {
students = jsonObject.getJSONArray(TAG_STUDENTS);
for (int i = 0; i < students.length(); i++){
JSONObject c =students.getJSONObject(i);
final String Id = c.getString(TAG_ID);
String Name = c.getString(TAG_NAME);
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_ID, Id);
map.put(TAG_NAME, Name);
studentList.add(map);
mylistView = (ListView) findViewById(R.id.list);
final ListAdapter adapter = new SimpleAdapter(Attendance.this,
studentList, R.layout.list_att, new String[]{
TAG_ID, TAG_NAME}, new int[]{
R.id.studId, R.id.studName});
mylistView.setAdapter(adapter);
mylistView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String ID = ((TextView) (view.findViewById(R.id.studId))).getText().toString();
Toast.makeText(Attendance.this, "List Clicked " + ID, Toast.LENGTH_LONG).show();
SharedPreferences preferences = getSharedPreferences("MyApp", MODE_PRIVATE);
preferences.edit().putString("id", ID).commit();
}
});
}
}catch (JSONException e){
e.printStackTrace();
}
}
}
private class MyListAdapter extends ArrayAdapter<String>{
private int layout;
public MyListAdapter(Context context, int resource, List<String> objects) {
super(context, resource, objects);
layout = resource;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder mainViewHolder = null;
if (convertView == null){
LayoutInflater inflater = LayoutInflater.from(getContext());
convertView = inflater.inflate(layout, parent, false);
ViewHolder viewHolder = new ViewHolder();
viewHolder.tvid = (TextView) convertView.findViewById(R.id.studId);
viewHolder.tvname = (TextView) convertView.findViewById(R.id.studName);
viewHolder.btnP = (Button) convertView.findViewById(R.id.present);
viewHolder.btnA = (Button) convertView.findViewById(R.id.absent);
viewHolder.btnP.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getContext(),"Button Clicked " + position, Toast.LENGTH_LONG).show();
}
});
convertView.setTag(viewHolder);
}
mainViewHolder = (ViewHolder) convertView.getTag();
mainViewHolder.tvid.setText(getItem(position));
return convertView;
}
}
public class ViewHolder{
TextView tvid, tvname;
Button btnP, btnA;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_attendance, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case android.R.id.home:
Intent intent = new Intent(Attendance.this, SpecificClassRecord.class);
startActivity(intent);
return true;
case R.id.action_view_attendance:
Intent intent1 = new Intent(Attendance.this, ViewAttendance.class);
startActivity(intent1);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
Sample Layout
like Udi said, more information would be nice.
One strange thing in your code is in the getView() method.
you have
if(convertView==null){
...
}else{
...
}
I think the else part is wrong. Just remove the else and the brackets (not the code insight of it).
The code in the else part is important, because without it the code will not change the TextView when the View is loaded for the first time. This mean, that your getView will do nothing
EDIT
The author has changed the code. You have now two different adapters there...
In my opinion the getView() Method should look like this
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder mainViewHolder = null;
if (convertView == null){
LayoutInflater inflater = LayoutInflater.from(getContext());
convertView = inflater.inflate(layout, parent, false);
ViewHolder viewHolder = new ViewHolder();
viewHolder.tvid = (TextView) convertView.findViewById(R.id.studId);
viewHolder.tvname = (TextView) convertView.findViewById(R.id.studName);
viewHolder.btnP = (Button) convertView.findViewById(R.id.present);
viewHolder.btnA = (Button) convertView.findViewById(R.id.absent);
viewHolder.btnP.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getContext(),"Button Clicked " + position, Toast.LENGTH_LONG).show();
}
});
convertView.setTag(viewHolder);
}
mainViewHolder = (ViewHolder) convertView.getTag();
mainViewHolder.tvid.setText(getItem(position));
return convertView;
}
}
But for me it is still not clear where exactly the problem is. Is the App crashing or is there just a behavior you don't understand? If yes, what exactly?
If the App is crashing, when exactly?
EDIT 2:
mylistView = (ListView) findViewById(R.id.list);
final ListAdapter adapter = new MyListAdapter(Attendance.this,
R.layout.list_att, new String[]{
TAG_ID, TAG_NAME});
mylistView.setAdapter(adapter);
maybe this is all. I assume the layout of your rows is given by the layoutressource R.layout.list_att and that TAG_ID and TAG_Name are defined somewhere before.
I see your new Adapter needs a List of Strings. Insert the following before you set the adapter
List<String> test = new ArrayList<String>();
test.add("1");
test.add("2"):
test.add("3");
and then your adapter should look like this
final ListAdapter adapter = new MyListAdapter(Attendance.this,
R.layout.list_att, test);
Hi I want to add an item to a listview.
This is my New message activity in which I wan to pass an item to my Main Activity. I'm not quite sure how to pass this data through an intent any help would be greatly appreciated.
public class NewMessage extends ActionBarActivity {
EditText new_message;
Button post_new_message_button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new_message);
new_message = (EditText) findViewById(R.id.message_content);
post_new_message_button = (Button) findViewById(R.id.message_send);
post_new_message_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
TextView username = (TextView) findViewById(R.id.conversation_username2);
itemAdapter.add(new MessageItem(1656,"Bill Smith", "image", DateTime.now(), new_message.getText().toString()));
itemAdapter.notifyDataSetChanged();
if (v.getId() == R.id.message_send);
new_message.setText("");
}
});
}
}
This is my main activity I want to pass in the data
public class MainActivity extends ActionBarActivity {
TextView threadId;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button newMessage = (Button) findViewById(R.id.new_message_button);
newMessage.setOnClickListener (new View.OnClickListener(){
#Override
public void onClick(View v){
Intent newMessage = new Intent(MainActivity.this, NewMessage.class);
startActivity(newMessage);
}
});
final ListView listView = (ListView) this.findViewById(R.id.messagingListView);
final ActivityAdapter itemAdapter = new ActivityAdapter(getApplicationContext(), this.MessageFeedData());
listView.setAdapter(itemAdapter);
listView.setTextFilterEnabled(true);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
listView.getAdapter().getItem(position);
}
});
}
// Get dummy data for Activity Feed
public ArrayList<MessageItem> MessageFeedData() {
ArrayList<MessageItem> items = new ArrayList<MessageItem>();
items.add(new MessageItem(1, "Bob Doe", "image", DateTime.now(), "Hello how are you?"));
items.add(new MessageItem(200, "John Smith", "image", DateTime.now(), "Hello what are you doing"));
return items;
}
class ActivityFeedTask extends AsyncTask<Integer, Void, Void> {
ArrayList<MessageItem> recentTracks;
}
public class ActivityAdapter extends ArrayAdapter<MessageItem> {
private final Context context;
private final ArrayList<MessageItem> items;
//private int currentPage = 0;
public ActivityAdapter(Context context, ArrayList<MessageItem> recentTrackArrayList) {
super(context, 0, recentTrackArrayList);
this.context = context;
this.items = recentTrackArrayList;
}
public View getView(int position, View convertView, ViewGroup parent) {
View rowView;
{
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = getLayoutInflater().inflate
(R.layout.message_list_item, parent, false);
//final MessageItem item = items.get(position);
rowView = convertView;
TextView comment2 = (TextView) rowView
.findViewById(R.id.messaging_username);
comment2.setText(items.get(position).Username);
ImageView comment3 = (ImageView) rowView
.findViewById(R.id.messaging_photo);
if (items.get(position).Image == null) {
comment3.setImageResource(R.drawable.ic_launcher);
}
TextView comment4 = (TextView) rowView
.findViewById(R.id.messaging_date);
comment4.setText(items.get(position).DateTimeStamp.toString());
TextView comment5 = (TextView) rowView
.findViewById(R.id.messaging_string);
comment5.setText(items.get(position).MessageString);
}
return convertView;
}
}
}
if you just want to pass data back and forth between the two activities, maybe you should use:
startActivityForResult(Intent intent, int requestCode)
and
onActivityResult(int requestCode, int resultCode, Intent data)
So that when the NewMessageActivity finishes, it can send the data back to the main activity.
I have designed an list view which has one imageview, textview, and button. initially the imageview and textview will be visible on clicking the imageview delete button will visible for selected view but my problem is while selecting the next list option i need to hide the button i need to show only one button at a time. can anyone help me please?
public class HistoryMenu extends MainActivity {
public final static String ITEM_TITLE = "title";
public final static String ITEM_CAPTION = "caption";
public static Boolean deletedispflag=false;
public static View selectdelete=null;
String optionSelectedValue;
ArrayList<String> listString;
ArrayAdapter<String> aa;
ListView settingsSubList;
LayoutInflater linf;
// public String[] stringList={"N # 17.3 MPH (16-18)","10:25, 20 June 2013","N # 17.3 MPH (16-18)","10:25, 20 June 2013","N # 17.3 MPH (16-18)","10:25, 20 June 2013","N # 17.3 MPH (16-18)","10:25, 20 June 2013"};
// HistoryListAdapters historyListAdapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_history_menu);
settingsSubList = (ListView) findViewById(R.id.settings_sub_list);
LayoutParams layout = new LayoutParams(Gravity.CENTER);
LayoutInflater inflator = (LayoutInflater)this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View v = inflator.inflate(R.layout.centered_menu_title, null);
((TextView)v.findViewById(R.id.title)).setTextColor(getResources().getColor(R.color.white));
this.getSupportActionBar().setCustomView(v,layout);
listString=new ArrayList<String>();
listString.add("history object 1");
listString.add("history object 2");
listString.add("history object 3");
listString.add("history object 4");
listString.add("history object 5");
MyArrayAdapter adapter = new MyArrayAdapter(this, R.layout.history_option_selector, listString);
settingsSubList.setAdapter(adapter);
settingsSubList.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View arg1, int position,
long arg3) {
}
});
}
public class MyArrayAdapter extends ArrayAdapter<String> {
int previousDegrees = 0;
int degrees = 90;
RotateAnimation animation = new RotateAnimation(0f, 90f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f); //, 200, 200); // canvas.getWidth() / 2, canvas.getHeight() / 2);
Context context;
int layoutResourceId;
ArrayList<String> historyitems = new ArrayList<String>();
public MyArrayAdapter(Context context, int layoutResourceId,ArrayList<String> historyitems)
{
super(context, layoutResourceId, historyitems);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.historyitems = historyitems;
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
animation.setDuration(1000L);
View item = convertView;
if (item == null) {
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
item = inflater.inflate(layoutResourceId, parent, false);
}
TextView items = (TextView) item.findViewById(R.id.history_list_option_text);
final ImageView select_option = (ImageView) item.findViewById(R.id.history_list_option_select_image);
final Button delete = (Button) item.findViewById(R.id.history_list_option_delete_button);
delete.setVisibility(View.INVISIBLE);
String itemtext = historyitems.get(position);
items.setText(itemtext);
select_option.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
select_option.startAnimation(animation);
if(deletedispflag == false)
{
delete.setVisibility(v.VISIBLE);
selectdelete = v;
deletedispflag=true;
}
else if(deletedispflag==true)
{
delete.setVisibility(selectdelete.INVISIBLE);
deletedispflag=false;
}
Toast.makeText(context, "Edit", Toast.LENGTH_LONG).show();
}
});
delete.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(context, "Delete", Toast.LENGTH_LONG).show();
}
});
return item;
}
}
#Override
public void onBackPressed() {
// TODO Auto-generated method stub
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
overridePendingTransition(R.drawable.activity_in_left_to_right_animation,R.drawable.activity_out_right_to_left_animation);
}
}
You can achieve this by storing the reference previously clicked button
private Button prevDelete;
And change click listener to something like below:
select_option.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(prevDelete!=null){
prevDelete.setVisibility(View.INVISIBLE);
}
delete.setVisibility(View.VISIBLE);
prevDelete = delete;
select_option.startAnimation(animation);
selectdelete = v;
Toast.makeText(context, "Edit", Toast.LENGTH_LONG).show();
}
});
I am adding one button per row to show off map in that row in array adapter . I want to get hold of value in that row when that button is clicked . How can I get those values on click of button .
my class:
public class MyListAdapter extends ArrayAdapter<String> {
private final Context context;
private final ArrayList<HashMap<String, ArrayList<String>>> pjclist;
private final ArrayList<PermJorneyCycleBean> pjcarraylist ;
String villagename;
int black = Color.WHITE;
float village = 20f;
float depot = 16f;
int red = Color.RED;
int count;
ArrayList<String> Deoptname;
public MyListAdapter(Context context,ArrayList<HashMap<String, ArrayList<String>>>pjcretrivelist, String [] villagename,ArrayList<PermJorneyCycleBean>itempjcarraylist) {
// public MyListAdapter(Context context,ArrayList<PermJorneyCycleBean> pjcretrivelist, String [] villagename) {
super(context, R.layout.scheduleplan,villagename);
this.context = context;
this.pjcarraylist=itempjcarraylist;
this.pjclist=pjcretrivelist;
count =pjcretrivelist.size();
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LinearLayout rowView1=null;
LinearLayout rowView=null;
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (position<count){
rowView1= (LinearLayout) inflater.inflate(R.layout.scheduleplan, null, true);
rowView= (LinearLayout) rowView1.findViewById(R.id.plan);
HashMap<String, ArrayList<String>> depotlistnew = new HashMap<String, ArrayList<String>>();
depotlistnew = pjclist.get(position);
Iterator<Entry<String, ArrayList<String>>> itr = depotlistnew.entrySet().iterator();
while (itr.hasNext()) {
Map.Entry pairs = (Map.Entry) itr.next();
villagename = pairs.getKey().toString();
createNewRow(rowView, villagename, black, village);
Deoptname = (ArrayList) pairs.getValue();
for (int i = 0; i < Deoptname.size(); i++) {
String depotname = new String();
depotname = Deoptname.get(i);
createNewRow(rowView, depotname, red, depot);
}
}
Button mapbutton = createbutton(rowView, "Locate on Map");
mapbutton.setTag(position);
mapbutton.setClickable(true);
mapbutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getContext(), " This is to depot map"+villagename,Toast.LENGTH_LONG).show();
}
});
}
else if (position==count){
rowView1 = (LinearLayout) inflater.inflate(R.layout.schedulemap, null, true);
Button villagebutton = (Button)rowView1.findViewById(R.id.getBack);
villagebutton.setClickable(true);
villagebutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getContext(), "This is for Map"+villagename,Toast.LENGTH_LONG).show();
}
});
}
else if (position==count+1)
{
rowView1 = (LinearLayout) inflater.inflate(R.layout.scheduleplanlast, null, true);
Button backbutton = (Button)rowView1.findViewById(R.id.getBackHome);
backbutton.setClickable(true);
backbutton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getContext(), " This is to test it",Toast.LENGTH_LONG).show();
}
});
}
return rowView1;
}
public void createNewRow(LinearLayout ll1, String value, Integer color,float size) {
TextView tv = new TextView(ll1.getContext());
tv.setTextColor(color);
tv.setTextSize(size);
tv.setText(value);
ll1.addView(tv);
}
public Button createbutton(LinearLayout ll1, String value) {
Button backbutton = new Button(ll1.getContext());
backbutton.setText(value);
backbutton.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));
ll1.addView(backbutton);
return backbutton;
}
public TextView createTextView(LinearLayout ll1, String value){
TextView lattextview = new TextView(ll1.getContext());
lattextview.setVisibility(0);
lattextview.setText(value);
lattextview.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));
ll1.addView(lattextview);
return lattextview;
}
}
I am not able to get hold of position on click of those buttons .
For your reference i have the following code snippet for button click on Array Adapter
class MySimpleArrayAdapter extends ArrayAdapter<String> {
private Context context;
public MySimpleArrayAdapter(Context context) {
super(context, R.layout.buddy_list);
this.context = context;
}
public int getCount() {
return speedList.size();
}
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View rowView = convertView;
if (rowView == null) {
LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
rowView = vi.inflate(R.layout.speeddial_list, null);
}
TextView name = (TextView) rowView.findViewById(R.id.Name);
TextView buddyId = (TextView) rowView.findViewById(R.id.sipid);
Button btn = (Button)rowView.findViewById(R.id.speeddialbtn);
name.setText(speedList.get(position).getName());
buddyId.setText(speedList.get(position).getNumber());
btn.setText(Integer.toString(speedList.get(position).getSPDIndex()));
/*name.setText(names.get(position).toString());
buddyId.setText(buddyIds.get(position).toString());
btn.setText(numberButton.get(position).toString());*/
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
if (!speedList.get(0).getName().equals(" No SpeedDial Found")) {
registerForContextMenu(getListView());
getListView().showContextMenu();
} else {
unregisterForContextMenu(getListView());
}
selected_name_fromlist = speedList.get(position).getName();
selected_number_fromlist = speedList.get(position).getNumber();
System.out.println(" selected :" + selected_name_fromlist);
}
});
return rowView;
}
}
Here is a good Handling Button clicks in a ListView Row tutorial.
I have a listview, and i start an intent to fill it. But the list shows up with a default image and no text. It is supposed to show up with different images and text.
I have two arrays, one is in string type and the other one is in drawable type... But my list doesn't show me none of these that i wanted...
My ListActivity:
public class fillLeftMenu extends ListActivity {
private View menu;
ImageView findLocation;
Spinner cityList;
ListView leftList;
String [] textIndex;
Drawable [] imageIndex;
ArrayList<LeftListItems> Left;
listAdapter lAdapter;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
dataTransfer dt = BonubonActivity.deneme;
menu = dt.getView();
findLocation = (ImageView) menu.findViewById(R.id.image_findLocation);
leftList = (ListView) menu.findViewById(R.id.list);
// add items to listView
Left = new ArrayList<LeftListItems>();
textIndex = new String[] {"Bugünün Fırsatları", "Son Dakika Bonusları", "Kadın", "Aile", "Çocuk", "Alışveriş", "Şehirden Kaçış", "Kışa Özel"};
imageIndex = new Drawable[] {leftList.getResources().getDrawable(R.drawable.kucukicon_01),leftList.getResources().getDrawable(R.drawable.kucukicon_02),leftList.getResources().getDrawable(R.drawable.kucukicon_03),leftList.getResources().getDrawable(R.drawable.kucukicon_04),leftList.getResources().getDrawable(R.drawable.kucukicon_05),leftList.getResources().getDrawable(R.drawable.kucukicon_06),leftList.getResources().getDrawable(R.drawable.kucukicon_07),leftList.getResources().getDrawable(R.drawable.kucukicon_08)};
lAdapter = new listAdapter(menu.getContext(), R.layout.list_item, Left);
leftList.setAdapter(lAdapter);
getIndex();
lAdapter.notifyDataSetChanged();
leftList.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
}
});
finish();
}
private void getIndex() {
try{
LeftListItems item = new LeftListItems();
for(int i=0; i<textIndex.length; i++) {
item.setText(textIndex[i]);
item.setImage(imageIndex[i]);
Left.add(item);
lAdapter.add(Left.get(i));
}
}
catch (Exception e) {
Log.e("BACKGROUND_PROC", e.getMessage());
}
}
private class listAdapter extends ArrayAdapter<LeftListItems> {
private ArrayList<LeftListItems> items;
private Context ctx;
public listAdapter(Context ctx, int textViewResourceId, ArrayList<LeftListItems> items) {
super(ctx, textViewResourceId, items);
this.ctx = ctx;
this.items = items;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater vi = (LayoutInflater) ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.list_item, null);
}
LeftListItems index = items.get(position);
if(index != null) {
TextView text = (TextView) v.findViewById(R.id.text);
ImageView img = (ImageView) v.findViewById(R.id.icon);
if(text != null)
text.setText(index.getText());
if(img != null)
img.setBackgroundDrawable(index.getImage());
}
return v;
}
}
}
Try calling getIndex() method before creating the adapter and setting it to the list. Like this:
getIndex();
//then create new adapter
lAdapter = new listAdapter(menu.getContext(), R.layout.list_item, Left);
leftList.setAdapter(lAdapter);