Using Intent with actions - android

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.

Related

Android : How to Pass the previous Activity Intent into a Listview

I have Two Activity ( Activity A, Activity B) In Activity A i have a EditText,Button and Image View And in Activity B i have a Listview and the listView View Contain CustomXml with ImageView,TextView,and Another TextView
in Activity A, i enter List Name in Edit Text (Ex : Apple) and i Chose One Image ina GridView (Ex an Apple Image )
and i pass Both the Edittext and ImageView to a new Activity Where i want to Display Those names in ListView (Apple and Apple Image) How to DO that
i want to display something like this ( i get the Grocery List and Image From the Previous Activity and i want to display in ListView( in listview i extra add the items Count TEXTVIEW)
firstActivity.Java
done.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String itemname = listname.getText().toString();
if (!TextUtils.isEmpty(listname.getText().toString())) {
startActivity(new Intent(getContext(), CheckslateHome.class).putExtra("data", itemname).putExtra("image", imageRes));
dismiss();
} else {
Toast.makeText(getContext(), "List Name not Empty ", Toast.LENGTH_SHORT).show();
}
}
});
Second Activity
public class CheckslateHome extends AppCompatActivity {
TextView listcounts;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_checkslate_home);
Bundle bundle = getIntent().getExtras();
if (bundle != null) {
String itemName= bundle.getString("data");
Int ItemImage = bundle.getString("Image");
**//How to Pass these Intents into the Custom ListView**
}
listcounts = findViewById(R.id.list_count);
ListView listView = findViewById(R.id.list1);
CustomAdpter customAdapter = new CustomAdpter();
listView.setAdapter(customAdapter);
}
public class CustomAdpter extends BaseAdapter {
private Context context;
private LayoutInflater layoutInflater;
#Override
public int getCount() {
}
#Override
public Object getItem(int i) {
return null;
}
#Override
public long getItemId(int i) {
return 0;
}
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
if (view == null) {
view = layoutInflater.inflate(R.layout.rowlayout, viewGroup, false);
}
ImageView imageicons = view.findViewById(R.id.image_list);
TextView listnames = view.findViewById(R.id.list_name);
return view;
}
}
I Highly suggest using a combination of Fragments and navigation, in this way you can easily navigate through your app and send values between fragments using safe-args plugin
but if you persist on using activity, you should use startActivityForResult to call second activity.

OnClickItem with unknown number of items Android

