Adding dynamic items to listview - android

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.

Related

How do I use variables of some class in a different class ( ConsumerDescAndEdit.java ) through onItemClickListener?

I need to display name, phoneNumber and accountNumber in EditText in the class ConsumerdescAndEdit, so how do pass these values when OnItemClickListener is executed?
ShowAll.java:
I have the ListView that inflated from CustomAdapter.
Intent intent = new Intent(ShowAll.this,ConsumerDescAndEdit.class);
startActivity(intent);
CustomAdapter.java:
public class CustomAdapter extends BaseAdapter {
Context mContext;
TextView nameView;
TextView phoneNumberView;
TextView accountView;
String name;
String phoneNumber;
String accountNumber;
ArrayList<Consumer> objects;
public CustomAdapter(Context context, int resource, ArrayList<Consumer> objects){
this.objects = objects;
this.mContext = context;
}
public CustomAdapter(){
}
#Override
public int getCount() {
return objects.size();
}
#Override
public Object getItem(int position) {
return objects.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
Consumer consumer = (Consumer) getItem(position);
// Values to be displayed.
name = consumer.getName();
phoneNumber = consumer.getPhoneNumber();
accountNumber = consumer.getAccountNumber();
LayoutInflater inflater = LayoutInflater.from(mContext); // generate an inflater using context.
convertView = inflater.inflate(R.layout.details_layout,null); // inflate details_layout and store it in convertView.
nameView = convertView.findViewById(R.id.nameView);
phoneNumberView = convertView.findViewById(R.id.phoneNumberView);
accountView = convertView.findViewById(R.id.accountView);
nameView.setText(name);
phoneNumberView.setText(phoneNumber);
accountView.setText(accountNumber);
return convertView;
}
}
ConsumerDescAndEdit.java (where do I need to use variables):
public class ConsumerDescAndEdit extends AppCompatActivity {
Button updateButton;
EditText nameEditTextVar;
EditText phoneEditTextVar;
EditText accountEditTextVar;
// Variables to store user inputted data.
String nameEdit;
String phoneEdit;
String accountEdit;
DatabaseHelper dbHelper;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_consumer_desc_and_edit);
dbHelper = new DatabaseHelper(this);
updateButton = findViewById(R.id.updateButton);
nameEditTextVar = findViewById(R.id.nameEditScreen);
phoneEditTextVar = findViewById(R.id.phoneNumberEditScreen);
accountEditTextVar = findViewById(R.id.accountNumberEditScreen);
String s_intent = getIntent().getStringExtra("EXTRA_SESSION_ID");
nameEditTextVar.setText(s_intent);
updateButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
nameEdit = nameEditTextVar.getText().toString();
phoneEdit = phoneEditTextVar.getText().toString();
accountEdit = accountEditTextVar.getText().toString();
if (nameEdit.isEmpty() || phoneEdit.isEmpty() || accountEdit.isEmpty()) {
Toast.makeText(ConsumerDescAndEdit.this, "Data Insufficient", Toast.LENGTH_SHORT).show();
} else {
boolean b = dbHelper.updateData(nameEdit, phoneEdit, accountEdit);
if (b)
Toast.makeText(ConsumerDescAndEdit.this, "Data updated", Toast.LENGTH_SHORT).show();
else
Toast.makeText(ConsumerDescAndEdit.this, "Could not update data", Toast.LENGTH_SHORT).show();
}
}
});
}
}
When you create the Intent for the edit Activity, add the data from the selected item as "extras" to the Intent, like this:
Intent intent = new Intent(ShowAll.this,ConsumerDescAndEdit.class);
intent.putExtra("name", name);
intent.putExtra("phone", phone);
intent.putExtra("account", account);
startActivity(intent);
In the edit Activity, extract the data from the Intent like this:
String name = intent.getStringExtra("name");
String phone = intent.getStringExtra("phone");
String account = intent.getStringExtra("account");
Try below code
public class CustomAdapter extends BaseAdapter {
Context mContext;
TextView nameView;
TextView phoneNumberView;
TextView accountView;
String name;
String phoneNumber;
String accountNumber;
ArrayList<Consumer> objects;
private ItemClickListener itemClickListener;
public interface ItemClickListener {
void onItemClick(Consumer consumer);
}
public CustomAdapter(Context context, int resource, ArrayList<Consumer> objects, ItemClickListener itemClickListener) {
this.objects = objects;
this.mContext = context;
this.itemClickListener = itemClickListener;
}
public CustomAdapter() {
}
#Override
public int getCount() {
return objects.size();
}
#Override
public Object getItem(int position) {
return objects.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final Consumer consumer = (Consumer) getItem(position);
// Values to be displayed.
name = consumer.getName();
phoneNumber = consumer.getPhoneNumber();
accountNumber = consumer.getAccountNumber();
LayoutInflater inflater = LayoutInflater.from(mContext); // generate an inflater using context.
convertView = inflater.inflate(R.layout.details_layout, null); // inflate details_layout and store it in convertView.
nameView = convertView.findViewById(R.id.nameView);
phoneNumberView = convertView.findViewById(R.id.phoneNumberView);
accountView = convertView.findViewById(R.id.accountView);
nameView.setText(name);
phoneNumberView.setText(phoneNumber);
accountView.setText(accountNumber);
convertView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (itemClickListener != null) {
itemClickListener.onItemClick(consumer);
}
}
});
return convertView;
}
}
In Activity do following
public class ConsumerActivity extends AppCompatActivity implements CustomAdapter.ItemClickListener {
CustomAdapter adapter;
ArrayList<Consumer> objects;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_consumer);
adapter = new CustomAdapter(this, objects, this);
}
#Override
public void onItemClick(Consumer consumer) {
Intent intent = new Intent(this, CustomerEdit.class);
intent.putExtra("Consumer", consumer);
startActivity(intent);
}
}

