2 Refreshing Issues within a ListFragment - android

I have two issues with my ListFragment:
I want to refresh the the ListFragment once I click a button which I define in the XML File.I initially load the Data of the DataAdapter within a AsyncTask in the TitlesFragment.
I have not found a way to create the code for the button which could access the AsyncTask - and refresh my TitlesFragment
On a different note: The Listfragment updates itself everytime I change the orientation of the phone, which is absolute not the desired behaviour.
public class ClosestPlaces extends FragmentActivity {
private static KantinenListe kantinen;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_ACTION_BAR);
setContentView(R.layout.kantinen_results);
}
/**
* This is the "top-level" fragment, showing a list of items that the
* user can pick. Upon picking an item, it takes care of displaying the
* data to the user as appropriate based on the currrent UI layout.
*/
public static class TitlesFragment extends ListFragment {
boolean mDualPane;
int mCurCheckPosition = 0;
private class BuildKantinen extends AsyncTask<String, Integer, KantinenListe> {
private KantinenListe kantinen;
#Override
protected KantinenListe doInBackground(String... params) {
try{
Gson gson = new Gson();
// SOAP Test
String NAMESPACE = "http://tempuri.org/";
String METHOD_NAME = "fullSyncGPS";
String SOAP_ACTION = "http://tempuri.org/IDatenService/fullSyncGPS";
String URL = "http://webserviceURL?wsdl";
SoapObject request = new SoapObject(NAMESPACE,METHOD_NAME);
PropertyInfo pi = new PropertyInfo();
request.addProperty("radius",10);
request.addProperty("lat", "14.089201");
request.addProperty("lng", "02.136459");
request.addProperty("von", "01.09.2011");
request.addProperty("bis", "01.09.2011");
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.setOutputSoapObject(request);
HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
androidHttpTransport.call(SOAP_ACTION, envelope);
SoapPrimitive result = (SoapPrimitive)envelope.getResponse();
String resultData = result.toString();
resultData = "{\"meineKantinen\":"+resultData+"}";
this.kantinen = gson.fromJson(resultData, KantinenListe.class);
Log.i("test", "blubber" );
}
catch(Exception e)
{
e.printStackTrace();
}
return this.kantinen;
}
#Override
protected void onPostExecute(KantinenListe result) {
// populate the List with the data
Log.i("test", "postexecute" );
setListAdapter( new MenuAdapter(getActivity(), R.layout.simple_list_item_checkable_1, kantinen.getMeineKantinen()));
}
}
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
new BuildKantinen().execute("test");
if (savedInstanceState != null) {
// Restore last state for checked position.
mCurCheckPosition = savedInstanceState.getInt("curChoice", 0);
}
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt("curChoice", mCurCheckPosition);
}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
showDetails(position);
}
/**
* Helper function to show the details of a selected item, either by
* displaying a fragment in-place in the current UI, or starting a
* whole new activity in which it is displayed.
*/
void showDetails(int index) {
mCurCheckPosition = index;
// Otherwise we need to launch a new activity to display
// the dialog fragment with selected text.
Log.i("Test",Integer.toString(index));
Intent intent = new Intent();
intent.setClass(getActivity(), BeAPartner.class);
startActivity(intent);
}
}
public static class MenuAdapter extends ArrayAdapter {
private LayoutInflater mInflater;
private List<Kantine> items;
private Context context;
public MenuAdapter(Context context, int textViewResourceId, List<Kantine> items) {
super(context, textViewResourceId);
mInflater = LayoutInflater.from(context);
this.items = items;
this.context = context;
}
#Override
public int getCount() {
return items.size();
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.menu_row, parent, false);
holder = new ViewHolder();
holder.color = (TextView) convertView.findViewById(R.id.color);
holder.title = (TextView) convertView.findViewById(R.id.detail);
holder.subdetail = (TextView) convertView.findViewById(R.id.subdetail);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
// Fill in the actual story info
Kantine s = items.get(position);
s.setName( Html.fromHtml(s.getName()).toString() );
if (s.getName().length() > 35)
holder.title.setText(s.getName().substring(0, 32) + "...");
else
holder.title.setText(s.getName());
Log.i("display", "Here I am");
return convertView;
}
}
static class ViewHolder {
TextView color;
TextView title;
TextView subdetail;
}

