I have been playing around with this code for days now if someone can help. I have 10 imagebutton in one layout i have all the button clicks in a case statement which takes care of them.What i need is to have a listview inside all the buttons when clicked.Now i have some good code from Ridcully
Listview On Multiple Button Clicks. I just can seem to get it to work
FirstActivity
package com.example.testtest;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.ImageButton;
import android.widget.ListView;
public class MainActivity extends Activity implements OnClickListener{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_of_button);
ImageButton btn1 = (ImageButton)findViewById(R.id.imageButton1);
ImageButton btn2 = (ImageButton)findViewById(R.id.imageButton2);
ImageButton btn3 = (ImageButton)findViewById(R.id.imageButton3);
ImageButton btn4 = (ImageButton)findViewById(R.id.imageButton4);
ImageButton btn5 = (ImageButton)findViewById(R.id.imageButton5);
ImageButton btn6 = (ImageButton)findViewById(R.id.imageButton6);
btn1.setOnClickListener(this);
btn2.setOnClickListener(this);
btn3.setOnClickListener(this);
btn4.setOnClickListener(this);
btn5.setOnClickListener(this);
btn6.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch(v.getId()) {
// if one of the image buttons is pressed...
case R.id.imageButton1:
case R.id.imageButton2:
case R.id.imageButton3:
case R.id.imageButton4:
case R.id.imageButton5:
case R.id.imageButton6:
Intent intent = new Intent(this, Listviewact.class);
// pass ID of pressed button to listview-activity
intent.putExtra("buttonId", v.getId());
startActivity(intent);
break;
// here you could place handling of other clicks if necessary...
}
}
private void setListAdapter(ArrayAdapter<String> arrayAdapter) {
// TODO Auto-generated method stub
}
private ListView getListView() {
// TODO Auto-generated method stub
return null;
}
}
Listviewact
import android.app.Activity;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
public class Listviewact extends Activity {
public void onCreate(Bundle b) {
super.onCreate(b);
setContentView(R.layout.listview_layout);
}
public void onResume() {
super.onResume();
int buttonId = getIntent().getIntExtra("buttonId", 0);
int buttonIdx = getButtonIdx(buttonId);
// find and set image according to buttonId
int imageId = IMAGE_IDS[buttonIdx]; // image to show for given button
ImageView imageView = (ImageView)findViewById(R.id.imageView1);
imageView.setImageResource(imageId);
// find and set listview imtes according to buttonId
String[] items = LISTVIEW_DATA[buttonIdx]; // listview items to show for given button
ListView listView = (ListView)findViewById(R.id.listView1);
ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, items);
setListAdapter(adapter);
}
private void setListAdapter(ArrayAdapter adapter) {
// TODO Auto-generated method stub
}
// a little helper to map ids to array indices
// to be able to fetch the correct image and listview data later
private final static int[] BUTTON_IDS = new int[] {
R.id.imageButton1,
R.id.imageButton2,
R.id.imageButton3,
R.id.imageButton4,
R.id.imageButton5,
R.id.imageButton6
};
// 6 images
private final static int[] IMAGE_IDS = new int[] {
R.drawable.ic_launcher,
R.drawable.ic_launcher,
R.drawable.ic_launcher,
R.drawable.ic_launcher,
R.drawable.ic_launcher,
R.drawable.ic_launcher
};
// 6 different sets of strings for the listviews
private final static String[][] LISTVIEW_DATA = new String[][] {
{"First A", "First B", "First C"},
{"Second A", "Second B", "Second C"},
{"Third A", "Third B", "Third C"},
{"Forth A", "Forth B", "Forth C"},
{"Fifth A", "Fifth B", "Fifth C"},
{"Sixth A", "Sixth B", "Sixth C"},
};
// map button id to array index
static private int getButtonIdx(int id) {
for(int i = 0; i<BUTTON_IDS.length; i++) {
if (BUTTON_IDS[i] == id) return i;
}
return 0; // should not happen
}
}
when i start it the button click works but no listview ??
You have to use listView.setListAdapter(adapter); as shown in the example code of my answer to your previous question. You're calling your own setListAdapter method which does nothing, so the listView has no adapter to get the data from.
Related
package com.example.partialheaderlistviewscrollsync;
import java.util.Dictionary;
import java.util.Hashtable;
import android.app.Activity;
import android.app.LocalActivityManager;
import android.content.ContentValues;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewTreeObserver;
import android.view.ViewTreeObserver.OnGlobalLayoutListener;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TabHost;
import android.widget.TabHost.TabSpec;
public class MainActivity extends Activity {
// here i want to use the "img" click event to open camera.. the img is placed in another //layout called header....but the click event is not working..
//is their any way to have the click eevent of the element out side of the layout... i m //inflating that layout through infalter... but the click event is unavailable
private ListView listView;
private View header;
private int headerHeight, baseScrollHeight, lowerHeaderHeight;
private LinearLayout floatingBarHeader;
private Dictionary<Integer, Integer> listViewItemHeights;
private boolean setScrollHeight, offsetSet;
private ArrayAdapter<String> adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final TabHost myTabHost = (TabHost) findViewById(R.id.tabhost);
LocalActivityManager mLocalActivityManager = new LocalActivityManager(
this, false);
mLocalActivityManager.dispatchCreate(savedInstanceState); // state will
// be bundle
// your
// activity
// state
// which you
// get in
// onCreate
myTabHost.setup(mLocalActivityManager);
myTabHost.setup();
TabSpec tab1 = myTabHost.newTabSpec("First Tab");
TabSpec tab2 = myTabHost.newTabSpec("Second Tab");
TabSpec tab3 = myTabHost.newTabSpec("Third tab");
TabSpec tab4 = myTabHost.newTabSpec("First Tab");
TabSpec tab5 = myTabHost.newTabSpec("Second Tab");
tab1.setIndicator(" Details ");
tab1.setContent(new Intent(this, TabActivity.class));
tab2.setIndicator(" Hours ");
tab2.setContent(new Intent(this, TabActivity.class));
tab3.setIndicator(" Break ");
tab3.setContent(new Intent(this, TabActivity.class));
tab4.setIndicator(" Details ");
tab4.setContent(new Intent(this, TabActivity.class));
tab5.setIndicator(" Hours ");
tab5.setContent(new Intent(this, TabActivity.class));
myTabHost.addTab(tab1);
myTabHost.addTab(tab2);
myTabHost.addTab(tab3);
myTabHost.addTab(tab4);
myTabHost.addTab(tab5);
myTabHost.setCurrentTab(0);
View head = getLayoutInflater().inflate(R.layout.header, null);
ImageView img = (ImageView) head.findViewById(R.id.imageView1);
img.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Log.e("clicked", "hurryyyyy");
String fileName = "photo-name.jpg";
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE, fileName);
values.put(MediaStore.Images.Media.DESCRIPTION,
"Image capture by camera");
Uri imageUri = getContentResolver().insert(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
startActivityForResult(intent, 4742);
}
});
setScrollHeight = false;
offsetSet = false;
listViewItemHeights = new Hashtable<Integer, Integer>();
listView = (ListView) findViewById(R.id.listView);
header = header();
listView.addHeaderView(header, null, false);
String[] strings = { "item1", "item2", "item3", "item4", "item5",
"item6", "item7", "item8", "item9", "item10", "item11",
"item4", "item5", "item6", "item7", "item8", "item9", "item10",
"item11", "item4", "item5", "item6", "item7", "item8", "item9",
"item10", "item11" };
adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, strings);
listView.setAdapter(adapter);
listView.setOverScrollMode(View.OVER_SCROLL_NEVER);
floatingBarHeader = (LinearLayout) findViewById(R.id.progBarFloat);
setOffset();
placeFloatingViewWhenReady();
ViewTreeObserver vto = listView.getViewTreeObserver();
vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
if (!setScrollHeight) {
baseScrollHeight = getScroll();
setScrollHeight = true;
}
}
});
listView.setOnScrollListener(new OnScrollListener() {
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
// TODO Auto-generated method stub
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
// TODO Auto-generated method stub
placeFloatingView();
}
});
}
if your onClick() function is placed in the main activity, the easiest way to generate it is to go to UI designer and select your imageview and fill in the onClick field, and put a name of the function, (example: onImgClick). then the IDE will generate event for u and guarantee that it will work!you just Copy the code from your
img.setOnClickListener(new OnClickListener() {
to :
public void onImgClick(View view) {// auto-generated
here you can type your onClice fubction name :
Hope you guys can help.
I have a activity which handles all the 10 image button clicks and list view intents. What i am looking to do is have 1 layout for all the list view button clicks. And in this layout call different data to it. When i started this project i had many activitys until a great stack overflow user pointed out that i can make it simpler which i did and made it a lot clear.
package com.example.testtest;
import android.app.Activity;
import android.graphics.Typeface;
import android.os.Bundle;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
public class Listviewact extends Activity {
public void onCreate(Bundle b) {
super.onCreate(b);
setContentView(R.layout.listview_layout);
Typeface tf = Typeface.createFromAsset(getAssets(),"fonts/AlexBrush-Regular-OTF.otf");
TextView tv = (TextView) findViewById(R.id.textView1);
tv.setTypeface(tf);
}
public void onResume() {
super.onResume();
int buttonId = getIntent().getIntExtra("buttonId", 0);
int buttonIdx = getButtonIdx(buttonId);
// find and set image according to buttonId
int imageId = IMAGE_IDS[buttonIdx]; // image to show for given button
ImageView imageView = (ImageView)findViewById(R.id.imageView1);
imageView.setImageResource(imageId);
// find and set listview imtes according to buttonId
String[] items = LISTVIEW_DATA[buttonIdx]; // listview items to show for given button
ListView listView = (ListView)findViewById(R.id.listView1);
ArrayAdapter adapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, items);
listView.setAdapter(adapter);
}
private void setListAdapter(ArrayAdapter adapter) {
// TODO Auto-generated method stub
}
// a little helper to map ids to array indices
// to be able to fetch the correct image and listview data later
private final static int[] BUTTON_IDS = new int[] {
R.id.imageButton1,
R.id.imageButton2,
R.id.imageButton3,
R.id.imageButton4,
R.id.imageButton5,
R.id.imageButton6
};
// 6 images
private final static int[] IMAGE_IDS = new int[] {
R.drawable.bmw,
R.drawable.ford,
R.drawable.honda,
R.drawable.toy,
R.drawable.vok2,
R.drawable.ic_launcher
};
// 6 different sets of strings for the listviews
private final static String[][] LISTVIEW_DATA = new String[][] {
{"First A", "First B", "First C", "First D","First E","First F"},
{"Second A", "Second B", "Second C"},
{"Third A", "Third B", "Third C"},
{"Forth A", "Forth B", "Forth C"},
{"Fifth A", "Fifth B", "Fifth C"},
{"Sixth A", "Sixth B", "Sixth C"},
};
// map button id to array index
static private int getButtonIdx(int id) {
for(int i = 0; i<BUTTON_IDS.length; i++) {
if (BUTTON_IDS[i] == id) return i;
}
return 0; // should not happen
}
}
It would be great if someone can show me how to make a class which i can call all the item clicks from all list views too from my code here.
package com.example.testtest;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.ImageButton;
import android.widget.ListView;
public class MainActivity extends Activity implements OnClickListener{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_of_button);
ImageButton btn1 = (ImageButton)findViewById(R.id.imageButton1);
ImageButton btn2 = (ImageButton)findViewById(R.id.imageButton2);
ImageButton btn3 = (ImageButton)findViewById(R.id.imageButton3);
ImageButton btn4 = (ImageButton)findViewById(R.id.imageButton4);
ImageButton btn5 = (ImageButton)findViewById(R.id.imageButton5);
ImageButton btn6 = (ImageButton)findViewById(R.id.imageButton6);
btn1.setOnClickListener(this);
btn2.setOnClickListener(this);
btn3.setOnClickListener(this);
btn4.setOnClickListener(this);
btn5.setOnClickListener(this);
btn6.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch(v.getId()) {
// if one of the image buttons is pressed...
case R.id.imageButton1:
case R.id.imageButton2:
case R.id.imageButton3:
case R.id.imageButton4:
case R.id.imageButton5:
case R.id.imageButton6:
Intent intent = new Intent(this, Listviewact.class);
// pass ID of pressed button to listview-activity
intent.putExtra("buttonId", v.getId());
startActivity(intent);
break;
// here you could place handling of other clicks if necessary...
}
}
private void setListAdapter(ArrayAdapter<String> arrayAdapter) {
// TODO Auto-generated method stub
}
private ListView getListView() {
// TODO Auto-generated method stub
return null;
}
}
CHEERS.
http://img40.imageshack.us/img40/705/f6h9.png
If I understand what you want, you could create a class with something like a static Arraylist to be appended each time an item is clicked. So create a class something like
public class Data class
{
static ArrayList<String> dataArray = new ArrayList<String>();;
public Data()
{
// empty constructor but could be used if needed
}
Then you can add different getters/setters or whatever you need here. When you click on an item you just call something like
Data.dataArray.add("stuff");
then retrieve items in here in your next Activity.
If that is too complicated or more than you need then you can just pass an ArrayList or whatever object you need through the Intent
Intents
Also, just a preference but since all of your Buttons do the same thing, you can do away with initializing them and setting listeners on all of them. In xml just add
`android:onClick="someFunctionName"`
to each Button then use that function name
public void someFunctionName(View v) {
switch(v.getId()) {
// if one of the image buttons is pressed...
Intent intent = new Intent(this, Listviewact.class);
// pass ID of pressed button to listview-activity
intent.putExtra("buttonId", v.getId());
startActivity(intent);
break;
// here you could place handling of other clicks if necessary...
}
There is also no need for the case statements since they all do the same thing and you don't need implements OnClickListener in the Activity declaration
You're using the ListView but not using any of it's callbacks? Here, this is my code that I use for my ListView. I'm putting activities in my array, but you could put anything. Modifying the R.layout.mfd_view allows you to put whatever you want for each list item. A Button if that's what you need. Hope this helps. I'm still learning myself.
import android.app.Activity;
import android.app.ListFragment;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;
public class MyListFragment extends ListFragment {
String fragmentBackStack;
MyMapHandler handler;
OnViewSelectedListener mListener;
/**
* An array of POJOs used to hold the info about the fragments we'll be
* swapping between This should be inserted into an array adapter of some
* sort before being passed onto ListAdapter
*/
private static final ViewDetails[] ACTIVITY_DETAILS = {
new ViewDetails(R.string.action_largeTach,
R.string.largeTach_description, LargeTachActivity.class),
new ViewDetails(R.string.action_map, R.string.map_description,
MyMapHandler.class),
new ViewDetails(R.string.action_navigation,
R.string.navigation_description, NavigationActivity.class),
new ViewDetails(R.string.action_raceMode,
R.string.raceMode_description, RaceModeActivity.class),
new ViewDetails(R.string.action_settings,
R.string.settings_description, SettingsFragment.class),
new ViewDetails(R.string.action_extraInfo,
R.string.extraInfo_description, ExtraInfoActivity.class) };
/**
* #author PyleC1
*
* A POJO that holds a class object and it's resource info
*/
public static class ViewDetails {
private final Class<? extends Activity> viewActivity;
private int titleId;
private int descriptionId;
/**
* #param titleId
* The resource ID of the string for the title
* #param descriptionId
* The resource ID of the string for the description
* #param activityClass
* The fragment's class associated with this list position
*/
ViewDetails(int titleId, int descriptionId,
Class<? extends Activity> viewActivity) {
super();
this.titleId = titleId;
this.descriptionId = descriptionId;
this.viewActivity = viewActivity;
}
public Class<? extends Activity> getViewActivity() {
return viewActivity;
}
}
/**
* #author PyleC1
*
* Extends the ArrayAdapter class to support our custom array that
* we'll insert into the ListAdapter so the user can pick between
* MFD screens at boot time.
*/
private static class CustomArrayAdapter extends ArrayAdapter<ViewDetails> {
public CustomArrayAdapter(Context context, ViewDetails[] activities) {
super(context, R.layout.mfd_view, R.id.mfdTitle, activities);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
MFDView mfdView;
if (convertView instanceof MFDView) {
mfdView = (MFDView) convertView;
} else {
mfdView = new MFDView(getContext());
}
ViewDetails details = getItem(position);
mfdView.setTitleId(details.titleId);
mfdView.setDescriptionId(details.descriptionId);
return mfdView;
}
}
public void onAttach(Activity activity) {
super.onAttach(activity);
ListAdapter listAdapter = new CustomArrayAdapter(getActivity(),
ACTIVITY_DETAILS);
setListAdapter(listAdapter);
try {
mListener = (OnViewSelectedListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnViewSelectedListener!");
}
}
#Override
public void onResume() {
super.onResume();
}
public interface OnViewSelectedListener {
public void onViewSelected(Class<? extends Activity> activityClass);
}
public void onListItemClick(ListView l, View v, int position, long id) {
ViewDetails details = (ViewDetails) getListAdapter().getItem(position);
mListener.onViewSelected(details.viewActivity);
}
}
Note that whatever activity calls this fragment must implement the OnViewSelectedListener interface. If you added this to your main activity as a subclass, this wouldn't be required. The public void onListItemClick(arg0, arg1, arg2, arg3) callback is fine. You just swap fragments or call activities from inside there.
I newbie in this field.
my application have 6 buttons with different category. when i click on one of the button it will go to another page for displaying listView for particular category in my database.
my problem is, I don't know how do switch case for this method.
Log.d("Reading", "Reading all Kategori ..");
List<UkmLocation> kategori = db.getCategoryFaculty();
for(UkmLocation k : kategori) {
results.add(k.getName());
results_id.add(k.getID());
}
adapter = new ArrayAdapter<String>(this, R.layout.list_item, R.id.textView1,results);
setListAdapter(adapter);
I want to include getCategoryHall, getCategoryFacilty,and getCategoryAdmin in this QSFacultyLocation.java. so that, i no need to create another activity merely to get getCategoryHall, getCategoryFacilty,and getCategoryAdmin (listView).Because it just using same coding.
below is my full code for:
QSFacultyLocation.java
package com.example.ukmlocationsearching;
import java.util.ArrayList;
import java.util.List;
import com.example.ukmlocationsearching.R;
import android.os.Bundle;
import android.app.Activity;
import android.app.ListActivity;
import android.content.Intent;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
public class QSFacultyLocation extends ListActivity {
//------------------------------------------------------------------
// Declaration
public static UkmLocation selectedPOI = null;
final DatabaseHandler db = new DatabaseHandler(this);
private EditText filterText = null;
ArrayAdapter<String> adapter = null;
final ArrayList<String> results = new ArrayList<String>();
final ArrayList<String> results_id = new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.qs_faculty_location);
final Intent c = new Intent(QSFacultyLocation.this, QSLocationDetail.class);
//------------------------------------------------------------------
// Link editText to layout item
filterText = (EditText) findViewById(R.id.search_box);
filterText.addTextChangedListener(filterTextWatcher);
//------------------------------------------------------------------
// Reading Poi
/*SearchKategori searchKategori = new SearchKategori();
UkmLocation selectedKategori = searchKategori.getSelectedKategori();
List<UkmLocation> locationList = null;*/
Log.d("Reading", "Reading all Kategori ..");
List<UkmLocation> kategori = db.getCategoryFaculty();
//------------------------------------------------------------------
// Determine list POI with category
for(UkmLocation k : kategori) {
results.add(k.getName());
results_id.add(k.getID());
}
//------------------------------------------------------------------
// Set list arrayAdapter to adapter
adapter = new ArrayAdapter<String>(this, R.layout.list_item, R.id.textView1,results);
setListAdapter(adapter);
//------------------------------------------------------------------
// Set ListView from ListActivity
ListView lv = getListView();
lv.setTextFilterEnabled(true);
//------------------------------------------------------------------
// Set click event from listView
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// When clicked, show a toast with the TextView text
Toast.makeText(getApplicationContext(), ((TextView) view).getText(),
Toast.LENGTH_SHORT).show();
Log.d("test", "position:" + position);
Log.d("test", "actualname:" + db.getUkmLocationByName(adapter.getItem(position)).getName());
// String poiID = results_id.get(position);
String poiID = db.getUkmLocationByName(adapter.getItem(position)).getID();
setSelectedPoi(poiID);
startActivity(c);
}
});
//------------------------------------------------------------------
// Closing db (if any)
// db.close();
}
private TextWatcher filterTextWatcher = new TextWatcher() {
public void afterTextChanged(Editable s) {
}
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
public void onTextChanged(CharSequence s, int start, int before,
int count) {
adapter.getFilter().filter(s);
}
};
#Override
protected void onDestroy() {
super.onDestroy();
filterText.removeTextChangedListener(filterTextWatcher);
}
public UkmLocation getSelectedPoi() {
return selectedPOI;
}
public void setSelectedPoi(String poiID) {
selectedPOI = db.getUkmLocation(poiID);
Log.d("test2", "_id:" + db.getUkmLocation(poiID).getID());
Log.d("test2", "Name:" + db.getUkmLocation(poiID).getName());
// Closing db
db.close();
}
}
QuickSearchMenu.java
package com.example.ukmlocationsearching;
import java.io.IOException;
import com.example.ukmlocationsearching.R;
import com.example.ukmlocationsearching.R.id;
import com.example.ukmlocationsearching.R.layout;
import com.example.ukmlocationsearching.R.menu;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.database.SQLException;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class QuickSearchMenu extends Activity implements OnClickListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
//---------------------------------------------------------------------------
// Initiate database data
initiateDb();
//---------------------------------------------------------------------------
super.onCreate(savedInstanceState);
setContentView(R.layout.quick_search_menu);
View faculty = findViewById(R.id.button2);
faculty.setOnClickListener(this);
View researchInstitute = findViewById(R.id.button1);
researchInstitute.setOnClickListener(this);
View college = findViewById(R.id.button3);
college.setOnClickListener(this);
View admin = findViewById(R.id.button4);
admin.setOnClickListener(this);
View facility = findViewById(R.id.button5);
facility.setOnClickListener(this);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.quick_search_menu, menu);
return true;
}
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.button1:
Intent b1 = new Intent(this, QSResearch.class);
startActivity(b1);
break;
case R.id.button2:
Intent b2 = new Intent(this,QSFacultyLocation.class);
startActivity(b2);
break;
/*case R.id.button3:
Intent b3 = new Intent(this,QuickSearchCollege.class);
startActivity(b3);
break;
case R.id.button4:
Intent b4 = new Intent(this,QuickSearchFaculty.class);
startActivity(b4);
break;
case R.id.button5:
Intent b5 = new Intent(this,QuickSearchCollege.class);
startActivity(b5);
break;*/
}
}
//---------------------------------------------------------------------------
// Initiate database data
public void initiateDb() {
DatabaseHandler myDbHandler = new DatabaseHandler(this);
try {
myDbHandler.createDataBase();
}
catch (IOException ioe) {
throw new Error("Unable to create database");
}
try {
myDbHandler.openDataBase();
}
catch(SQLException sqle) {
throw sqle;
}
Log.d("Initiate", "UKM Location Count: " + myDbHandler.getUkmLocationCount());
/*Log.d("Initiate", "Kategori Count: " + myDbHandler.getKategoriCount());
Log.d("Initiate", "KategoriPoi Count: " + myDbHandler.getKategoriPoiCount());*/
myDbHandler.close();
}
//------------------------------------------------------------------------------
}
please do help me solve this. thank you
First,pass a query or simply any key value such as department id or department name as an intent with each button click using
intentname.putExtra(keyname_used_to_retrieve_value,value_to_be_passed_to_next_activity);
case R.id.button1:
String query="select * from table_name where something='xyz'";
Intent b1 = new Intent(this, QSResearch.class);
b1.putExtra("myextrakey",query);
startActivity(b1);
Then, receive the intent in the onCreate method of list activity as follows,initialise database and call user defined mylist() and setuplist() functions
Intent i=getIntent();
String x=i.getStringExtra("myextrakey");//this assigns the query to string x
//open database here
mylist();//call myList function which i have defined in the following lines
setUpList();//call setUpList function which i have defined in the following lines
This is the myList function:
private void myList() {
myownlist= new ArrayList<String>();
Cursor myCursor = database.rawQuery(x,null);
myCursor.moveToFirst();
if(!myCursor.isAfterLast()) {
do {
//selects data in column 2 to be displayed on list
String listitem= myCursor.getString(2);
myownlist.add(listitem);
} while (myCursor.moveToNext());
}
myCursor.close();
}
This is the setUpList() function:
private void setUpList() {
setListAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, myownlist));
ListView lv = getListView();
}
I'm trying to use 2 spinners on my view and at the moment implementing the "OnItemSelected" method . I have a switch statement set up to tell the spinners apart, but it doesn't seem to be working for some reason.
Here is my code:
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import java.util.List;
import java.util.ArrayList;
import android.widget.AdapterView.OnItemSelectedListener;
/**
* This is the activity for feature 1 in the dashboard application.
* It displays some text and provides a way to get back to the home activity.
*
*/
public class F1Activity extends DashboardActivity implements OnItemSelectedListener
{
/**
* onCreate
*
* Called when the activity is first created.
* This is where you should do all of your normal static set up: create views, bind data to lists, etc.
* This method also provides you with a Bundle containing the activity's previously frozen state, if there was one.
*
* Always followed by onStart().
*
* #param savedInstanceState Bundle
*/
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView (R.layout.activity_f1);
setTitleFromActivityLabel (R.id.title_text);
//declaring variables
Button submitButton = (Button) findViewById(R.id.button1);
Button cancelButton = (Button) findViewById(R.id.button2);
//getting arrays from strings file
String[] regions = getResources().getStringArray(R.array.regions_array);
String[] grids = getResources().getStringArray(R.array.grids_array);
Spinner gridSpinner = (Spinner) findViewById(R.id.gridSpinner);
Spinner regionSpinner = (Spinner) findViewById(R.id.regionSpinner);
//creating adapters for both spinners
ArrayAdapter<String> dataAdapter =
new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, grids);
ArrayAdapter<String> regionAdapter =
new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, regions);
// drop down layout style with radio button type.
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
regionAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// attaching data adapters to spinners
gridSpinner.setAdapter(dataAdapter);
regionSpinner.setAdapter(regionAdapter);
gridSpinner.setOnItemSelectedListener(this);
regionSpinner.setOnItemSelectedListener(this);
submitButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view){
Intent changeAdd = new Intent();
setResult(RESULT_OK, changeAdd);
EditText nameText = (EditText) findViewById(R.id.nameTextBox);
EditText passText = (EditText) findViewById(R.id.passwordTextBox);
if(nameText.getText().toString().length() > 0 &&
passText.getText().toString().length() > 0) //TAKE CARE OF LISRVIEW/DROPDOWN
{
Toast.makeText(getApplicationContext(),
"Loading...", Toast.LENGTH_LONG).show();
// make an intent to start the virtual world activity..................like in addGridActivity/screen switch!
finish();
}
else
{
Toast.makeText(getApplicationContext(), "Sorry, you have to complete all the fields",
Toast.LENGTH_SHORT).show();
}
}
});
cancelButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view){
Intent changeAdd = new Intent();
setResult(RESULT_OK, changeAdd);
// cancelled and went back to home screen
finish();
}
});
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int pos, long arg3) {
// to handle the selection of the gridSpinner or the regionSpinner
int id = parent.getId();
switch(id)
{
case R.id.gridSpinner:
Toast.makeText(parent.getContext(), "you selected" +
parent.getItemAtPosition(pos).toString() + "from the grid spinner", Toast.LENGTH_LONG);
break;
case R.id.regionSpinner:
Toast.makeText(parent.getContext(), "you selected" +
parent.getItemAtPosition(pos).toString() + "from the region spinner", Toast.LENGTH_LONG);
break;
default:
break;
}
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
} // end class
<code>
Your switch is working fine. The reason it seems to be not working is because your code to display the Toast is missing the show() calls.
Instead of:
Toast.makeText(parent.getContext(), ..., Toast.LENGTH_LONG);
do this:
Toast.makeText(parent.getContext(), ..., Toast.LENGTH_LONG).show();
I make the same mistake all the time myself :)
Replace int id = parent.getId(); to int id = view.getId();
You need to switch based on the id of the view not the view adapter. Try changing int id = parent.getId(); to int id = view.getId();.
Something is wrong with my code. In the application, when I "add item", it doesn't show anything, and if I am clicking somewhere around the Android application, then "item" sometimes comes.
Can somebody help me?
package com.example.proov;
import java.util.ArrayList;
import com.example.proov.R;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
public class proovin extends Activity {
private ListView LView;
ArrayList <String>ar = new ArrayList<String>();
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
LView = (ListView) findViewById(R.id.ListView01);
// Set option as Multiple Choice. So that user can able to select more the one option
LView.setAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_multiple_choice, ar));
LView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
Button b = (Button) findViewById(R.id.add_item);
final EditText d = (EditText) findViewById(R.id.title);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ar.add(d.getText().toString());
}
});
}
}
Use below code instead of your code.
public class proovin extends Activity {
private ListView LView;
ArrayList <String>ar = new ArrayList<String>();
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
LView = (ListView) findViewById(R.id.ListView01);
// Set option as Multiple Choice. So that user can able to select more
// the one option
final ArrayAdapter<String> adpt=new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_multiple_choice, ar);
LView.setAdapter(adpt);
LView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
Button b = (Button) findViewById(R.id.add_item);
final EditText d = (EditText) findViewById(R.id.title);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ar.add(d.getText().toString());
adpt.setNotifyOnChange(true);
LView.setAdapter(adpt);
}
});
}
}
The item is likely getting added to the ArrayList, but that is different from getting added to the ListView. You need to tell the ListView that you updated the data model so that it knows to look. See ArrayAdapter.notifyDatasetChanged()
you can use this add string to list on a button click
final String a[]={"hello","world"};
final ArrayAdapter<String> at=new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_1,a);
final ListView sp=(ListView)findViewById(R.id.listView1);
sp.setAdapter(at);
final EditText et=(EditText)findViewById(R.id.editText1);
Button b=(Button)findViewById(R.id.button1);
b.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
// TODO Auto-generated method stub
int k=sp.getCount();
String a1[]=new String[k+1];
for(int i=0;i<k;i++)
a1[i]=sp.getItemAtPosition(i).toString();
a1[k]=et.getText().toString();
ArrayAdapter<String> ats=new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_1,a1);
sp.setAdapter(ats);
}
});