How to Switch Activities using a Custom ListView Adapter?

I'm trying to use a Custom ListView Adapter to switch to different activities, but am having trouble doing so, as there is an error that I can't seem to get rid of.
Relevant code
Category Table:
public class CategoryTable extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.category_table);
populateTable();
goToPreviousActivity();
}
private void populateTable() {
final ListView mListView = findViewById(R.id.listView);
Category 1 = new Category(" One");
Category 2 = new Category(" Two");
Category 3 = new Category(" Three");
Category 4 = new Category(" Four");
final ArrayList<Category> categoryList = new ArrayList<>();
categoryList.add(1);
categoryList.add(2);
categoryList.add(3);
categoryList.add(4);
CategoryListAdapter adapter = new CategoryListAdapter(this, R.layout.adapter_view_layout, categoryList);
mListView.setAdapter(adapter);
}
private void goToPreviousActivity() {
ImageButton btn = findViewById(R.id.backButton);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
}
public static Intent makeIntent(Context context) {
return new Intent(context, CategoryTable.class);
}
}
Category List Adapter:
public class CategoryListAdapter extends ArrayAdapter<Category> {
private Context mContext;
int mResource;
public CategoryListAdapter(Context context, int resource, ArrayList<Category> objects) {
super(context, resource, objects);
mContext = context;
mResource = resource;
}
#NonNull
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
String name = getItem(position).getName();
Category category = new Category(name);
final LayoutInflater inflater = LayoutInflater.from(mContext);
convertView = inflater.inflate(mResource, parent, false);
Button catName = convertView.findViewById(R.id.btnNextTbl);
catName.setText(name);
catName.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (position == 0) {
//error -> makeIntent(android.content.Context in AllToolsTable cannot be applied to com.test.test.CategoryListAdapter
Intent intent = AllToolsTable.makeIntent(CategoryListAdapter.this);
mContext.startActivity(intent);
} else {
Toast toast = Toast.makeText(getContext(), "Clicked2", Toast.LENGTH_SHORT);
toast.show();
}
}
});
return convertView;
}
}
(I commented above the erroneous piece of code)
All Tools Table:
public class AllToolsTable extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.all_tools_table);
}
public static Intent makeIntent(Context context) {
return new Intent(context, AllToolsTable.class);
}
}
I will provide any other relevant code/details if needed.
Any help will be greatly appreciated.
//error -> makeIntent(android.content.Context in AllToolsTable cannot be applied to com.test.test.CategoryListAdapter
Intent intent = AllToolsTable.makeIntent(CategoryListAdapter.this);
Your AllToolsTable.makeIntent() method requires a Context argument. Normally you'd be fine with something like AllToolsTable.makeIntent(MainActivity.this) because Activity is a subclass of Context. However, CategoryListAdapter is not.
So you need to get your hands on a Context object somehow.
Luckily, the getView() method passes you a non-null ViewGroup parent object, and all views have a context. So you can replace your intent creation with this code:
Context context = parent.getContext();
Intent intent = AllToolsTable.makeIntent(context);