Well to stop the activity from being restarted you can just set android:configChanges attribute on the activity that is running the fragment.
android:configChanges="orientation"
Setting that tells the system to not restart the activity on an orientation change just to change the orientation.
As for the button, set your click listener in XML by using the attribute android:onClick="myFunction". Then in your fragment define this function:
public void myFunction(View v)
{
new myAsync.execute('test');
}

When you change the phone orientation, it restarts the activity. Anything you need to be persistent you'll need to save in onSaveInstanceState(Bundle savedInstanceState) and restore with onRestoreInstanceState(Bundle savedInstanceState).
As far as updating the data when clicking a button, try calling notifyDataSetChanged() on the adapter. If that doesn't work, you'll likely just have to run your asynctask again.

Ok, I thought it's best practice to post a possible solution in a new answer - for the obvious reasons of readability:
public void reload(View v)
{
if (getSupportFragmentManager().findFragmentById(R.id.titles) != null) {
Fragment titles = (ListFragment)getSupportFragmentManager().findFragmentById(R.id.titles);
//recreate the fragment
titles.onActivityCreated(null);
}
}
Does exactly what I want ( reload the data )! However ... I think the memory footprint of this solution might be bad.

Related

Combine Activity and fragment into a class android

I want to ask,
I have 2 classes:
1. an activity class (to get data from json)
2. a fragment class (not to do something)
and I want to get data from json of activity via fragment class.
Can be combine Activity and Fragment in a class ? and how to do ?
I combined activity and fragment in a Fragment class, I have used a GridView to get data and display
JSON, execute the AsyncTask in the this Fragment
This is my code after updated 25/10:
public class FeedBackFragment extends Fragment {
ProgressDialog pDialog;
JSONParser jsonParser = new JSONParser();
MyAdapter adapter;
JSONArray manufacturers = null;
// manufacturers JSON url
private static final String URL_MANUFACTURERS ="MYURL";
public FeedBackFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.feedback_gridview_manufacturer, container, false);
GridView gridView = (GridView) view.findViewById(R.id.gridview);
gridView.setAdapter(new MyAdapter(getActivity(), manufacturersList));
gridView.setOnItemClickListener(new android.widget.AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View view, int arg2, long arg3) {
// on selecting a single manufacturer
// CategoryCarActivity will be launched to show category car inside the manufacturer
Intent i = new Intent(getActivity(), CategoryCarActivity.class);
// send manufacturer id to activity to get list of cars under that manufacturer
String manufacturer_id = ((TextView) view.findViewById(R.id.manufacturer_id)).getText().toString();
i.putExtra("manufacturer_id", manufacturer_id);
startActivity(i);
}
});
return view;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onActivityCreated(savedInstanceState);
// manufacturersList = new ArrayList<>();
new LoadAllManufacturers().execute();
}
class LoadAllManufacturers extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(getActivity());
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* After completing background task Dismiss the progress dialog
* **/
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
adapter.notifyDataSetChanged();
// dismiss the dialog after getting all manufacturers
if (pDialog.isShowing())
pDialog.dismiss();
}
}
private class MyAdapter extends BaseAdapter
{
// List<POJOManufacturer> listData = null;
LayoutInflater inflater;
Context context;
public MyAdapter(Context context, ArrayList<HashMap<String, String>> arrayList)
{
// this.context = context;
this.manufacturersList = arrayList;
inflater = LayoutInflater.from(context);
}
#Override
public int getCount() {
if (manufacturersList != null)
return manufacturersList.size();
return 0;
}
#Override
public Object getItem(int i)
{
if (manufacturersList != null)
return manufacturersList.get(i);
return null;
}
#Override
public long getItemId(int i)
{
if (manufacturersList != null)
return manufacturersList.get(i).hashCode();
return 0;
}
#Override
public View getView(int i, View convertView, ViewGroup viewGroup)
{
ViewHolder holder;
if (convertView == null)
{
convertView = inflater.inflate(R.layout.gridview_item, null);
holder = new ViewHolder();
holder.name = (TextView) convertView.findViewById(R.id.text);
holder.iconName = (ImageView) convertView.findViewById(R.id.picture);
convertView.setTag(holder);
}
else {
holder = (ViewHolder) convertView.getTag();
}
holder.name.setText(this.manufacturersList.get(i).getClass().getName());
// holder.iconName.setImageResource(this.manufacturersList.get(i).image);
return convertView;
}
public class ViewHolder
{
TextView name;
ImageView iconName;
}
}
}
I have updated and added: manufacturerList = new ArrayList<>. everything seem is better, and it happen some issues in getView() method,
I have try and it's only display with 7 empty items in gridview, and not display content and image
So How fill data from Adapter into Gridview?
constructor ManufacturerFragment in class ManufacturerFragment cannot be applied to given types;
gridView.setAdapter() takes an adapter, not a Fragment
And new ManufacturerFragment() doesn't accept an Context.
I am not really sure why you think you need to create a new ManufacturerFragment within the Fragment class you already are in. Did you mean to do gridView.setAdapter(new MyAdapter(getActivity()))?
Also, your manufacturersList needs to be loaded into that adapter, so you'll need to figure that out.
And you need to use getActivity() instead of getActivity().getApplicationContext() in most places.
Then, you should only call new LoadAllManufacturers().execute(); in either onCreateView or onActivityCreated, not both. Otherwise, you're running two AsyncTasks.
Then, onPostExecute already runs on the UI thread, no need to use getActivity().runOnUiThread(new Runnable() {...
Once you do figure out how to put that ArrayList into the Adapter class, you'll want to call adapter.notifyDataSetChanged() within onPostExecute to tell the adapter to refresh the data, thereby updating the GridView to display the data.

Changing value of textview using android spinners

I have a spinner(dynamic) which contains a list of IDs' and each ID has a product value. When I click on a particular ID, the value needs to be changed associated with that ID.
I have a listView which contains a table. The table consists of product names, product price and product information. When I change the ID, the table information(listview) changes but not the product value (this is a textview and not part of listview).
I'm passing the product value using an intent from a different class. How do I make it such that when I change an item in the spinner, the product value gets changed?
/**
* Listener for flight leg selection of spinner
*/
private OnItemSelectedListener onFlightLegSelectedListener = new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
new ShowSalesReportAsyncTask(flightLegMap.get(flightLegs.get(position)), position).executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// Do nothing
}
};
This is my onCreate where I am getting the product value.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sales_report);
salesReportListView = (ListView) findViewById(R.id.sales_report_listview);
spinnerFlightLegs = (Spinner) findViewById(R.id.flight_legs);
noTransactionsWarning = (TextView) findViewById(R.id.no_transactions_warning);
totalValueNetAmount = (TextView) findViewById(R.id.total_currency_net_value);
String salesRevenue = TOTAL_VALUE;
Bundle extras = getIntent().getExtras();
if (extras != null) {
salesRevenue = extras.getString(TOTAL_VALUE);
}
totalValueNetAmount.setText(salesRevenue);
flightLegMap = getAllFlightLegs();
if (!flightLegMap.isEmpty()) {
setFlightLegSpinner();
btnShare.setEnabled(true);
} else {
btnShare.setEnabled(false);
}
spinnerFlightLegs.setOnItemSelectedListener(onFlightLegSelectedListener);
salesReportListAdapter = new SalesReportListAdapter(this);
salesReportListView.setAdapter(salesReportListAdapter);
This is the Async task that I use to populate the view with data.
private class ShowSalesReportAsyncTask extends AsyncTask> {
private String flightLeg;
private int position;
public ShowSalesReportAsyncTask(String flightLeg, int position) {
this.flightLeg = flightLeg;
this.position = position;
}
#Override
protected List<Purchase> doInBackground(Void... params) {
List<Purchase> rows = new ArrayList<Purchase>();
PurchaseDao purchaseDao = new PurchaseDao(flightLeg, MIUtils.getShardDatabaseIndexMap());
LOG.debug(TAG + "Getting report for : {}", flightLeg);
// double netTotal = SalesUtil.calculateFlightTransactionTotal(purchaseDao, refundDao,());
return purchaseDao.getSuccessfulTransactions();
}
#Override
protected void onPostExecute(List<Purchase> result) {
super.onPostExecute(result);
if (!result.isEmpty()) {
noTransactionsWarning.setVisibility(View.GONE);
} else {
noTransactionsWarning.setVisibility(View.VISIBLE);
}
salesReportListAdapter.setRowsAndFlightDetails(result, flightLegMap.get(flightLegs.get(position)),
spinnerFlightLegs.getSelectedItem().toString());
totalValueNetAmount.setText((int) netTotal);
}
}
The item that needs to be changed is "EUR". SPINNER TABLE IMAGE
Add the code to register the listener in the onStart() method of the activity. This should work.
This should better answer your question - How to keep onItemSelected from firing off on a newly instantiated Spinner?

