A question about list - Java for Android App Development

Hi.
I am building an app that has a list. All of the clicks on list items result in one activity, like XActivity. XActivity contains a text view. I want that when I click on ListItem1 the text view shows a string forexample string1, then onClickListItem2 it shows string2, onListItemClicX it shows stringX. If it's confusing let me know.
How can I handle it ?
Thanks in advance.

torpedo mohammadi said:
Hi.
I am building an app that has a list. All of the clicks on list items result in one activity, like XActivity. XActivity contains a text view. I want that when I click on ListItem1 the text view shows a string forexample string1, then onClickListItem2 it shows string2, onListItemClicX it shows stringX. If it's confusing let me know.
How can I handle it ?
Thanks in advance.
Click to expand...
Click to collapse
I'm assuming you're using an ArrayAdapter - it would be helpful if you posted some code.
You have to setup an OnItemClickListener for your ListView. In the OnItemClick method, you will have to get the data from the adapter using the position that was clicked. Then create an intent to ActivityX and pass the clicked data.
Code:
[B]ArrayAdapter adapter = new ArrayAdapter();[/B]
listView.setClickable(true);
//Setup the on item click listener for the listview
listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//Create an intent pointing to XActivity
Intent intent = new Intent(this, XActivity.class);
//Add the clicked string as an extra
intent.putExtra("KEY_CLICKEDSTRING", adapter.getItem(position - 1));
//Start the activity
this.startActivity(intent);
}
});
In ActivityX, simply retrieve the data and set it in the textview:
Code:
@Override
public void onCreate(Bundle savedInstanceState) {
... Activity setup code
TextView textView = findViewById(R.id.yourtextview);
//Get the intent data
String strClicked = getIntent().getStringExtra("KEY_CLICKEDSTRING");
textView.setText(strClicked);
}

Thank you.
But I don't know what value does the "int position" give me ? Forexample does it give the value of "1" or .... ?
I want to know that in order to know which item was clicked and now what to do .
Can anybody help me ?
Thanks in advance.

Like previously mentioned. Post your code and we can help you out better.

not complex, First I make a new ArrayAdapter<string> add adapt it to my listView. Up to know no problem. But in the continue :
// usual codes to answer a click onItemClick(AdapterView<?> av, View v, int position, long id) {
//create a intent as Alkonic said
//My problem }
...
@My problem I want to use a set of codes and understand which item was clicked. I have 41 items and my idea is this :
// getting the text of the clicked item String title = ((TextView)v).getText().toString();
If (title=getString(R.string.theTextIHadAddedToArrayAdapterForItem1)) {
// so item 1 was clicked
//Change the text of thesecond TextView in the second activity ( wich I wrote intent for)
// rewrite the if order 41 times for 41 items
...
But this doesn't work. Can anybody help me ?
@Alconic :
I don't understand the method you wrote for retrieving intent data ( I mean
//Get the intent data String strClicked = getIntent().getStringExtra("KEY_CLICKEDSTRING");
) because the "Key_CLICKEDSTRING" is always constant and one thing. How can I cange it for 41 items ?
Thank you guys anyway.

not complex, First I make a new ArrayAdapter<string> add adapt it to my listView. Up to know no problem. But in the continue :
// usual codes to answer a click onItemClick(AdapterView<?> av, View v, int position, long id) {
//create a intent as Alkonic said
//My problem }
...
@My problem I want to use a set of codes and understand which item was clicked. I have 41 items and my idea is this :
// getting the text of the clicked item String title = ((TextView)v).getText().toString();
If (title=getString(R.string.theTextIHadAddedToArrayAdapterForItem1)) {
// so item 1 was clicked
//Change the text of thesecond TextView in the second activity ( wich I wrote intent for)
// rewrite the if order 41 times for 41 items
...
But this doesn't work. Can anybody help me ?
@Alconic :
I don't understand the method you wrote for retrieving intent data ( I mean
//Get the intent data String strClicked = getIntent().getStringExtra("KEY_CLICKEDSTRING");
) because the "Key_CLICKEDSTRING" is always constant and one thing. How can I cange it for 41 items ?
Thank you guys anyway.

