Actionbar mit tabs und fragmenten

  • 0 Antworten
  • Letztes Antwortdatum
D

Didi95

Neues Mitglied
0
Hi,

ich arbeite im Moment an einer App für die Schule. Im Moment bin ich dabei mit Tabs den Vertretungsplan einmal für heute und einmal für morgen anzeigen zu lassen. Ich hab mich jetzt mal durch diverse Tutorials gearbeitet und hab das Grundgerüst jetzt auch fertig. Allerdings habe ich jetzt ein paar Fragen:

Kann man in eine Fragmentklasse eine Asyncabfrage reinpacken?
Code:
@SuppressLint("NewApi")
public class Fragments1 extends ListFragment {


	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
		Bundle savedInstanceState) {
		// Loading value class in Background Thread
		SharedPreferences Klassen = getActivity().getSharedPreferences("shared_string1", 0);  
		String dataReturned = Klassen.getString("KEY_ART", null);
		new LoadAllProducts().execute(dataReturned);
		// Get listview
		ListView lv = getListView();
		return inflater.inflate(R.layout.frag1, container, false);
	}

	private ProgressDialog pDialog;
	// Creating JSON Parser object
	

	// url to get substition plan
	private static String url_all_products = "http://yourcloud.eichsfeld-gymnasium.de/app_neu/get_all_products.php?id=23";

	// JSON Node names
	private static final String TAG_SUCCESS = "success";
	private static final String TAG_ERROR = "error";
	private static final String TAG_PRODUCTS = "substitionplan";
	private static final String TAG_DATUM = "Datum";
	private static final String TAG_Stunde = "Stunde";
	private static final String TAG_Klassen = "Klassen";
	private static final String TAG_Vertreter = "Vertreter";
	private static final String TAG_Fach = "Fach";
	private static final String TAG_Raum = "Raum";
	private static final String TAG_Art = "Art";
	private static final String TAG_Lehrer_alt = "Lehrer_alt";
	private static final String TAG_le_nach = "le_nach";
	private static final String TAG_Vertretungstext = "Vertretungstext";
	private static final String KEY_Returned = "dataReturned";


	


	class LoadAllProducts extends AsyncTask<String, String, String> {
		private MenuItem menuItem;
		// products JSONArray
		private JSONArray Vertretung;	
		private ArrayList<HashMap<String, String>> substitionList;
		private JSONParser jParser;

		/**
		 * Before starting background thread Show Progress Dialog
		 * */
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			
			// Hashmap for ListView
			substitionList= new ArrayList<HashMap<String, String>>();
		}

		/**
		 * getting All products from url
		 * */
		@Override
		protected String doInBackground(String... args) {
			jParser = new JSONParser();
			// Building Parameters
			List<NameValuePair> params = new ArrayList<NameValuePair>();
			params.add(new BasicNameValuePair(KEY_Returned, args[0]));
			// getting JSON string from URL
			JSONObject json = jParser.makeHttpRequest(url_all_products, "POST",
					params);

			// Check your log cat for JSON reponse
			Log.d("Alle Vertretungen: ", json.toString());

			try {
				// Checking for SUCCESS TAG
				int success = json.getInt(TAG_SUCCESS);

				if (success == 1) {
					// Vertretung found
					// Getting Array of Vertretung
					Vertretung = json.getJSONArray(TAG_PRODUCTS);

					// looping through All Products
					for (int i = 0; i < Vertretung.length(); i++) {
						JSONObject c = Vertretung.getJSONObject(i);

						// Storing each json item in variable
						String Datum = c.getString(TAG_DATUM);
						String Klasse = c.getString(TAG_Klassen);
						String Stunde = c.getString(TAG_Stunde);
						String Vertreter = c.getString(TAG_Vertreter);
						String Fach = c.getString(TAG_Fach);
						String Raum = c.getString(TAG_Raum);
						String Art = c.getString(TAG_Art);
						String Lehrer_alt = c.getString(TAG_Lehrer_alt);
						String le_nach = c.getString(TAG_le_nach);
						String Vertretungstext = c
								.getString(TAG_Vertretungstext);

						// creating new HashMap
						HashMap<String, String> map = new HashMap<String, String>();

						// adding each child node to HashMap key => value
						map.put(TAG_DATUM, Datum);
						map.put(TAG_Klassen, Klasse);
						map.put(TAG_Stunde, Stunde);
						map.put(TAG_Vertreter, Vertreter);
						map.put(TAG_Fach, Fach);
						map.put(TAG_Raum, Raum);
						map.put(TAG_Art, Art);
						map.put(TAG_Lehrer_alt, Lehrer_alt);
						map.put(TAG_le_nach, le_nach);
						map.put(TAG_Vertretungstext, Vertretungstext);

						// adding HashList to ArrayList
						substitionList.add(map);
					}

				} else if (success == 0) {

				}
			} catch (JSONException e) {
				e.printStackTrace();
			}

			return null;
		}

		@Override
		protected void onPostExecute(String file_url) {
			// dismiss the dialog after getting substition plan
			pDialog.dismiss();
			// updating UI from Background Thread
			getActivity().runOnUiThread(new Runnable() {
				@Override
				public void run() {
					/**
					 * Updating parsed JSON data into ListView
					 * */
					ListAdapter adapter = new SimpleAdapter(
							getActivity(), substitionList,
							R.layout.list_item2, new String[] { TAG_Klassen,
								TAG_Stunde, TAG_Vertreter, TAG_Fach,
								TAG_Raum, TAG_Art, TAG_Lehrer_alt,
								TAG_le_nach, TAG_Vertretungstext },
								new int[] { R.id.Klassen, R.id.Stunde,
								R.id.Vertreter, R.id.Fach, R.id.Raum,
								R.id.Art, R.id.Lehrer_alt,
								R.id.Vertretungstext });
					// updating listview
					setListAdapter(adapter);
				}
			});
		}
	}
}

