masterdetail flow with images - android

I'm very new to developing android apps and my programing experience is also lacking a bit.
But I hope some of you can still help me.
Let's get to my problem.
I created a list with images. If I click on one item, I get a Toast saying "you clicked xy". But I want to include a master detail flow. I looked up the internet for some help but all I could find were tutorials on how to integrate a website...
This is my onCreate method, I hope someone could help me.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
CustomList adapter = new
CustomList(MainActivity.this, web, imageId);
list=(ListView)findViewById(R.id.list);
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(MainActivity.this, "You Clicked at " + web[+position], Toast.LENGTH_SHORT).show();
}
});

There are two approaches - using fragments or using activities. Fragments are the preferred way, but harder. Seeing as you are new to android you should probably learn how to do it with activities first. Before you can do that you need to learn about intents.
What you need to do is use the intent to start the detail activity when your item is selected.
Master activity
protected void onCreate(Bundle savedInstanceState) {
...
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(MainActivity.this, "You Clicked at " + web[+position], Toast.LENGTH_SHORT).show();
Intent intent = new Intent(MainActivity.this, DetailActivity.class);
//you should make the key string a constant in your code
//im assuming for this example your item is something like a drawable resource id
intent.putExtra("ImageId", getItem(position));
startActivity(intent);
}
});
Detail activity
protected void onCreate(Bundle savedInstanceState) {
...
ImageView iv = (ImageView) findViewById(...);
int imageRes = getIntent().getIntExtra("ImageId", -1);
if (imgRes > 0){
iv.setImageResource(imageRes);
}
}

Related

Android dependent spinners - onItemSelected does not fire

I tryed to create two dependent spinners. I know there is more than enough of this type of question, but nothing fixed my problem. It seems onItemSelected does not fire at all. I want the second (townships_spinner) change when first spinner (divisions_spinner) is selected or changed. Let's say I have states and cities, when I select the state a want to display only cities from given state. Spinners are created dynamicaly.
That's my code:
public class RegistrationActivity extends Activity implements AdapterView.OnItemSelectedListener {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
...
createLayout();
}
public void createLayout(){
division_spinner = new Spinner(this);
ArrayAdapter division_adapter = new ArrayAdapter(this,R.layout.spinner,divisions.getList());
divisions_id = viewer.getValueByKey(viewer_form.getViewers_form_viewers_inputname());
division_spinner.setAdapter(division_adapter);
division_spinner.setSelection(divisions.getIndex(divisions_id));
division_spinner.setOnItemSelectedListener(this);
township_spinner = new Spinner(this);
ArrayAdapter township_adapter = new ArrayAdapter(this,R.layout.spinner,townships_map.get(divisions_id));
if (divisions_id == null) {
township_spinner.setEnabled(false);
}
String value = viewer.getValueByKey(viewer_form.getViewers_form_viewers_inputname());
township_spinner.setSelection(townships.getIndex(value, divisions_id));
}
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,long arg3) {
Toast.makeText(RegistrationActivity.this, "Yes",Toast.LENGTH_LONG);
if(arg0.equals(division_spinner)) {
Toast.makeText(RegistrationActivity.this, "Yes - You got it!",Toast.LENGTH_LONG);
township_spinner.setEnabled(true);
ArrayAdapter township_adapter = new ArrayAdapter(this, R.layout.spinner, townships_map.get(((Division)division_spinner.getSelectedItem()).getDivisions_id().toString()));
township_spinner.setAdapter(township_adapter);
}
}
public void onNothingSelected(AdapterView<?> arg0) {
}
}
But "Yes" even "Yes - you got it!" toast does not appear.
I guess I miss something stupid, but I cant find it.
you're implementing AdapterView.onItemSelected.
...Just try this instead
Spinner.setOnItemSelectedListener(new OnItemSelectedListener()
{
#Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id)
{
Toast.makeText(topThis, "selected", Toast.LENGTH_LONG).show();
//Call other spinner here to update.
}
#Override
public void onNothingSelected(AdapterView<?> parentView)
{
Toast.makeText(topThis, "nothing selected", Toast.LENGTH_LONG).show();
}
});
Edit: as Prasad says. If you don't have setContentView(View); your activity won't have an xml to inflate, so your views will never get created into anything.
I made a series of mistakes that led to the fact that it did not work as I expected.
First: I forgot to call **show()** on Toast.makeText()
Second: I make a huge mistake when creating ArrayList. I filled ArrayList with data, then I put the list to HashMap and after that I called ArrayList.**clear()**. Which led to override the HashMap values, and that was why it seemed, the spinner was not changing at all...
Well... I feel quite silly ...