I have an array of objects. In my listview, I pass only the name of those objects but when someone clicks on any of them, I want a new window to pop up and to see the extra information from my items. Can I do that somehow?
This is how my list activity looks like:
public class ListItemsActivity extends ListActivity {
String[] mTestArray;
ListView listView;
private static final String TAG = "ListActivity";
#Override
public void onCreate(Bundle savedInstanceState) {
Log.d(TAG, "Trying to create the list activitye");
super.onCreate(savedInstanceState);
ArrayAdapter<String> adapter;
mTestArray = getResources().getStringArray(R.array.sections);
ArrayList<Sweet> sweets = getSweets(mTestArray);
ArrayList<String> result = getSweetsNames(mTestArray);
Log.d(TAG, mTestArray.toString());
adapter = new ArrayAdapter<String>(
this,
R.layout.activity_list_items,
result;
setListAdapter(adapter);
}
public void onListItemClick(ListView parent, View v, int position, long id) {
parent.setItemChecked(position, parent.isItemChecked(position));
Toast.makeText(this, "You have selected " + mTestArray[position],
Toast.LENGTH_SHORT).show();
}
So this is ok, it shows me a lsit of names. And when I click on them it jsut tells me on a small popup thing that I've selected it. What I want is actually to open a new window and show all the information from my items. Is that possible? How would I go around to do it?
The only way I found is to do something like this:
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
switch( position ) {
case 0: Intent newActivity = new Intent(this, i1.class);
startActivity(newActivity);
break;
case 1: Intent newActivity = new Intent(this, i2.class);
startActivity(newActivity);
break;
case 2: Intent newActivity = new Intent(this, i3.class);
startActivity(newActivity);
break;
case 3: Intent newActivity = new Intent(this, i4.class);
startActivity(newActivity);
break;
case 4: Intent newActivity = new Intent(this, i5.class);
startActivity(newActivity);
break;
}
}
But it's a bad approach for these reasons:
1) I have an unknown number of elements
2)I dont have 1000 activities for each item, I want 1 general window that would depend on some integer position.
Can I do it this way?
If you are getting position of the item from listView, then I think you can get the information about same item by the use of Adapter.
Codes that you can try:
Make a xml that your list view items would have:
This can include any types of items and items would be seen in the list view as you would want to show it. I am making an xml named list_items_view.xml and including just a text view in the listview.
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/nameInList"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="26dp"
android:padding="7dp"/>
</RelativeLayout>
Make a class that would include the items that you want to bind with each list-items:
Here I am binding each list items with it's description, price, and callories (You can change that according to your need), and make constructor and getter-setter method for each one.Name of the class is ListDetailsClass:
public class ListDetailsClass {
String price,name, description,calories;
public String getPrice() {
return price;
}
public void setPrice(String price) {
this.price = price;
}
public ListDetailsClass(String price, String name, String description, String calories) {
this.price = price;
this.name = name;
this.description = description;
this.calories = calories;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getCalories() {
return calories;
}
public void setCalories(String calories) {
this.calories = calories;
}
}
Make an adapter that could adapt the properties of the xml and the class in one single item:
Here I have made an adapter class that extends BaseAdapter and implemented it's methods according to use of my purpose.Name of the class is adapterForLV:
public class adapterForLV extends BaseAdapter {
ArrayList<ListDetailsClass> itemsInList;
Context mContext;
LayoutInflater inflater;
public Context getmContext() {
return mContext;
}
public void setmContext(Context mContext) {
this.mContext = mContext;
}
public ArrayList<ListDetailsClass> getItemsInList() {
return itemsInList;
}
public void setItemsInList(ArrayList<ListDetailsClass> itemsInList) {
this.itemsInList = itemsInList;
}
public adapterForLV(ArrayList<ListDetailsClass> itemsInList, Context mContext) {
this.itemsInList = itemsInList;
this.mContext = mContext;
}
#Override
public int getCount() {
return itemsInList.size();
}
#Override
public Object getItem(int position) {
return itemsInList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if(inflater == null){
inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
if(convertView == null){
convertView = inflater.inflate(R.layout.list_items_view,null);
}
TextView nameOfItem = (TextView) convertView.findViewById(R.id.nameInList);
ListDetailsClass items = itemsInList.get(position);
String name = items.getName();
nameOfItem.setText(items.getName());
return convertView;
}
}
Finally implement adapter in your main activity so as to include the list items with bound data:(Name of the activity is MainActivity)
ListView listView;
ArrayList<ListDetailsClass> list = new ArrayList<>();
adapterForLV customAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.lv) ;
//Adapted the list form with customAdapter
customAdapter = new adapterForLV(list,this);
//Set the listview to the customAdapter
listView.setAdapter(customAdapter);
//Made two new objects of the ListDetaisClass to add data in the listview
ListDetailsClass newData = new ListDetailsClass("3$","abc","description","543 cal");
ListDetailsClass newData2 = new ListDetailsClass("35.3$","item name","description about item","callories about it");
//Added data to the list
list.add(newData);
list.add(newData2);
//Listview item click listener implementation
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String name = customAdapter.getItemsInList().get(position).getName();
String description = customAdapter.getItemsInList().get(position).getDescription();
String price = customAdapter.getItemsInList().get(position).getPrice();
String calories = customAdapter.getItemsInList().get(position).getCalories();
//Intent to pass the data of the list item to next activity
Intent i = new Intent(getApplicationContext(),Main2Activity.class);
i.putExtra("Item_Name",name);
i.putExtra("Item_Desc",description);
i.putExtra("Item_Price",price);
i.putExtra("Item_cal",calories);
startActivity(i);
}
});
}
Getting the data to show in the form according to our use in the new activity:
Here you have to define a new xml for the new activity so that data could be shown in the form we want.
Main2Activity:
//defined textViews to show my data
TextView itemName,itemDescription,itemPrice,itemCal;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
itemName = (TextView) findViewById(R.id.ItemName);
itemDescription = (TextView) findViewById(R.id.ItemDescr);
itemCal = (TextView) findViewById(R.id.ItemCal);
itemPrice = (TextView) findViewById(R.id.ItemPrice);
//Getting data from oldActivity i.e. MainActivity
Intent i = getIntent();
//Setting data to textViews
itemName.setText("Name: "+i.getStringExtra("Item_Name"));
itemDescription.setText("Description: "+i.getStringExtra("Item_Desc"));
itemPrice.setText("Price: "+i.getStringExtra("Item_Price"));
itemCal.setText("Calories: "+i.getStringExtra("Item_cal"));
}
Screenshots after implementation:
Listview
Item details in new activity
Hope this help you!
I didn't understand well but you could use Intent for new Window For example:
public void onListItemClick(ListView parent, View v, int position, long id) {
parent.setItemChecked(position, parent.isItemChecked(position));
Intent intent=new Intent(ListItemActivity.this, newDetailActivity.class); //newDetailActivity is a Activity you need to create or can say redirect window
startActivity(intent); // This opens a window
}
Here's Official Documentation for more information Follow Documentation
You can start a common activity and pass the selected item along with the intent :
public void onListItemClick(ListView parent, View v, int position, long id) {
parent.setItemChecked(position, parent.isItemChecked(position));
//DetailsActivity is the activity which shows the extra details
Intent intent=new Intent(ListItemActivity.this, DetailsActivity.class);
//Add the item that the user clicked on, the class has to implement Parcelable or Serializable
intent.putExtra("data", sweets.getItem(position));
startActivity(intent); // This opens a window
}
In the opened activity, you can get the item from the intent and display it's contents :
//in newDetailActivity :
Sweet s = getIntent().getExtras.getParcelable("data");
The easiest way of passing data between activities is using intents.
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Intent newActivity = new Intent(this, i1.class);
newActivity.putExtra("id", postion);
newActivity.putExtra("key", value);
startActivity(newActivity);
}
In short, putExtra method takes a key and value
which can be retrieved in the destination Activity.
Bundle extras = getIntent().getExtras();
String id,key;
if(extras == null) {
id = null;
key = null;
} else {
id= extras.getString("id");
key= extras.getString("key");
}