You should post your onItemClick routine. But for going at it blind on our side this is what I would do:
Code:
public void onItemClick(AdapterView<?> av, View v, int pos, long id) {
//Get text from a textview that is on your listview
TextView textView2 = (TextView) v.findViewById(R.id.myTextView);
String txtMytext = textView2.getText().toString();
//Create an intent pointing to XActivity
Intent intent = new Intent(this, XActivity.class);
//Add the clicked string as an extra
intent.putExtra("KEY_CLICKEDSTRING", txtMytext);
//Start the activity
this.startActivity(intent);
}
Without your code, I don't understand what you are comparing with the if statement you posted. Use this along with @Alkonic 's code should get you in the right direction. If it doesn't, we need more code to help better.

torpedo mohammadi said:
not complex, First I make a new ArrayAdapter<string> add adapt it to my listView. Up to know no problem. But in the continue :
// usual codes to answer a click onItemClick(AdapterView<?> av, View v, int position, long id) {
//create a intent as Alkonic said
//My problem }
...
@My problem I want to use a set of codes and understand which item was clicked. I have 41 items and my idea is this :
// getting the text of the clicked item String title = ((TextView)v).getText().toString();
If (title=getString(R.string.theTextIHadAddedToArrayAdapterForItem1)) {
// so item 1 was clicked
//Change the text of thesecond TextView in the second activity ( wich I wrote intent for)
// rewrite the if order 41 times for 41 items
...
But this doesn't work. Can anybody help me ?
@Alconic :
I don't understand the method you wrote for retrieving intent data ( I mean
//Get the intent data String strClicked = getIntent().getStringExtra("KEY_CLICKEDSTRING");
) because the "Key_CLICKEDSTRING" is always constant and one thing. How can I cange it for 41 items ?
Thank you guys anyway.
Click to expand...
Click to collapse
Handling Clicks:
The int position refers to the position of the item that was clicked in the arrayadapter.
Instead of this:
Code:
String title = ((TextView)v).getText().toString();
you can use
Code:
String title = adapter.getItem(position);
That code will take the clicked position and get the clicked string from the adapter.
Intent Data
When you send data with an intent, it has two parts: the Name and Value.
The following code sets the name to a constant "Key_CLICKEDSTRING" and the Value is variable, depending on what was clicked.
Code:
intent.putExtra("KEY_CLICKEDSTRING", adapter.getItem(position));
When you want to access the VALUE, you have to provide the constant name:
Code:
String strClicked = getIntent().getStringExtra("KEY_CLICKEDSTRING");
Hope that helped!

Related

Database Stress

I'm getting a Null Pointer when I call a database method inside a listener. If the method call is outside the listener, it runs, but the data I want to pass is empty.
Help
(Note: I do comment-out one of the myDbHelper calls as req'd) LOL
Code:
/** Set Search Button Listener */
searchButton.setOnClickListener(button_listener);
searchButton = (Button) findViewById(R.id.searchButton);
myDbHelper.getRow(s); // Ok, but "s" is empty!
}
private OnClickListener button_listener = new OnClickListener() {
public void onClick(View v) {
EditText search = (EditText) findViewById(R.id.searchBox);
String s = search.getText().toString();
myDbHelper.getRow(s); // Throws Null Pointer Exception
}
};
Wow, same post on THREE different forums, 200 total views, no responses...bummer
I really don't have any idea why this is throwing the Null Pointer inside of the onClick. I've Googled 100 times for solutions and just can't find anything.
I guess I'll just gut all the code from the database helper class and put it in my main Activity; only thing I can think of doing right now LOL
Woo friggn' hoo!! I got it working.
And to the hundreds out there that may be struggling on the same thing, let me know when you've got 100 debugging hours in first and then I'll help ROFL

[Q] DatePickerDialog cancelclick