StartActivityForResult to update a row in a ListView

I've the following Activity that uses a ListView to display a list of subjects. Each row has a textview which is set to red to indicate the question for that subject has not yet been answered. When the user clicks on a row it should launch an Activity that asks a question on that subject.
I want to launch the Activity by calling startActivityForResult, this will update the row with the fact the question has been asked and turn the textview green.
My question is how to update a particular row in the listview from onActivityResult?
public class QuestionListForInTransaction extends ActionBarActivity {
ListView listView;
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.questionlistforintxlayout);
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setIcon(R.drawable.ic_launcher);
setTitle("Call Question(s)");
listView = (ListView)findViewById(R.id.txinquestionlist);
String[] values = new String[] { "Are you the driver?", "Question 2", "Question 3", };
MySimpleArrayAdapter adapter = new MySimpleArrayAdapter(this, values);
listView.setAdapter(adapter);
listView.setOnItemClickListener(listener);
}//end of onCreate
public class MySimpleArrayAdapter extends ArrayAdapter<String> {
private final Context context;
private final String[] values;
public MySimpleArrayAdapter(Context context, String[] values) {
super(context, R.layout.questionlisttxinrowlayout, values);
this.context = context;
this.values = values;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(R.layout.questionlisttxinrowlayout, parent, false);
TextView question = (TextView) rowView.findViewById(R.id.tvquestionforintx);
question.setText(values[position]);
TextView answered = (TextView) rowView.findViewById(R.id.rowstatusbox);
answered.setBackgroundColor(Color.RED);
String questionStr = values[position];
rowView.setTag(questionStr);
return rowView;
}
} //end of adapter class
OnItemClickListener listener = new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//Toast.makeText(QuestionListForInTransaction.this, "pos = " + position, Toast.LENGTH_LONG).show();
String question = (String)view.getTag();
if(question.equalsIgnoreCase("Are you the driver?")){
//Toast.makeText(QuestionListForInTransaction.this, "Are you the driver?" + position, Toast.LENGTH_LONG).show();
final int QUESTION_REQUEST = 1;
Intent questionIntent = new Intent(QuestionListForInTransaction.this, Question.class);
startActivityForResult(questionIntent, QUESTION_REQUEST);
//TextView answered = (TextView) view.findViewById(R.id.rowstatusbox);
//answered.setBackgroundColor(Color.GREEN);
}
}
};
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent){
super.onActivityResult(requestCode, resultCode, intent);
Bundle extras = intent.getExtras();
if(extras != null)
int result = extras.getInt("result");
//*********************update a row green**********************
}
} //end of class
Just Create some custom wrapper class like this:
public class QuestionWrapper {
private String mQuestionText;
private boolean mIsAsked;
public QuestionWrapper(String defaultQuestionText, boolean isAsked) {
mQuestionText = defaultQuestionText;
mIsAsked = isAsked;
}
public boolean isAsked() {
return mIsAsked;
}
public void setIsAswked(boolean isAsked) {
mIsAsked = isAsked;
}
public String getQuestionText() {
return mQuestionText;
}
}
then you need to set List of this wrappers to Adapter:
public class QuestionListForInTransaction extends ActionBarActivity {
List<QuestionWrapper> mWrappers = new ArrayList<>();
MySimpleArrayAdapter mAdapter;
....
public void onCreate(Bundle icicle) {
....
wrappers.add(new QuestionWrapper("Are you the driver?",false));
wrappers.add(new QuestionWrapper("Question 2",false));
wrappers.add(new QuestionWrapper("Question 3",false));
mAdapter = new MySimpleArrayAdapter(this, wrappers);
....
and Update Your Adapter like this:
public class MySimpleArrayAdapter extends ArrayAdapter<QuestionWrapper> {
private final Context context;
private final List<QuestionWrapper> mWrappers;
public MySimpleArrayAdapter(Context context, List<QuestionWrapper> wrappers) {
super(context, R.layout.questionlisttxinrowlayout, wrappers);
this.context = context;
this.mWrappers = wrappers;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View rowView = inflater.inflate(R.layout.questionlisttxinrowlayout, parent, false);
QuestionWrapper wrapper = mWrappers.get(position);
TextView question = (TextView) rowView.findViewById(R.id.tvquestionforintx);
question.setText(wrapper.getQuestionText());
TextView answered = (TextView) rowView.findViewById(R.id.rowstatusbox);
if (wrapper.isAsked()) {
answered.setBackgroundColor(Color.GREEN);
} else {
answered.setBackgroundColor(Color.RED);
}
rowView.setTag(wrapper.getQuestionText());
return rowView;
}
onActivityResult - Need to update your wrapper class and adpater:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent){
super.onActivityResult(requestCode, resultCode, intent);
....
mWrappersList.get(yourPosition).setAsked(true/false);
if (mAdapter!=null){
mAdapter.notifyDataSetChanged();
}
...
}
I think for RequestCode in startActivityForResult you can use Adapter click position.

Adding item to listview through a dialog

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);

My ListView consist an ImageView and a TextView i need to get the Text from the TextView

My ListView consist an ImageView and a TextView I need to get the Text from the TextView.
int the position of my list where I press (onItemClick).
How can I do that?
The 1 class have a Button then when you press I moving to the next activity (CountryView)
and expect to get back from the next activity with a text (name of the selected Country)
The 2 classes have a ListView (ImageView and TextView) the data is getting from a database and showing on the ListView.
My problem is to get back to the 1 class the selected name of the country.
Thanks so much for helping!!!
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.home);
// final int recquestCode = 0;
final Button btnCountry = (Button) findViewById(R.id.fromButton);
btnCountry.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
Intent pingIntent = new Intent("CountryView");
pingIntent.putExtra("btnText", " ");
pingIntent.setClass(Travel.this, CountryView.class);
startActivityForResult(pingIntent, RECEIVE_MESSAGE);
}
});
/* Button btnSearch = (Button) findViewById(R.id.searchButton);
btnSearch.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
Intent intent = new Intent(v.getContext(), ResultView.class);
startActivityForResult(intent, 0);
}
});*/
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
if (data.hasExtra("response")){
Button b = (Button)findViewById(R.id.fromButton);
CharSequence seq = data.getCharSequenceExtra("response");
b.setText(seq);
}
}
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.country);
mListUsers = getCountry();
lvUsers = (ListView) findViewById(R.id.countrylistView);
lvUsers.setAdapter(new ListAdapter(this, R.id.countrylistView, mListUsers));
// lvUsers.setTextFilterEnabled(true);
// String extraMsg1 = getIntent().getExtras().getString("extra1");
lvUsers.setOnItemClickListener(new OnItemClickListener()
{
public void onItemClick(AdapterView<?> parent, View view,int position, long id)
{
// When clicked, show a toast with the TextView text
//textItem=view;
// Toast.makeText(getApplicationContext(), ((TextView) view).getText(),
// Toast.LENGTH_SHORT).show();
Intent pongIntent = new Intent();
// lvUsers.getItemAtPosition(position);
t = (TextView) view;
Log.v("fffvd"+t, null);
t.setText(getIntent().getStringExtra("btnText"));
String strText = t.getText().toString();
//((TextView) view).getText().toString()
pongIntent.putExtra("response",strText);
setResult(Activity.RESULT_OK,pongIntent);
finish();
// startActivity(new Intent(CountryView.this,TravelPharmacy.class));
}
});
}
public ArrayList<Country> getCountry(){
DBHelper dbAdapter=DBHelper.getDBAdapterInstance(this);
try {
dbAdapter.createDataBase();
} catch (IOException e) {
Log.i("*** select ",e.getMessage());
}
dbAdapter.openDataBase();
String query="SELECT * FROM Pays;";
ArrayList<ArrayList<String>> stringList = dbAdapter.selectRecordsFromDBList(query, null);
dbAdapter.close();
ArrayList<Country> countryList = new ArrayList<Country>();
for (int i = 0; i < stringList.size(); i++) {
ArrayList<String> list = stringList.get(i);
Country country = new Country();
try {
//country.id = Integer.parseInt(list.get(0));
country.pays = list.get(1);
// country.age = Long.parseLong(list.get(2));
} catch (Exception e) {
Log.i("***" + TravelPharmacy.class.toString(), e.getMessage());
}
countryList.add(country);
}
return countryList;
}
#Override
public void onDestroy()
{
// adapter.imageLoader.stopThread();
lv.setAdapter(null);
super.onDestroy();
}
public OnClickListener listener=new OnClickListener()
{
#Override
public void onClick(View arg0)
{
// adapter.imageLoader.clearCache();
((BaseAdapter) adapter).notifyDataSetChanged();
}
};
CountryAdapter Class
public class CountryAdapter extends BaseAdapter {
private Activity activity;
private String[] data;
private LayoutInflater inflater=null;
// public ImageLoader imageLoader;
public CountryAdapter(Activity a, String[] d)
{
activity = a;
data=d;
inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public int getCount() {
return data.length;
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public class ViewHolder
{
public TextView text;
public ImageView image;
}
public View getView(int position, View convertView, ViewGroup parent)
{
View vi=convertView;
ViewHolder holder;
if(convertView==null)
{
vi = inflater.inflate(R.layout.singlecountry, null);
holder=new ViewHolder();
holder.text=(TextView)vi.findViewById(R.id.text);;
holder.image=(ImageView)vi.findViewById(R.id.image);
vi.setTag(holder);
}
else
holder=(ViewHolder)vi.getTag();
holder.text.setText("item "+data[position]);
holder.image.setTag(data[position]);
return vi;
}
}
ListAdapter Class
private class ListAdapter extends ArrayAdapter<Country> { // --CloneChangeRequired
private ArrayList<Country> mList; // --CloneChangeRequired
private Context mContext;
public ListAdapter(Context context, int textViewResourceId,ArrayList<Country> list) { // --CloneChangeRequired
super(context, textViewResourceId, list);
this.mList = list;
this.mContext = context;
}
public View getView(int position, View convertView, ViewGroup parent)
{
View view = convertView;
try{
if (view == null) {
LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = vi.inflate(R.layout.singlecountry, null); // --CloneChangeRequired(list_item)
}
final Country listItem = mList.get(position); // --CloneChangeRequired
if (listItem != null) {
// setting singleCountry views
// ( (TextView) view.findViewById(R.id.tv_id) ).setText( listItem.getId()+"");
( (TextView) view.findViewById(R.id.text) ).setText( listItem.getPays() );
//((ImageView)view.findViewById(R.id.image)).setImageDrawable(drawable.world);
//( (TextView) view.findViewById(R.id.tv_age) ).setText( listItem.getAge()+"" );
}}catch(Exception e){
Log.i(CountryView.ListAdapter.class.toString(), e.getMessage());
}
return view;
}
}
When you add things to the list, you can add hashmaps to the arraylist which the adapter looks at. Then you can grab the values which are name value pairs.
I think you want to get the position of the list you clicked, Its simple you can use OnItemClickListener as follows
YourList.setOnItemClickListener(new OnItemClickListener(){
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
int position=arg2;
// where position is the clicked position
} }
If you stored your data in String array pass this position say array[position] to string array you can get the Text..

Categories

Resources