2. Wie verfahre ich mit der Anzeige? Eigentlich wird bislang ja noch meine Hauptactivity geladen. Die fragmentklassen werden nicht angezeigt, nur die tabs. Man muss ja jetzt irgendwie die View ersetzen können, und die fragment activity ja noch irgendwo (in der xml oder so) als fragment kennzeichnen muss.

Code:
public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.all_products);
		zurück = (ImageView) findViewById(R.id.imageView1);
		error = (TextView) findViewById(R.id.Error);
		Statistik = (WebView) findViewById(R.id.webView1);
		spinner = (Spinner) findViewById(R.id.spinner1);

		ActionBar ab = getActionBar();
		ab.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

		Tab tab = ab
				.newTab()
				.setText(R.string.frag1)
				.setTabListener(
						new MyTabListener(this, Fragments1.class.getName()));
		ab.addTab(tab);

		Tab tab2 = ab
				.newTab()
				.setText(R.string.frag1)
				.setTabListener(
						new MyTabListener(this, Fragments2.class.getName()));
		ab.addTab(tab2);

		InternetDetector ID = new InternetDetector(getApplicationContext());
		Boolean checkInternet = ID.isConnectingToInternet();

		if (checkInternet == true) {
			Statistik
			.loadUrl("http://plus.eichsfeld-gymnasium.de/app/track.php");

			zurück.setOnClickListener(new View.OnClickListener() {

				@Override
				public void onClick(View view) {
					// go back
					finish();

				}
			});

			
			

		} else {

			zurück.setOnClickListener(new View.OnClickListener() {

				@Override
				public void onClick(View view) {
					// go back
					finish();

				}
			});
			// Internet connection is not present
			// Ask user to connect to Internet
			showAlertDialog(AlleVertretungen.this, "Keine Internetverbindung",
					"Verbinde dich bitte mit dem Internet!", false);
		}

	}

	// Option Menu, AppBar,MenuButton
	@Override
	@SuppressLint("NewApi")
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.optionmenu, menu);

		final String[] actions = new String[] { "Heute", "Morgen" };

		ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
				android.R.layout.simple_spinner_dropdown_item, actions);

		ActionBar actionBar = getActionBar();
		actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_LIST);

		ActionBar.OnNavigationListener navigationListener = new OnNavigationListener() {

			@Override
			public boolean onNavigationItemSelected(int itemPosition,
					long itemId) {
				switch (itemPosition) {
				case 0: // Heute;
					break;
				case 1: // Morgen;
					break;
				}
				return false;
			}
		};

		actionBar.setListNavigationCallbacks(adapter, navigationListener);
		return true;
	}

	@SuppressLint("NewApi")
	@TargetApi(Build.VERSION_CODES.HONEYCOMB)
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.aktualisieren:
			menuItem = item;
			menuItem.setActionView(R.layout.actionview);
			menuItem.expandActionView();
			SharedPreferences Klassen = getSharedPreferences("shared_string1",
					0);
			String dataReturned = Klassen.getString("KEY_ART", null);
			
			break;
		default:
			break;

		}
		return true;
	}

	
	

	/**
	 * Function to display simple Alert Dialog
	 * 
	 * @param context
	 *            - application context
	 * @param title
	 *            - alert dialog title
	 * @param message
	 *            - alert message
	 * @param status
	 *            - success/failure (used to set icon)
	 * */
	@SuppressWarnings("deprecation")
	public void showAlertDialog(Context context, String title, String message,
			Boolean status) {
		AlertDialog alertDialog = new AlertDialog.Builder(context).create();

		// Setting Dialog Title
		alertDialog.setTitle(title);

		// Setting Dialog Message
		alertDialog.setMessage(message);

		// Setting alert dialog icon
		alertDialog.setIcon((status) ? R.drawable.cancel : R.drawable.cancel);

		// Setting OK Button
		alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
			}
		});

		// Showing Alert Message
		alertDialog.show();
	}

	private class MyTabListener implements ActionBar.TabListener {
		private Fragment mFragment;
		private final Activity mActivity;
		private final String mFragName;

		public MyTabListener(Activity activity, String fragName) {
			mActivity = activity;
			mFragName = fragName;
		}

		@SuppressLint("NewApi")
		@Override
		public void onTabReselected(Tab tab, FragmentTransaction ft) {
			// TODO Auto-generated method stub
		}

		@SuppressLint("NewApi")
		@Override
		public void onTabSelected(Tab tab, FragmentTransaction ft) {
			mFragment = Fragment.instantiate(mActivity, mFragName);
			ft.add(android.R.id.content, mFragment);
		}

		@SuppressLint("NewApi")
		@Override
		public void onTabUnselected(Tab tab, FragmentTransaction ft) {
			ft.remove(mFragment);
			mFragment = null;
		}
	}

}

Ich hoffe es ist klar geworden wo mein Problem liegt.

Vielen Dank schonmal im Voraus.

Didi95
 
Zurück
Oben Unten