How to keep the checked items of the dynamically created views from a adapter on Orientation change

What i am doing:: I have a horizontal listview as shown below for which i am populating items dynamically
What is happening:: Since its a dynamically created listview onorientation change the checked items are unchecked
Question: How can i collected the checked items from the adapter and recheck the selected things on orientation change
AdpBufTypeSearch.java
public class AdpBufTypeSearch extends BaseAdapter{
private HashMap<String, String> objHashBufType;
SparseBooleanArray mBufTypeArr = new SparseBooleanArray();
private ArrayList<HashMap<String, String>> objListBufType;
Context mContext;
public AdpBufTypeSearch(Context _mContext,ArrayList<HashMap<String, String>> _objListBufType) {
mContext=_mContext;
objListBufType=_objListBufType;
}
#Override
public int getCount() {
return objListBufType.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
//LOGIC:: result will be a set on which ones are selected Ex:: 0,1,2,4
public String getSelectedBuffetType() {
//This final value(strBufTypeId) is returned when we access from class
String strBufTypeId="";
for(int i=0;i<objListBufType.size();i++) {
HashMap<String, String> objHashBufType = objListBufType.get(i);
if(objHashBufType.get("selected")=="1") {
strBufTypeId=strBufTypeId+objHashBufType.get(buf_type_mas.COLUMN_BUF_TYPE_ID);
strBufTypeId=strBufTypeId+",";
}
}
//remove the last "," in the string
if(strBufTypeId.lastIndexOf(",")>0)
strBufTypeId=strBufTypeId.substring(0, strBufTypeId.lastIndexOf(","));
return strBufTypeId;
}
/*LOGIC:: <HashMapObject(objHashBufType)> ==> their value of key(selected) is updated to "1" else key(selected) is updated to 0 */
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View retval = LayoutInflater.from(parent.getContext()).inflate(R.layout.adp_meal_type, null);
final TextView buf_type_name = (TextView) retval.findViewById(R.id.buf_type_name);
TextView buf_type_id=(TextView) retval.findViewById(R.id.buf_type_id);
ImageView buf_type_image=(ImageView) retval.findViewById(R.id.buf_type_image);
final LinearLayout imgBkgSelector=(LinearLayout) retval.findViewById(R.id.imgBkgSelector);
imgBkgSelector.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
//LOGIC:: If Selected unselect it and if it is unselected select it
if(mBufTypeArr.get((Integer) imgBkgSelector.getTag())==true){
//INNER-LOGIC:: Background not selected
mBufTypeArr.put((Integer) imgBkgSelector.getTag(), false);
objHashBufType = objListBufType.get((Integer) imgBkgSelector.getTag());
objHashBufType.put("selected", "0");
imgBkgSelector.setBackgroundColor(Color.parseColor(mContext.getString(R.color.cBlack)));
buf_type_name.setTextColor(Color.parseColor(mContext.getString(R.color.cWhite)));
}
else{
//INNER-LOGIC:: Background selected
mBufTypeArr.put((Integer) imgBkgSelector.getTag(), true);
objHashBufType = objListBufType.get((Integer) imgBkgSelector.getTag());
objHashBufType.put("selected", "1");
imgBkgSelector.setBackgroundColor(Color.parseColor(mContext.getString(R.color.cBlue)));
buf_type_name.setTextColor(Color.parseColor(mContext.getString(R.color.cWhite)));
}
}
});
imgBkgSelector.setTag(position);
//Essential code for retain the Background check part on scroll of images
if(mBufTypeArr.get(position)==true){
imgBkgSelector.setBackgroundColor(Color.parseColor(mContext.getString(R.color.cBlue)));
buf_type_name.setTextColor(Color.parseColor(mContext.getString(R.color.cWhite)));
}else{
imgBkgSelector.setBackgroundColor(Color.parseColor(mContext.getString(R.color.cBlack)));
buf_type_name.setTextColor(Color.parseColor(mContext.getString(R.color.cWhite)));
}
// Get the position
objHashBufType = objListBufType.get(position);
// Capture position and set results to the TextViews
//Capitilize the names
String capitalizedBufTypeName = WordUtils.capitalizeFully(objHashBufType.get(buf_type_mas.COLUMN_BUF_TYPE_NAME), ' ');
buf_type_name.setText(capitalizedBufTypeName);
buf_type_id.setText(objHashBufType.get(buf_type_mas.COLUMN_BUF_TYPE_ID));
Picasso.with(mContext)
.load(mContext.getString(R.string.URL_BUFFET_TYPE_IMAGE).trim()+objHashBufType.get(buf_type_mas.COLUMN_BUF_TYPE_IMAGE).trim()).resizeDimen(R.dimen.filter_image_width,R.dimen.filter_image_height).centerCrop().into(buf_type_image);
return retval;
}
}
FrgMdSearch .java
public class FrgMdSearch extends Fragment {
private HashMap<String, String> objHashBufType;
private ArrayList<HashMap<String, String>> objListBufType=null;
private AdpBufTypeSearch bufTypeAdapter;
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
//Setting the adapter for buf images<---DYNAMIC VIEWS--->
setAdapterBufImages();
}
private void setAdapterBufImages() {
bufTypeAdapter=new AdpBufTypeSearch(getActivity(),objListBufType);
hListView.setAdapter(bufTypeAdapter);
}
}
You need to save the position of the checked item when orientation change occurs in your onSaveInstanceState method also create a getter method in your AdpBufTypeSearch adapter that returns the current position of the checked item and setter method to set the checked item.
sample:
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt("position", bufTypeAdapter.getCheckedPosition()); //getCheckedPosition must return the checked item position
}
In oncreateView of the fragment
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
//Setting the adapter for buf images<---DYNAMIC VIEWS--->
setAdapterBufImages(savedInstanceState);
}
private void setAdapterBufImages(Bundle savedInstanceState) {
bufTypeAdapter=new AdpBufTypeSearch(getActivity(),objListBufType);
if(savedInstanceState != null)
{
bufTypeAdapter.setCheckedItem(savedInstanceState.getInt("position")); //will set the checked item
}
hListView.setAdapter(bufTypeAdapter);
}