Android onItemLongClick adds position to the arrayList in different activity

I have got two activities.
My goal is: After longClick on any ListView position in activity 2, I want some String to be added to ListView in activity 1. From activity 2 I'm going back to activity 1 by pressing back button. Each ListView has got different adapter.
I tried with Bundle (put extra), but it makes app crash.
Fragment of code from activity 1:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.start_layout);
mDrawerList = (ListView)findViewById(R.id.navList);
mDrawerLayout = (DrawerLayout)findViewById(R.id.drawer_layout);
mActivityTitle = getTitle().toString();
addDrawerItems();
setupDrawer();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
}
private void addDrawerItems() { //It adds text ect. to listView - It works so I cut out the rest of code
ar.add("anything");
ar.add(lv.try);
mAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, ar);
mDrawerList.setAdapter(mAdapter);
mDrawerList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
});
}
Simply adding like ar.add("anything"); works. The lv.try contains by default text "First text". I tried to update this variable in activity 2 onItemLongClick fragment of code:
mListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
//What to type here?
return false;
}
});
Putting simply try = "Second text"; will not update my try variable. I tried also with Bundle (extras) but without success. Any ideas?
I don't know if I understood the question. Anyway, have you tried to override onBackPressed?
In the second activity you create a boolean variabile and inizialize it as false, then change its value when you perform a long click:
mListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
longClick = true;
return false;
}
});
Remember, longClick has to be a class variable!
Outside onCreate:
#Override
public void onBackPressed() {
Intent intent = new Intent(SecondActivityName.this, FirstActivity.class);
intent.putExtra("longClick", longClick);
finish();
startActivity(setIntent);
}
And in the first Activity:
Intent intent = getIntent();
if (intent.getBooleanExtra("longClick", false)) {
addDrawerItems();
}
What does add position mean ?
In my opinion add position means add one element to a structure (array, list, etc).
So basically what I mean is that you can have an array in your CustomApplicatioClass or even a Static array(someone probably would not agree with me) and onItemLongClick() add the element you want in the structure.
Then when you load the Activity with the ListView you can do your ListView stuff using the updated structure
hope it helps

same webview for different activities

i have many buttons in main activity that each button link to another activity that contain listview that each item in listview link one html file that is in asset folder.
in my codes i'm using one webview activity for each activity.
how can i use one same webview activity for all activity.
i have eight different activities with different html files.
and i try to use one webview for others and always result is one html for all address.
one of my activities:
public class Dia_Page extends ListActivity {
public ListView lv;
public String number_of_keys;
public String[] values = new String[] {"dia 1",
"dia 2","dia 3"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dia__page);
setListAdapter(new MyAdapter(this,android.R.layout.simple_list_item_1,R.id.textView1,values));
lv = getListView();
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, final View view,
int position, long id) {
Intent myIntent = new Intent(Dia_Page.this,Dia_sec.class);
myIntent.putExtra("key",position);
startActivity(myIntent);
}
});
}
my webview activity:
web2.setWebViewClient(new myWebClient());
web2.getSettings().setJavaScriptEnabled(true);
int pos = getIntent().getIntExtra("key", 0);
if (pos == 0) {
web2.loadUrl("file:///android_asset/dia/diaone.html");
} else if (pos == 1) {
web2.loadUrl("file:///android_asset/dia/diatwo.html");
} else if (pos == 2) {
web2.loadUrl("file:///android_asset/dia/diathree.html");
}
how can i use same webview for show all activities html that are in different activities.
I'm posting this answer to my question to those friends that have a problem like mine.
in each activity that contains listview i put this codes:
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, final View view,
int position, long id) {
Intent intent = new Intent(getApplicationContext(), Dia_sec.class);
switch(position){
case 0 :
intent.setData(Uri.parse("file:///android_asset/can/canone.html"));
break;
case 1 :
intent.setData(Uri.parse("file:///android_asset/can/cantwo.html"));
break;
case 2 :
intent.setData(Uri.parse("file:///android_asset/can/canthree.html"));
break;
// etc
}
startActivity(intent);
and in my webview "dia_sec" i add this code:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dia_sec);
web2.loadUrl(getIntent().getDataString());
I had about 8 different activities that contains their own listview with different html files.
and now i put code in activity and link them to my webview page.
problem solved and now i have one webview that i use it to show all html files from different source and different listviews.
Thanks alot every body to try help me in this way
Try changing the code in webview activity like this.
`
String pos="";
in = getIntent();
web2.setWebViewClient(new myWebClient());
web2.getSettings().setJavaScriptEnabled(true);
pos= in.getStringExtra("key");
if (pos.equals("0")) {
web2.loadUrl("file:///android_asset/dia/diaone.html");
} else if (pos.equals("1")) {
web2.loadUrl("file:///android_asset/dia/diatwo.html");
} else if (pos.equals("2")) {
web2.loadUrl("file:///android_asset/dia/diathree.html");
}`