DrawerLayout with ListView representing actions - how to call action methods on a View?

I have prepared a simple test project at GitHub for my question.
It is based on the well-known Navigation Drawer Example by Google - extended by a right-side Drawer with music-related actions in a ListView:
The actions are all defined in res/values/strings.xml:
<string-array name="music_actions">
<item>Play</item>
<item>Pause</item>
<item>Stop</item>
<item>Shuffle</item>
</string-array>
<integer-array name="music_icons">
<item>#drawable/ic_play_arrow_black_24dp</item>
<item>#drawable/ic_pause_black_24dp</item>
<item>#drawable/ic_stop_black_24dp</item>
<item>#drawable/ic_shuffle_black_24dp</item>
</integer-array>
And here is the code reading them from resources (this works well):
public class MainActivity extends AppCompatActivity {
private String[] mActions;
private int[] mIcons;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mActions = getResources().getStringArray(R.array.music_actions);
TypedArray ta = getResources().obtainTypedArray(R.array.music_icons);
mIcons = new int[ta.length()];
for (int i = 0; i < mIcons.length; i++)
mIcons[i] = ta.getResourceId(i, R.drawable.ic_menu_black_24dp);
ta.recycle();
My problem is:
From the onItemClick method in the listener for the ListView - how to call the corresponding method in the Fragment?
I only see ugly ways to do it, like here with a hardcoded switch statement:
mRightDrawer.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, mActions) {
#Override
public View getView(int position, View convertView, ViewGroup parent) {
TextView view = (TextView) super.getView(position, convertView, parent);
view.setCompoundDrawablesWithIntrinsicBounds(mIcons[position], 0, 0, 0);
return view;
}
});
mRightDrawer.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if (mActiveFragment instanceof GameFragment) {
GameFragment fragment = (GameFragment) mActiveFragment;
switch (position) {
case 0:
fragment.playMusic(); // and then this calls myView.playMusic();
break;
case 1:
fragment.pauseMusic(); // calls myView.pauseMusic();
break;
}
}
mDrawerLayout.closeDrawer(mRightDrawer);
}
});
It is ugly, because I have to track my currently active Fragment and then use wrapper methods to finally call the methods on my custom View.
How to improve this situation, should I maybe use BroadcastReceiver in my custom View?
I wish, I could define icon + title + action in my resources and then just use them.
UPDATE:
For now I am using BroadcastReceiver, but wonder if it's an apropriate solution (or maybe too heavy-weight?).
In my Fragment I call:
#Override
public void onResume() {
super.onResume();
myView.register();
}
#Override
public void onPause() {
super.onPause();
myView.unregister();
}
And in my custom View I have:
public class MyView extends View {
public final static String ACTION_PLAY = "de.afarber.myapp.play";
public final static String ACTION_PAUSE = "de.afarber.myapp.pause";
public final static String ACTION_STOP = "de.afarber.myapp.stop";
public final static String ACTION_SHUFFLE = "de.afarber.myapp.shuffle";
private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (ACTION_PLAY.equals(action))
playMusic();
else if (ACTION_PAUSE.equals(action))
pauseMusic();
else if (ACTION_STOP.equals(action))
stopMusic();
else if (ACTION_SHUFFLE.equals(action))
shuffleMusic();
}
};
public void register() {
IntentFilter filter = new IntentFilter();
filter.addAction(ACTION_PLAY);
filter.addAction(ACTION_PAUSE);
filter.addAction(ACTION_STOP);
filter.addAction(ACTION_SHUFFLE);
getContext().registerReceiver(mMessageReceiver, filter);
}
I would prefer to have some kind of "context menu" for Fragments - defining title + icon + action - which then could be used by the actions-ListView in the right Drawer...
public void unregister() {
getContext().unregisterReceiver(mMessageReceiver);
}
Broadcasts work well for my DrawerLayout based apps, but for better security and efficiency I have switched to LocalBroadcastManager -
MainActivity.java (right action drawer menu sends broadcasts):
mRightDrawer.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String action = mActions[position];
Intent intent = new Intent(action);
//intent.putExtra("message", "data");
LocalBroadcastManager.getInstance(getApplicationContext()).sendBroadcast(intent);
mDrawerLayout.closeDrawer(mRightDrawer);
}
});
PlanetFragment.java (the active fragment receives app-internal broadcasts):
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
...
mManager = LocalBroadcastManager.getInstance(getActivity());
mFilter = new IntentFilter();
mFilter.addAction(ACTION_PLAY);
mFilter.addAction(ACTION_PAUSE);
mFilter.addAction(ACTION_STOP);
mFilter.addAction(ACTION_SHUFFLE);
...
}
#Override
public void onResume() {
super.onResume();
mManager.registerReceiver(mMessageReceiver, mFilter);
}
#Override
public void onPause() {
super.onPause();
mManager.unregisterReceiver(mMessageReceiver);
}