How does a spinner know its value?

I have a spinner which starts a second activity on a value change. This works good.
After a return everything works fine too. But if I rotate now the mobile the OnItemSelectedListener is called! Why? The spinner should be on position -1. Which means that the callback will not be called.
How does android know which spinner item is selected? I tried to prevend to restore this information by sending the base class the a null value for the savedInstanceState.
Here is some code:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(null);
setContentView(R.layout.menu);
String db=MyDatabase.getData();
if(db == null)
db="";
Spinner spinner=(Spinner)findViewById(R.id.spinner);
MyAdapter adapter=new MyAdapter(this, db, "ID", "Name");
spinner.setAdapter(adapter);
adapter.setHint(spinner, "Please select...");
spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id2) {
int id=((SpinnerItem)parent.getAdapter().getItem(position)).getId();
Intent intent=new Intent();
intent.setClass(MainMenu.this, Other.class);
intent.putExtra("id", id);
startActivity(intent);
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
}
});
}
Here is my adapter:
public class MyAdapter extends ArrayAdapter<SpinnerItem> {
private final Context context;
private String hint;
public MyAdapter(Context context, String input, String key, String value) {
super(context, android.R.layout.simple_spinner_item, create(input, key, value));
this.context=context;
}
private static SpinnerItem[] create(String input, String key, String value) {
Vector<SpinnerItem> list=new Vector<SpinnerItem>();
// fill the list
return list.toArray(new SpinnerItem[] {});
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// show the hint
if(position == -1) {
TextView tv=new TextView(context);
tv.setTextColor(Color.DKGRAY);
tv.setText(hint);
return tv;
}
return super.getView(position, convertView, parent);
}
public void setHint(Spinner spinner, String hint) {
if(spinner.getAdapter() == null) {
throw new IllegalStateException("Set your adapter first!");
}
this.hint=hint;
try {
final Method m=AdapterView.class.getDeclaredMethod("setNextSelectedPositionInt", int.class);
m.setAccessible(true);
m.invoke(spinner, -1);
final Method n=AdapterView.class.getDeclaredMethod("setSelectedPositionInt", int.class);
n.setAccessible(true);
n.invoke(spinner, -1);
} catch(Exception e) {
throw new RuntimeException(e);
}
}
}
When you rotate your device your Activity gets restarted or recreated add this line to your AndroidManifest file in activity tag to avoid it.
android:configChanges="keyboardHidden|orientation"
When you change the orientation the onCreate() of Activity get Called.
and by default as the behaviour of the spinner the method onItemSelectedListener() get called of the spinner when ever the activity gets created.
So this is happening to you in this case
Solution for such issue is given here StackOverflow Question's Link check how he handled the issue by taking two counters checkBoxCounter and checkBoxInitialized and try to implement same in your case.