Hi there!
I have been trying to catch the Cancel click of a DatePickerDialog, because I want to do some additional stuff, when the user clicks on the Cancel Button.
I tried it like described in the second answer from esilver from this Question:
http://stackoverflow.com/questions/...erner-of-datepicker-dialog?tab=active#tab-top
But I can't get it to work like that. When do I have to call this onClick method?
Would be great if someone could help me with that!
Thanks!
cTrox said:
Hi there!
I have been trying to catch the Cancel click of a DatePickerDialog, because I want to do some additional stuff, when the user clicks on the Cancel Button.
I tried it like described in the second answer from esilver from this Question:
http://stackoverflow.com/questions/...erner-of-datepicker-dialog?tab=active#tab-top
But I can't get it to work like that. When do I have to call this onClick method?
Would be great if someone could help me with that!
Thanks!
Click to expand...
Click to collapse
the "checked" solution in that example seems wrong to me. but the second one people voted up seems correct.
You can also set the onDissmissListener which will catch if the user backs out with the back key ( recommended for user friendliness )
have a look here:
http://developer.android.com/refere...id.content.DialogInterface.OnDismissListener)
Also, since DatePickerDialog is a subclass of AlertDialog, you can set the buttons the same way:
http://developer.android.com/guide/topics/ui/dialogs.html#AlertDialog
That should get you started but feel free to post back if you get stuck again. And post the code you are using.
Also, one other thing, it might be useful to keep a private reference to your dialog in your activity class.
All those examples (in the API docs and tutorials) always show a new dialog created when "onCreateDialog(int ID)" is called by the OS on your activity and they never save any sort of reference to it. They give you just enough code to hang yourself
Anyways, while this is a perfectly normal way to do things, it doesnt give you a chance to follow what is actually happening with the dialog. It also makes it harder to reference your dialog from elsewhere in the activity.
Keeping a reference, and exploring the onPrepareDialog(int ID) method are good for learning what the OS is doing with your dialog. (IMHO)
hth
Thanks a lot for your answers. But I still can't figure out how to do it.
Here's my current Code:
Code:
private DatePickerDialog.OnDateSetListener mDateSetListener = new DatePickerDialog.OnDateSetListener() {
public void onDateSet(DatePicker datePicker, int year, int monthOfYear,
int dayOfMonth) {
mYear = year;
mMonth = monthOfYear;
mDay = dayOfMonth;
// do some more stuff...
}
};
Code:
protected Dialog onCreateDialog(int id) {
Calendar cDate = Calendar.getInstance();
int cyear = cDate.get(Calendar.YEAR);
int cmonth = cDate.get(Calendar.MONTH);
int cday = cDate.get(Calendar.DAY_OF_MONTH);
switch(id){
case DATE_DIALOG_ID:
return new DatePickerDialog(this, mDateSetListener, cyear, cmonth, cday);
}
return null;
}
With that I can just call showDialog(DATE_DIALOG_ID); and I get the dialog. Now, where do I have to implement this OnDismissListener and how?
Thanks!
there are lots of ways to do this but I broke it out into several parts so hopefully it seems more obvious what is happening.
Code:
//here's our field reference we could use later or reuse or whatever
private DatePickerDialog dateDialog = null;
protected Dialog onCreateDialog(int id)
{
//your calendar code here... just removed to save space
switch(id)
{
case DATE_DIALOG_ID:
dateDialog = new DatePickerDialog(this, mDateSetListener, cyear, cmonth, cday);
dateDialog.setButton ( DialogInterface.BUTTON_NEGATIVE, android.R.string.cancel, cancelBtnListener );
dateDialog.setOnDismissListener ( listener );
break;
}
return dateDialog;
}
//our dismiss listener
protected DialogInterface.OnDismissListener dismissListener = new OnDismissListener( )
{
@Override
public void onDismiss ( DialogInterface dialog )
{
// do your thang here
}
};
//our click listener
protected DialogInterface.OnClickListener cancelBtnListener = new OnClickListener( )
{
@Override
public void onClick ( DialogInterface dialog, int which )
{
dialog.dismiss ( );
// since we dismiss here, the next listener to get called
// is the dismiss listener. now we'll have consistent behavoir
}
};
Ah thank you very much! I was always confused, where to set the Button and the OnDismissListener.
It works perfectly like that!

[Q] How to get text from an EditText field inside a second activity?