Android - Change View when alertdialog button is clicked

I have a listview with a couple of strings in at the moment. when a user selects one it brings up an alertdialog box which gives the option to book(this is going to be a taxi app) or cancel. What i cant work out is how to get it so that when the user clicks "Book" it takes the information they've selected and loads up a new view with more contact information.
My Code is currently this -
public class ListTaxi extends ListActivity{
/** Called when the activity is first created. */
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String[] taxi = getResources().getStringArray(R.array.taxi_array);
setListAdapter(new ArrayAdapter<String>(this, R.layout.listtaxi, taxi));
final ListView lv = getListView();
lv.setTextFilterEnabled(true);
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> a, View v, int position, long id)
{
AlertDialog.Builder adb=new AlertDialog.Builder(ListTaxi.this);
adb.setTitle("Taxi Booking");
adb.setMessage("You have chosen = "+lv.getItemAtPosition(position));
adb.setPositiveButton("Book", null);
adb.setNegativeButton("Cancel", null);
adb.show();
}
});
Any help or pointers with this would be immensely appreciated as its the last bit i need to get working before its almost done.
Thanks everyone
Oli
You need to put an onClickListener onto your positive button, which will launch the new activity and pass the data to it. Your code would become something like:
public class ListTaxi extends ListActivity{ /** Called when the activity is first created. */ public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final String[] taxi = getResources().getStringArray(R.array.taxi_array);
setListAdapter(new ArrayAdapter<String>(this, R.layout.listtaxi, taxi));
final ListView lv = getListView();
lv.setTextFilterEnabled(true);
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> a, View v, int position, long id)
{
final int selectedPosition = position;
AlertDialog.Builder adb=new AlertDialog.Builder(ListTaxi.this);
adb.setTitle("Taxi Booking");
adb.setMessage("You have chosen = "+lv.getItemAtPosition(position));
adb.setPositiveButton("Book", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Intent intent = new Intent(getApplicationContext(), NextActivity.class);
intent.putExtra("booking", taxi[selectedPosition];
startActivity(intent);
}
});
adb.setNegativeButton("Cancel", null);
adb.show();
}
});
In your target activity, have something like this:
Intent intent = getIntent();
String booking = "";
if (intent != null) {
Bundle extras = intent.getExtras();
if (extras != null) {
booking = extras.getString("booking");
}
}
One way could be to get your item out of your taxi list:
taxi.get(position);
and pass it through an intent to a next activity:
Intent intent = new Intent(this, YOUR_NEXT_ACTIVITY.class);
intent.putExtra("booking", taxi.get(position);
on the next activity you can get it with:
intent = getIntent();
inten.getExtra("booking");
// could be (not sure): inten.getExtraString("booking");
You can use this method from alertDialog class
public void setButton (int whichButton, CharSequence text, DialogInterface.OnClickListener listener)
Refer link
http://developer.android.com/reference/android/app/AlertDialog.html
depending on positive response, say book is positive response then start another activity which shows details contact info, pass the select item from list as Bundle or extra with intent while starting another activity.

Android custom listview, setOnItemSelectedListener not working

I'm just beginning Android development, and I'm working to get a Custom listview with a checkbox working. I've created a base class that extends Activity, Created an Adapter and overrode the getView() method to add the checkbox to the listview. I'm assuming I need to do this because I need something equivalent to didSelectRowIndexAtPath from Obj C to update my model. Please let me know if there's an alternate way of doing this too!
Now in my base class, I have the following code -
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout);
setContentView(R.layout.facilityscreen);
/* Static Data source */
facilityModel = new FacilityDataModel[2];
facilityModel[0] = new FacilityDataModel();
facilityModel[1] = new FacilityDataModel();
facilityModel[0].setFacilityName("Test 1");
facilityModel[0].setFacilityID("Facid0001");
facilityModel[0].setChecked(false);
facilityModel[1].setFacilityName("Test 2");
facilityModel[1].setFacilityID("Facid0002");
facilityModel[1].setChecked(true);
facilityListView = (ListView) findViewById(R.id.facilityListView);
FacilityScreenAdapter adapter = new FacilityScreenAdapter(this, facilityModel);
facilityListView.setAdapter(adapter);
myPatBtn = (Button) findViewById(R.id.myPatBtn);
myPatBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
int i=0;
i++;
}});
facilityListView.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
int i=0;
i++;
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
}
My problem now is the setOnItemSelectedListener isn't getting called at all. Been struggling with this for a couple of hours now, and I can't figure out why it wouldn't get called at all.
Any help is much appreciated!
Thanks,
Teja.
I know this is an outdated answer but I'm going to write it just in case some other fellow who has the same "problem" bumps onto this page :
The solution to the above problem which is not a problem but just a misunderstanding is that the ListView.onItemSelected() event is fired up, upon :
1) Navigating through the emulators-cross handles or
2) as far-as my HTC-Hero is concerned, the rolling-action on the white little roller-ball.
You don't have to extend your activity explicitly to a ListActivity.
Here's my tiny little code which retrieves a phone number from
a TextView control, inside a listview item.
When the user either touches the list item or scrolls through the list with
the little roller-ball the below Events, fire up and MakeACall() method is called :
myList.setOnItemClickListener(new OnItemClickListener()
{
public void onItemClick(AdapterView<?> parent, View view, int position, long i)
{
TextView myPhone = (TextView)view.findViewById(R.id.txtphone);
MakeACall(myPhone.getText().toString());
}
});
myList.setOnItemSelectedListener(new OnItemSelectedListener()
{
public void onItemSelected(AdapterView<?> parent, View view, int position, long i)
{
TextView myPhone = (TextView)view.findViewById(R.id.txtphone);
MakeACall(myPhone.getText().toString());
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
I hope that was helpful... :)
There exists already the possibility to have a ListView with checkboxes.
public class List11 extends ListActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setListAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_multiple_choice, GENRES));
final ListView listView = getListView();
listView.setItemsCanFocus(false);
listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
}
private static final String[] GENRES = new String[] {
"Action", "Adventure", "Animation", "Children", "Comedy", "Documentary", "Drama",
"Foreign", "History", "Independent", "Romance", "Sci-Fi", "Television", "Thriller"
};
}
I've taken this from the APIDemos 'cause it was the simplest. You can then get the selected items by using:
long[] selectedIds = getListView().getCheckItemIds();
What you may also be interested in is the CheckedTextView which is used internally in the list.
To the part of the onListItemClick problem
Try to extend from ListActivity rather than Activity. Then override the onListItemClick. That should work.
use
setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
// here you code
}
})
instead of setOnItemSelectedListener
As setOnItemSelectedListener is called when item is being selected not clicked so to get clicked item you must use setOnItemClickListener this will work
You should set all focusable items in custom list layout to false:
android:focusable="false"
also I think you should not use attributes like android:clickable="true" for them.
The lack of the item selected listener getting called is by design and is based on which mode the device is in. In touch mode, there is no focus and no selection. Your UI should use widgets that differentiate between touch for selection versus touch for scrolling. Radio buttons, for example, are good when there is a single selection choice.

Categories

Resources