Using Intent with actions

Right. I have an action that needs to call another activity. As I understand this, I need to use Intents to do so if I want to parse values to this activity.
However, my code fails and im a little lost as to why.
My main activity:
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.main);
final ArrayList<menuItem> AMI = new ArrayList<menuItem>();
/*Menu item: String name, String menu ID*/
/*ToDo: Logic to fecth new menu structure from server*/
menuItem MI1 = new menuItem("menu item 1","1");
menuItem MI2 = new menuItem("menu item 2","2");
AMI.add(MI1);
AMI.add(MI2);
GridView gridview = (GridView) findViewById(R.id.GridView01);
gridview.setAdapter(new menuAdapter(this, AMI));
gridview.setOnItemClickListener(new OnItemClickListener()
{
public void onItemClick(AdapterView<?> parent, View v, int position, long id)
{
//Toast.makeText(Runner.this, AMI.get(position).getMenuID(), Toast.LENGTH_SHORT).show();
Intent myIntent = new Intent(v.getContext(), showMenu.class);
myIntent.putExtra("parentID", AMI.get(position).getMenuID());
startActivityForResult(myIntent, 0);
}
});
The "Toast" works just fine, however when I call the showMenu class it crashes.
The showMenu class looks as follows:
public class showMenu extends Activity{
public String menuParent = "";
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.submenu);
Bundle extras = getIntent().getExtras();
if(extras !=null)
{
menuParent = extras.getString("parentID");
}
/*ToDo: Logic to fecth new menu structure from server*/
final ArrayList<menuItem> AMI = new ArrayList<menuItem>();
menuItem MI1 = new menuItem("submenu 1","1");
menuItem MI2 = new menuItem("submenu 2","2");
AMI.add(MI1);
AMI.add(MI2);
GridView gridview = (GridView) findViewById(R.id.GridView01);
gridview.setAdapter(new subMenuAdapter(this, AMI));
}
public class subMenuAdapter extends BaseAdapter {
private ArrayList<menuItem> MIL = new ArrayList<menuItem>();
public static final int ACTIVITY_CREATE = 10;
public subMenuAdapter(Context c, ArrayList<menuItem> AMI) {
MIL = AMI;
}
public int getCount() {
return MIL.size();
}
public Object getItem(int position) {
return null;
}
public long getItemId(int position) {
return 0;
}
public View getView(int position, View convertView, ViewGroup parent) {
View v;
if (convertView == null) {
LayoutInflater li = getLayoutInflater();
v = (LinearLayout) li.inflate(R.layout.grid_item, null);
TextView tv = (TextView)v.findViewById(R.id.grid_text);
tv.setText(MIL.get(position).getMenuname());
} else {
v = convertView;
}
return v;
}
}
}
Any idea why it crashes?
I think you have to register your Intent in your AndroidManifest.xml
<activity
android:name="Package.Name.showMenu"
android:theme="#android:style/Theme.Light"></activity>
As both activities are from same application, there are some other ways as well to pass data between instead of intents. check the link below:
http://developer.android.com/resources/faq/framework.html#3
If you want to use only intents, can you please specify the error you are facing, so that someone can reply you correctly.
if you want to parse values to another activity,you must use startActivityForResult.This is called sub_activity.

Categories

Resources