Hello, help me please, i made a launcher activity, and a second activity (child activity). now there is an edit text fiels in my second activity, where the user can enter some text, and i dont know how to retrieve that text the user entered, and transfer it to a string ? Plz help!!
Geo B said:
Hello, help me please, i made a launcher activity, and a second activity (child activity). now there is an edit text fiels in my second activity, where the user can enter some text, and i dont know how to retrieve that text the user entered, and transfer it to a string ? Plz help!!
Click to expand...
Click to collapse
Paste some code here from your second activity, use the code tags to keep it pleasant to read.
You can use a helper class to store (set) the string and retrieve (get) it...
Sent from my LG-P350 using xda app-developers app
Geo B said:
Hello, help me please, i made a launcher activity, and a second activity (child activity). now there is an edit text fiels in my second activity, where the user can enter some text, and i dont know how to retrieve that text the user entered, and transfer it to a string ? Plz help!!
Click to expand...
Click to collapse
Hi.
2 ways poped up in my mind.
1- in your intent (if any) from 2nd activity to first put this :
Code:
public class yourActivity extends Avtivity{
EditText et;
onCreate{
et = (EditText) findViewById (R.id.your_edittext);
Button bt = etc...
bt.setOnClickListener(something I skip
onClick(...){
Intent toHome = new Intent(SecondActivity.this, FirstActivity.class);
toHome.putExtra("myEditText", et.getText().toString());
startActivity(toHome);
}
);
}
}
Then in your first one add :
Code:
Intent fromThat = getIntent();
// not sure about getIntent(), check it.
Bundle b = fromThat.getExtras();
String s = b.getString("myEditText");
Now s has exactly the value of EditText.
Second :
Create a SharedPreference containing the string of edittext and retrieve it in first activity.
You just have to use startActivityForResult to launch your second activity and override onActivityResult to get the result from started activity
Sent from my U8120 using Tapatalk 2
as said by pedja1
to start your second activity from first activity: 99 is your request code, you're free to change it to any int
Code:
Intent intent = new Intent(FirstActivity.this, FirstActivity.class);
startActivityForResult(intent, 99)
on second activity finish/closed:
Code:
Intent data = new Intent();
data.putExtra("my_text", myEditText.getText().toString());
setResult(Activity.RESULT_OK, data);
override method on first activity:
Code:
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 99 && resultCode == Activity.RESULT_OK) {
if (data != null) {
Log.i("My Apps", data.getStringExtra("my_text"));
}
}
}

Java newbabie!!! Please help !!!

PLEASE HELP ME GUYS!!! I HAVE NO CLUE WHAT I SUPPOSE TO DO THIS ASSIGNMENT :
+ Create an app with multiple activities and a ListView with data consisting of instances of a custom model class. Provide an addtional activity allow editing of the data.
+ A ListView with 8 Course Model Class
+ A seperate Activity is display on click of ClickView, which show 3 value (Title, Catalog, Capacity) and editable
-----------------------
So first I create a listview with 8 items on main activity layout, and then this my my MainActivity.class :
ListView listView = (ListView) findViewById(R.id.listView);
String[] items = { "English 156", "Match 232", "Chemistry 110FL", "Physical 051", "Piano 09","Guitar 100","Android Development 207","History 207A" };
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, items);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View v, int position, long id) {
Intent myIntent = new Intent(getApplicationContext(), FragmentClass.class);
startActivity(myIntent);
}
});
---------
I have problem that when running app, 2 activity appears at same time...
Please help me with remain codes and what can I do to fix that problems...
my app being shown like this, I want course title, catalog and capacity are shown itemonclick only.
Really???? Noone is wiliing to help me in this case???? SO SAD!!!!
ptt1404 said:
Really???? Noone is wiliing to help me in this case???? SO SAD!!!!
Click to expand...
Click to collapse
Just looks like your throwing a fragment onto the top of a listView ? Not sure what you want, it is not clear
Do you have a second fragment with transparent background?

Dynamically refresh ListView with CursorAdapter