Custom Spinner Crashing

I asked a question on here about a week or so ago about a custom spinner and got led to this guide. http://app-solut.com/blog/2011/03/using-custom-layouts-for-spinner-or-listview-entries-in-android/
I followed it and I've tried adapting it to work with my code and pull the results from a database onto the spinner but it keeps crashing.
This is the code for the spinner.
public class EditTeam extends Activity {
private final List<SpinnerEntry> spinnerContent = new LinkedList<SpinnerEntry>();
private Spinner D1Spinner;
private final ETSpinnerAdapter D1Adapter = new ETSpinnerAdapter(spinnerContent, this);
DataBaseHelper myDbHelper = new DataBaseHelper(this);
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.editteam);
myDbHelper = new DataBaseHelper(this);
myDbHelper.openDataBase();
fillSpinner();
}
private void fillSpinner() {
Cursor c = myDbHelper.FetchDrivers();
startManagingCursor(c);
// create an array to specify which fields we want to display
String[] from = new String[]{"FirstName", "LastName"};
// create an array of the display item we want to bind our data to
int[] to = new int[]{android.R.id.text1};
spinnerContent.add(new SpinnerEntry(1, null, "Test"));
//adapter.setDropDownViewResource( R.layout.spinner_entry_with_icon );
D1Spinner = (Spinner) findViewById(R.id.spr_Driver1);
D1Spinner.setAdapter((SpinnerAdapter) D1Adapter);
}
}
And I am using the two classes from that contacts example which are un-modified at the moment.
As you can see I'm trying to just manually add one item at the moment but it just crashes when you load it.
This seems to be the breaking point?
05-25 15:17:34.773: E/AndroidRuntime(241): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.f1manager.android/com.f1manager.android.EditTeam}: java.lang.ClassCastException: com.f1manager.android.ETSpinnerAdapter
Any ideas would be great.
Thanks.
ETSpinnerAdapter Code (Unmodified from the original code in the example):
public class ETSpinnerAdapter {
private final List<SpinnerEntry> content;
private final Activity activity;
public ETSpinnerAdapter(List<SpinnerEntry> content, Activity activity) {
super();
this.content = content;
this.activity = activity;
}
public int getCount() {
return content.size();
}
public SpinnerEntry getItem(int position) {
return content.get(position);
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
final LayoutInflater inflater = activity.getLayoutInflater();
final View spinnerEntry = inflater.inflate(
R.layout.spinner_entry_with_icon, null); // initialize the layout from xml
final TextView contactName = (TextView) spinnerEntry
.findViewById(R.id.spinnerEntryContactName);
final ImageView contactImage = (ImageView) spinnerEntry
.findViewById(R.id.spinnerEntryContactPhoto);
final SpinnerEntry currentEntry = content.get(position);
contactName.setText(currentEntry.getContactName());
//contactImage.setImageBitmap(currentEntry.getContactPhoto());
return spinnerEntry;
}
}
It would seem like your ETSpinnerAdapter is not a SpinnerAdapter as your are getting a class cast exceptin. Maybe you can post your code for the ETSpinnerAdapter?

2 Refreshing Issues within a ListFragment

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.

Categories

Resources