Hi everyone,
First of all, I'd like to apologize if I'm posting this in a wrong place... This is my first post, I'm still getting familiar with this forum.
I would also like to apologize for the lengthy post.
The title, to a certain extent, reflects what my problem is, but to clarify:
I'm learning Android, so I'm making a simple SMS app for practice.
In it, I have a database which has tables for sent messages, received messages and contacts. I have 3 separate activities (which do NOT extend ListActivity) which show lists for sent messages, received messages and contacts, respectively. The lists are populated through CursorAdapter.
Let's consider the activity for contacts...
In it I have list (ListView) which displays contacts (each list element displays name and phone number). Below the list I have a "Add Contact" button. When I click the button a dialog pops up and shows the form for adding new contact. The buttons in the dialog preform all the database operations.
Similarly, when I click some item in the ListView, another dialog pops up. That dialog has buttons for "Send SMS", "Edit" and "Delete" contact. Again, the buttons do all the work with the database.
The trouble:
My trouble is... When I add a new contact, or delete one (after both operations their dialogs dismiss), the ListView is not refreshed.
In order to see the refreshed list I need to close the activity and start it again.
I googled and googled this for 3 days now, and all the answers I found say that I need to call
Code:
adapter.notifyDataSetChanged
and
Code:
adapter.changeCursor
but that doesn't do the trick.
I'll now post the relevant code with the two methods mentioned above. I placed them where i thought they should be, but this doesn't work.
So, I humbly beg someone to guide me through this ordeal.
Many thanks in advanced!
Here comes the code:
The Adapter:
Code:
public class AdapterContactListView extends CursorAdapter {
private MyDatabaseHelper mdbh;
private LayoutInflater myLayoutInflater;
public AdapterContactListView(Context context, Cursor c, int flags) {
super(context, c, flags);
mdbh = MyDatabaseHelper.getMyDatabaseHelper(context);
myLayoutInflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
@Override
public void bindView(View view, Context context, Cursor cursor) {
// TODO Auto-generated method stub
TextView fullNameTV = (TextView)view.findViewById(R.id.contactElementNameTV);
TextView phoneNumberTV = (TextView)view.findViewById(R.id.contactElementNumberTV);
String fullName = cursor.getString(cursor.getColumnIndex(mdbh.getContactFirstName()));
fullName = fullName.concat(" ");
fullName = fullName.concat(cursor.getString(cursor.getColumnIndex(mdbh.getContactLastName())));
String phoneNumber = cursor.getString(cursor.getColumnIndex(mdbh.getContactPhoneNumber()));
fullNameTV.setText(fullName);
phoneNumberTV.setText(phoneNumber);
}
@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
// TODO Auto-generated method stub
return myLayoutInflater.inflate(R.layout.contact_element, parent, false);
}
}
And the Activity:
Code:
public class ContactsActivity extends Activity {
private MyUtilities myUtilities;
private MyDatabaseHelper mdbh;
private AdapterContactListView contactsAdapter;
private ListView contactsListView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_contacts);
mdbh = MyDatabaseHelper.getMyDatabaseHelper(this);
myUtilities = new MyUtilities(this);
contactsAdapter = new AdapterContactListView(this,mdbh.getContactsCursor(),CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
contactsListView = (ListView)findViewById(R.id.contactActivityLV);
contactsListView.setAdapter(contactsAdapter);
contactsListView.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// TODO Auto-generated method stub
TextView phoneNumberTV = (TextView)view.findViewById(R.id.contactElementNumberTV);
String phoneNumber = phoneNumberTV.getText().toString();
Contact contact = mdbh.getContactFromPhoneNumber(phoneNumber);
Dialog d = myUtilities.createSelectedContactOptionsDialog(contact);
d.show();
contactsAdapter.changeCursor(mdbh.getContactsCursor());
contactsAdapter.notifyDataSetChanged();
}
});
}
public void addContact(View view) {
Dialog d = myUtilities.createAddContactDialog();
d.show();
contactsAdapter.changeCursor(mdbh.getContactsCursor());
contactsAdapter.notifyDataSetChanged();
}
}
djolec987 said:
Hi everyone,
Click to expand...
Click to collapse
Well notifyDatasetChanged only informs the adapter that the backing interface has new data... but your backing it with a cursor... so in your case it would just cause getView/bindView to be called for all current visible items, thus fire a query at the cursor. I think the cursor will cache the data so it's really a reload on the cursor data and then an adapter notify call you want... If you use loader (depending on target api version) then it should do most of this for you. As it stands if you want to do it manually make sure the cursor is a new cursor of the database that has changed.
(typed in a rush)

Categories

Resources