There is two arrows as you see in picture ..
one indicate to Activities in my project
other one indicate to recommended activity to declare in manifest ..
but there is no recommended activity except " StreamingActivity "
when i run my application ,, application show me that message " Unfortunately , application has stopped "
this code for publisheractivity
package khaabbas.huthaifa.com.talk_listen;
import android.hardware.Camera;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import com.red5pro.streaming.R5Connection;
import com.red5pro.streaming.R5Stream;
import com.red5pro.streaming.R5StreamProtocol;
import com.red5pro.streaming.config.R5Configuration;
import com.red5pro.streaming.source.R5Camera;
import com.red5pro.streaming.source.R5Microphone;
//import android.graphics.Camera;
public class PublishFragment extends android.support.v4.app.Fragment implements SurfaceHolder.Callback {
public static android.support.v4.app.Fragment newInstance() {
PublishFragment fragment = new PublishFragment();
Bundle args = new Bundle();
fragment.setArguments(args);
return fragment;
}
public PublishFragment() {
// Required empty public constructor
}
public R5Configuration configuration;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
configuration = new R5Configuration(R5StreamProtocol.RTSP, "localhost", 8554, "live", 1.0f);
configuration.setLicenseKey("NBZF-UFM2-GCEP-OUYZ");
configuration.setBundleID(getActivity().getPackageName());
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_publish, container, false);
return v;
}
protected Camera camera;
protected boolean isPublishing = false;
protected R5Stream stream;
private void preview() {
camera = Camera.open(Camera.CameraInfo.CAMERA_FACING_FRONT);
SurfaceView surface = (SurfaceView) getActivity().findViewById(R.id.surfaceView);
surface.getHolder().addCallback(this);
}
#Override
public void surfaceCreated(SurfaceHolder surfaceHolder) {
try {
camera.setPreviewDisplay(surfaceHolder);
camera.startPreview();
}
catch(Exception e) {
e.printStackTrace();
}
}
#Override
public void surfaceChanged(SurfaceHolder surfaceHolder, int i, int i2, int i3) {
}
#Override
public void surfaceDestroyed(SurfaceHolder surfaceHolder) {
}
#Override
public void onResume() {
super.onResume();
preview();
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
Button publishButton = (Button) getActivity().findViewById(R.id.publishButton);
publishButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
onPublishToggle();
}
});
}
private void onPublishToggle() {
Button publishButton = (Button) getActivity().findViewById(R.id.publishButton);
if(isPublishing) {
stop();
}
else {
start();
}
isPublishing = !isPublishing;
publishButton.setText(isPublishing ? "stop" : "start");
}
public void start() {
camera.stopPreview();
stream = new R5Stream(new R5Connection(configuration));
stream.setView((SurfaceView) getActivity().findViewById(R.id.surfaceView));
R5Camera r5Camera = new R5Camera(camera, 320, 240);
R5Microphone r5Microphone = new R5Microphone();
stream.attachCamera(r5Camera);
stream.attachMic(r5Microphone);
stream.publish("red5prostream", R5Stream.RecordType.Live);
camera.startPreview();
}
public void stop() {
if(stream != null) {
stream.stop();
camera.startPreview();
}
}
#Override
public void onPause() {
super.onPause();
if(isPublishing) {
onPublishToggle();
}
}
}
Remove both this activity because u used only single activity it define activity and two other is fragment.
<activity android:name=".S"/>
<activity android:name=".Sub"/>
and fragment call used below code..
Fragment fragment = new HomeFragment();
getSupportFragmentManager().beginTransaction()
.replace(R.id.fragment_frame, fragment, fragment.getClass().getSimpleName()).addToBackStack(null).commit();
No need to declare fragment on manifest, remove fragment declaration from manifest because you are declare fragment within section in manifest file.
Related
what i'm trying to do:
in FirstFragment the user can type in his weight.
in SecondFragment the weight should be shown in a TextView
the Value should be passed on swipe of the user.
i tried arround 3 how-to's and read a lot about fragments but i still couldn't find a suitable solution. As i'm kind of new to fragments it could also be that i made a uncommon way to generate fragments and it therefore doesn't work but i couldn't figure it out yet.
As you can se unerneath actually there is an error in the code because i tried to get access to the method of FirstFragment through the MainActivity
To simplyfy, i don't poste the whole code of the two fragment xlm's.
first_frag.xml have a EditText (id: getWeight) Box where you only can enter numbers up to 3 digits
second_frag.xml has a TextView (id: txtAlcLvl)
activity_main.xml:
<android.support.v4.view.ViewPager
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/viewPager"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
/>
MainActivity.java:
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;
public class MainActivity extends FragmentActivity {
Calculator calc = new Calculator();
ViewPager pager;
private MyPagerAdapter myPagerAdapter;
String TabFragmentB;
public void setTabFragmentB(String t){
TabFragmentB = t;
}
public String getTabFragmentB(){
return TabFragmentB;
}
public Calculator getCalc(){
return this.calc;
}
public void getWeight(){
FragmentManager fm = getSupportFragmentManager();
FirstFragment fragment = (FirstFragment)fm.findFragmentById(R.id.i_dont_know_the_id);
//failure because trying to get access to Method of FirstFragment
fragment.getWeight();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final MyPagerAdapter pagerAdapter = new MyPagerAdapter(getSupportFragmentManager());
pager = (ViewPager) findViewById(R.id.viewPager);
pager.setAdapter(pagerAdapter);
pager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(final int i, final float v, final int i2) {
}
#Override
public void onPageSelected(final int i) {
YourFragmentInterface fragment = (YourFragmentInterface) pagerAdapter.instantiateItem(pager, i);
if (fragment != null) {
fragment.fragmentBecameVisible();
}
}
#Override
public void onPageScrollStateChanged(final int i) {
}
});
}
public interface YourFragmentInterface {
void fragmentBecameVisible();
}
private class MyPagerAdapter extends FragmentStatePagerAdapter {
public MyPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
switch(position) {
case 1: return new SecondFragment(); //SecondFragment.newInstance("SecondFragment, Instance 1");
case 0: return new FirstFragment();
default: return new FirstFragment(); //FirstFragment.newInstance("FirstFragment, Default");
}
}
#Override
public int getCount() {
return 2;
}
}
}
FirstFragment.java:
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
public class FirstFragment extends Fragment implements MainActivity.YourFragmentInterface {
Button btnBeer;
Button btnBeerSmall;
Button btnWine;
Button btnLiq;
Button btnSch;
Button btnWater;
Button btnMale;
Button btnFemale;
Calculator calc;
EditText getWeight;
public String getWeight(){
return getWeight.getText().toString();
}
#Override
public void fragmentBecameVisible() {
// You can do your animation here because we are visible! (make sure onViewCreated has been called too and the Layout has been laid. Source for another question but you get the idea.
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.first_frag, container, false);
calc = ((MainActivity) getActivity()).getCalc();
btnBeer = (Button) v.findViewById(R.id.btnBeer);
btnBeerSmall = (Button) v.findViewById(R.id.btnBeerSmall);
btnWine = (Button) v.findViewById(R.id.btnWine);
btnLiq = (Button) v.findViewById(R.id.btnLiq);
btnSch = (Button) v.findViewById(R.id.btnSch);
btnWater = (Button) v.findViewById((R.id.btnWater));
btnMale = (Button) v.findViewById(R.id.btnMale);
btnFemale = (Button) v.findViewById(R.id.btnFemale);
getWeight = (EditText) v.findViewById(R.id.getWeight);
btnBeer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
calc.addConsumption(0);
}
});
btnBeerSmall.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
calc.addConsumption(1);
}
});
btnWine.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
calc.addConsumption(2);
}
});
btnLiq.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
calc.addConsumption(3);
}
});
btnSch.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
calc.addConsumption(4);
}
});
btnWater.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
calc.addConsumption(5);
}
});
btnMale.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
btnMale.setBackgroundResource(R.drawable.male_false);
btnFemale.setBackgroundResource(R.drawable.female);
}
});
btnFemale.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
btnFemale.setBackgroundResource(R.drawable.female_false);
btnMale.setBackgroundResource(R.drawable.male);
}
});
return v;
}
public static FirstFragment newInstance(String text) {
FirstFragment f = new FirstFragment();
Bundle b = new Bundle();
b.putString("msg", text);
f.setArguments(b);
return f;
}
}
SecondFragment.java:
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.TextView;
public class SecondFragment extends Fragment implements MainActivity.YourFragmentInterface {
TextView txtAlcLvl;
TextView txtTimeToZero;
TextView txtPeak;
ImageButton btnReset;
Calculator calc;
String weight;
#Override
public void fragmentBecameVisible() {
calc.person.setSex(false);
calc.person.setWeight(80);
txtAlcLvl.setText(((MainActivity) getActivity()).getWeight());
//txtAlcLvl.setText(String.format("%.2f", calc.getCurrentLevel()) + "‰");
// You can do your animation here because we are visible! (make sure onViewCreated has been called too and the Layout has been laid. Source for another question but you get the idea.
}
public void setSex(){
}
public void setWeight(){
try{
} catch(NumberFormatException e){
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.second_frag, container, false);
calc = ((MainActivity) getActivity()).getCalc();
String myTag = getTag();
((MainActivity)getActivity()).setTabFragmentB(myTag);
txtAlcLvl = (TextView) v.findViewById(R.id.txtAlcLvl);
txtTimeToZero = (TextView) v.findViewById(R.id.txtTimeToZero);
txtPeak = (TextView) v.findViewById(R.id.txtPeak);
btnReset = (ImageButton) v.findViewById((R.id.btnReset));
btnReset.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
calc.resetConsumption();
}
});
return v;
}
public void updateText(String t){
txtAlcLvl.setText(t);
}
public static SecondFragment newInstance(String text) {
SecondFragment f = new SecondFragment();
Bundle b = new Bundle();
b.putString("msg", text);
f.setArguments(b);
return f;
}
}
You could do it the over way round.
Instead of trying to get the weight in activity from your fragment, try to set the weight on the activity from the fragment.
public class MainActivity extends FragmentActivity {
...
private float weight;
public void setWeight(float weight) {
this.weight = weight;
}
public float getWeight() {
return this.weight();
}
Then in your FirstFragment:
((MainActivity)getActivity()).setWeight(...);
And finally in your SecondFragment:
float weight = ((MainActivity)getActivity()).getWeight();
Don't try to "pass" the value like you would normally expect when an activity is invoking a new fragment.
Instead, consider using some persistent storage to store the value, such as SharedPreferences or a Sqlite database. Each fragment can read and write values out of there as needed.
Im trying to implement a webview inside one of my pages but I am using an "else if" for the fragment. Im getting and error on the line "changeFragment(new CalendarFragment());", saying that it cannot be applied to my Calender Fragment file. Any help solving this would be greatly appreciated.
MainActivity.java
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTransaction;
import android.view.MotionEvent;
import android.view.View;
import android.webkit.WebViewClient;
import android.widget.Toast;
import com.special.ResideMenu.ResideMenu;
import com.special.ResideMenu.ResideMenuItem;
import com.parse.Parse;
import com.parse.ParseAnalytics;
import com.parse.ParseInstallation;
import com.parse.PushService;
public class MenuActivity extends FragmentActivity implements View.OnClickListener{
private ResideMenu resideMenu;
private MenuActivity mContext;
private ResideMenuItem itemHome;
private ResideMenuItem itemProfile;
private ResideMenuItem itemCalendar;
private ResideMenuItem itemSettings;
/**
* Called when the activity is first created.
*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mContext = this;
setUpMenu();
changeFragment(new HomeFragment());
Parse.initialize(this, "123", "IHecHh");
PushService.setDefaultPushCallback(this, MenuActivity.class);
}
private void setUpMenu() {
// attach to current activity;
resideMenu = new ResideMenu(this);
resideMenu.setBackground(R.drawable.menu_background);
resideMenu.attachToActivity(this);
resideMenu.setMenuListener(menuListener);
//valid scale factor is between 0.0f and 1.0f. leftmenu'width is 150dip.
resideMenu.setScaleValue(0.6f);
// create menu items;
itemHome = new ResideMenuItem(this, R.drawable.icon_home, "Home");
itemProfile = new ResideMenuItem(this, R.drawable.icon_profile, "Profile");
itemCalendar = new ResideMenuItem(this, R.drawable.icon_calendar, "Calendar");
itemSettings = new ResideMenuItem(this, R.drawable.icon_settings, "Settings");
itemHome.setOnClickListener(this);
itemProfile.setOnClickListener(this);
itemCalendar.setOnClickListener(this);
itemSettings.setOnClickListener(this);
resideMenu.addMenuItem(itemHome, ResideMenu.DIRECTION_LEFT);
resideMenu.addMenuItem(itemProfile, ResideMenu.DIRECTION_LEFT);
resideMenu.addMenuItem(itemCalendar, ResideMenu.DIRECTION_RIGHT);
resideMenu.addMenuItem(itemSettings, ResideMenu.DIRECTION_RIGHT);
// You can disable a direction by setting ->
// resideMenu.setSwipeDirectionDisable(ResideMenu.DIRECTION_RIGHT);
findViewById(R.id.title_bar_left_menu).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
resideMenu.openMenu(ResideMenu.DIRECTION_LEFT);
}
});
findViewById(R.id.title_bar_right_menu).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
resideMenu.openMenu(ResideMenu.DIRECTION_RIGHT);
}
});
}
#Override
public boolean dispatchTouchEvent(MotionEvent ev) {
return resideMenu.dispatchTouchEvent(ev);
}
#Override
public void onClick(View view) {
if (view == itemHome){
changeFragment(new HomeFragment());
}else if (view == itemProfile){
changeFragment(new ProfileFragment());
}else if (view == itemCalendar){
changeFragment(new CalendarFragment());
}else if (view == itemSettings){
changeFragment(new SettingsFragment());
}
resideMenu.closeMenu();
}
private ResideMenu.OnMenuListener menuListener = new ResideMenu.OnMenuListener() {
#Override
public void openMenu() {
Toast.makeText(mContext, "Menu is opened!", Toast.LENGTH_SHORT).show();
}
#Override
public void closeMenu() {
Toast.makeText(mContext, "Menu is closed!", Toast.LENGTH_SHORT).show();
}
};
private void changeFragment(Fragment targetFragment){
resideMenu.clearIgnoredViewList();
getSupportFragmentManager()
.beginTransaction()
.replace(R.id.main_fragment, targetFragment, "fragment")
.setTransitionStyle(FragmentTransaction.TRANSIT_FRAGMENT_FADE)
.commit();
}
// What good method is to access resideMenu?
public ResideMenu getResideMenu(){
return resideMenu;
}
}
CalendarFragment.java
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class CalendarFragment extends Activity implements OnClickListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.calendar);
WebView wv = (WebView) findViewById(R.id.webView1);
wv.getSettings().setJavaScriptEnabled(true);
wv.loadUrl("http://www.xxxx.com");
wv.setWebViewClient(new WebViewClient());
}
#Override
public void onClick(View v) {
}
private class Callback extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
return (true);
}
}
#Override
public void onPause() {
super.onPause();
}
#Override
public void onResume() {
super.onResume();
}
}
your CalendarFragment is not actually a Fragment but an Activity since you extended Activity
public class CalendarFragment extends Activity
but the changeFragment method takes a parameter a Fragment, causing a compile time error,
In the android app I am creating, I have a scrollable tabs from my TabsPagerAdapter class which extends FragmentPagerAdapter. However, in my app, I am trying to display all user installed apps on the phone into a section of a tab. However the class which was able to return all of that extended FragmentActivity.
I tried to follow this, but it is not working.
How to list all downloaded android apps in a fragment
Sadly, after much research I found out that I can only put fragments in different tabs and only have one Activity displayed at any one time and the tabs themselves can only return Fragments.
I really need to put all the user installed apps into a Fragment in this case I guess but I am unsure how to implement this...I have an Adapter class and everything.
Here is my InstalledAppActivity class which extends FragmentActivity to return all user downloaded apps.
package com.spicycurryman.getdisciplined10.app;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.ActivityNotFoundException;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.Toast;
import com.javatechig.listapps.ApplicationAdapter;
import java.util.ArrayList;
import java.util.List;
public class InstalledAppActivity extends FragmentActivity {
private PackageManager packageManager = null;
private List<ApplicationInfo> applist = null;
private ApplicationAdapter listadaptor = null;
ListView InstalledAppList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.installed_apps);
InstalledAppList = (ListView) findViewById(R.id.Installed_List);
packageManager = getPackageManager();
new LoadApplications().execute();
InstalledAppList.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
ApplicationInfo app = applist.get(i);
try {
Intent intent = packageManager
.getLaunchIntentForPackage(app.packageName);
if (null != intent) {
startActivity(intent);
}
} catch (ActivityNotFoundException e) {
Toast.makeText(InstalledAppActivity.this, e.getMessage(),
Toast.LENGTH_LONG).show();
} catch (Exception e) {
Toast.makeText(InstalledAppActivity.this, e.getMessage(),
Toast.LENGTH_LONG).show();
}
}
});
}
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
packageManager = getPackageManager();
new LoadApplications().execute();
return inflater.inflate(R.layout.installed_apps, container, false);
}
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.block, menu);
return true;
}
public boolean onOptionsItemSelected(MenuItem item) {
boolean result = true;
switch (item.getItemId()) {
case R.id.main_text: {
displayAboutDialog();
break;
}
default: {
result = super.onOptionsItemSelected(item);
break;
}
}
return result;
}
private void displayAboutDialog() {
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(getString(R.string.app_name));
builder.setMessage(getString(R.string.slogan));
builder.setPositiveButton("Know More", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://javatechig.com"));
startActivity(browserIntent);
dialog.cancel();
}
});
builder.setNegativeButton("No Thanks!", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
builder.show();
}
private AdapterView.OnItemClickListener OnItemClickListener = new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
}
protected void onListItemClick(ListView InstalledAppList, View v, int position, long id) {
ApplicationInfo app = applist.get(position);
try {
Intent intent = packageManager
.getLaunchIntentForPackage(app.packageName);
if (null != intent) {
startActivity(intent);
}
} catch (ActivityNotFoundException e) {
Toast.makeText(InstalledAppActivity.this, e.getMessage(),
Toast.LENGTH_LONG).show();
} catch (Exception e) {
Toast.makeText(InstalledAppActivity.this, e.getMessage(),
Toast.LENGTH_LONG).show();
}
}
};
private List<ApplicationInfo> checkForLaunchIntent(List<ApplicationInfo> list) {
ArrayList<ApplicationInfo> applist = new ArrayList<ApplicationInfo>();
for (ApplicationInfo info : list) {
try {
if (null != packageManager.getLaunchIntentForPackage(info.packageName)) {
applist.add(info);
}
} catch (Exception e) {
e.printStackTrace();
}
}
return applist;
}
private class LoadApplications extends AsyncTask<Void, Void, Void> {
private ProgressDialog progress = null;
#Override
protected Void doInBackground(Void... params) {
applist = checkForLaunchIntent(packageManager.getInstalledApplications(PackageManager.GET_META_DATA));
listadaptor = new ApplicationAdapter(InstalledAppActivity.this,
R.layout.snippet_list_row, applist);
return null;
}
#Override
protected void onCancelled() {
super.onCancelled();
}
#Override
protected void onPostExecute(Void result) {
//setListAdapter(listadaptor);
InstalledAppList.setAdapter(listadaptor);
super.onPostExecute(result);
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
}
}
Here is an example of how you would do it:
package com.spicycurryman.getdisciplined10.app;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageItemInfo;
import android.content.pm.PackageManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import com.ibc.android.demo.appslist.app.ApkAdapter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class InstalledAppActivity extends Fragment
implements OnItemClickListener {
//hi
PackageManager packageManager;
ListView apkList;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
setHasOptionsMenu(true);
View rootView = inflater.inflate(R.layout.user_installed, container, false);
packageManager = getActivity().getPackageManager();
/*To filter out System apps*/
apkList = (ListView) rootView.findViewById(R.id.applist);
new LoadApplications(getActivity().getApplicationContext()).execute();
return rootView;
}
/**
* Return whether the given PackageInfo represents a system package or not.
* User-installed packages (Market or otherwise) should not be denoted as
* system packages.
*
* #param pkgInfo
* #return boolean
*/
private boolean isSystemPackage(PackageInfo pkgInfo) {
return ((pkgInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) ? true
: false;
}
private boolean isSystemPackage1(PackageInfo pkgInfo) {
return ((pkgInfo.applicationInfo.flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0) ? false
: true;
}
// Don't need in Fragment
/*#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.block, menu);
// super.onCreateOptionsMenu(menu,inflater);
}*/
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
//ApkAdapter apkAdapter=(ApkAdapter)apkList.getAdapter();
}
private class LoadApplications extends AsyncTask<Void, Void, Void> {
Context mContext;
private ProgressDialog pDialog;
List<PackageInfo> packageList1 = new ArrayList<PackageInfo>();
public LoadApplications(Context context){
Context mContext = context;
}
#Override
protected Void doInBackground(Void... params) {
List<PackageInfo> packageList = packageManager
.getInstalledPackages(PackageManager.GET_PERMISSIONS);
/* List<ApplicationInfo> list = mContext.getPackageManager().getInstalledApplications(PackageManager.GET_UNINSTALLED_PACKAGES);
for(int n = 0;n<list.size();n++){
if ((list.get(n).flags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP))
}*/
for(PackageInfo pi : packageList) {
boolean b = isSystemPackage(pi);
boolean c = isSystemPackage1(pi);
if(!b || !c ) {
packageList1.add(pi);
}
}
//sort by application name
final PackageItemInfo.DisplayNameComparator comparator = new PackageItemInfo.DisplayNameComparator(packageManager);
Collections.sort(packageList1, new Comparator<PackageInfo>() {
#Override
public int compare(PackageInfo lhs, PackageInfo rhs) {
return comparator.compare(lhs.applicationInfo, rhs.applicationInfo);
}
});
return null;
}
#Override
protected void onCancelled() {
super.onCancelled();
}
#Override
protected void onPreExecute() {
pDialog = new ProgressDialog(InstalledAppActivity.this.getActivity());
pDialog.setMessage("Loading your apps...");
pDialog.show();
}
#Override
protected void onPostExecute(Void result) {
apkList.setAdapter(new ApkAdapter(getActivity(), packageList1, packageManager));
if (pDialog.isShowing()){
pDialog.dismiss();
}
super.onPostExecute(result);
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
}
}
way don't you just from youre main activity on click off the tab create a fragment with a listview in it and displays the data list there?? you can pars the list to the fragment bay saying
fragmentclass fragment = new fragmentclass(list);
fragment.show();
if youre having truble understanding fragments you can watch this great tutorial on it especialy the part on inter fragment communication is realy use full
In my Android app, I am trying to place a ListView in my FragmentActivity. Unfortunately there is no such thing as FragmentListActivity. The problem is that I can't call setListAdapter() and onListItemClick() methods.
So I did a lot of research and I went to my XML file and manually added the ListView there. Then instead of getListView(), I declared a ListView variable so I could call the methods on my new ListView variable. Unfortunately the method is still riddled with errors The method is unable to be resolved etc.
Here is my java code:
package com.spicycurryman.getdisciplined10.app;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.ActivityNotFoundException;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import com.javatechig.listapps.ApplicationAdapter;
import java.util.ArrayList;
import java.util.List;
public class InstalledAppActivity extends FragmentActivity {
private PackageManager packageManager = null;
private List<ApplicationInfo> applist = null;
private ApplicationAdapter listadaptor = null;
//Implementing the Listview Programatically
ListView InstalledAppList = (ListView) findViewById(R.id.Installed_List);
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
packageManager = getPackageManager();
new LoadApplications().execute();
return inflater.inflate(R.layout.installed_apps, container, false);
}
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.block, menu);
return true;
}
public boolean onOptionsItemSelected(MenuItem item) {
boolean result = true;
switch (item.getItemId()) {
case R.id.main_text: {
displayAboutDialog();
break;
}
default: {
result = super.onOptionsItemSelected(item);
break;
}
}
return result;
}
private void displayAboutDialog() {
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(getString(R.string.app_name));
builder.setMessage(getString(R.string.slogan));
builder.setPositiveButton("Know More", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://javatechig.com"));
startActivity(browserIntent);
dialog.cancel();
}
});
builder.setNegativeButton("No Thanks!", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
builder.show();
}
//here
InstalledAppList.setOnItemClickListener(new OnItemClickListener()){
#Override
public void onItemClick(AdapterView <?> arg0, View view, int index, long id){
ApplicationInfo app = applist.get(index);
try {
Intent intent = packageManager
.getLaunchIntentForPackage(app.packageName);
if (null != intent) {
startActivity(intent);
}
} catch (ActivityNotFoundException e) {
Toast.makeText(InstalledAppActivity.this, e.getMessage(),
Toast.LENGTH_LONG).show();
} catch (Exception e) {
Toast.makeText(InstalledAppActivity.this, e.getMessage(),
Toast.LENGTH_LONG).show();
}
}
});
private List<ApplicationInfo> checkForLaunchIntent(List<ApplicationInfo> list) {
ArrayList<ApplicationInfo> applist = new ArrayList<ApplicationInfo>();
for (ApplicationInfo info : list) {
try {
if (null != packageManager.getLaunchIntentForPackage(info.packageName)) {
applist.add(info);
}
} catch (Exception e) {
e.printStackTrace();
}
}
return applist;
}
private class LoadApplications extends AsyncTask<Void, Void, Void> {
private ProgressDialog progress = null;
#Override
protected Void doInBackground(Void... params) {
applist = checkForLaunchIntent(packageManager.getInstalledApplications(PackageManager.GET_META_DATA));
listadaptor = new ApplicationAdapter(InstalledAppActivity.this,
R.layout.snippet_list_row, applist);
return null;
}
#Override
protected void onCancelled() {
super.onCancelled();
}
#Override
protected void onPostExecute(Void result) {
//setListAdapter(listadaptor);
InstalledAppList.setAdapter(listadaptor);
progress.dismiss();
super.onPostExecute(result);
}
#Override
protected void onPreExecute() {
progress = ProgressDialog.show(InstalledAppActivity.this, null,
"Loading application info...");
super.onPreExecute();
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
}
}
Here is my XML File:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<ListView
android:id="#+id/Installed_List"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
</LinearLayout>
Try this..
You have missed onCreate
ListView InstalledAppList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.installed_apps);
InstalledAppList = (ListView) findViewById(R.id.Installed_List);
packageManager = getPackageManager();
new LoadApplications().execute();
InstalledAppList.setOnItemClickListener(new OnItemClickListener()){
#Override
public void onItemClick(AdapterView <?> arg0, View view, int index, long id){
ApplicationInfo app = applist.get(index);
try {
Intent intent = packageManager
.getLaunchIntentForPackage(app.packageName);
if (null != intent) {
startActivity(intent);
}
} catch (ActivityNotFoundException e) {
Toast.makeText(InstalledAppActivity.this, e.getMessage(),
Toast.LENGTH_LONG).show();
} catch (Exception e) {
Toast.makeText(InstalledAppActivity.this, e.getMessage(),
Toast.LENGTH_LONG).show();
}
}
});
}
and remove onCreateView and add ItemClickListener also inside onCreate
public class MyAndroidVersionListFragment extends ListFragment{
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
CustomDoctorsListAdapter adapter= new CustomDoctorsListAdapter(getActivity(), getResources().getStringArray(R.array.doctors_name), getResources().getStringArray(R.array.doctors_address),
getResources().getStringArray(R.array.doctors_category), getResources().obtainTypedArray(R.array.doctors_rating), getResources().getIntArray(R.array.doctors_clinic_distance));
getResources().obtainTypedArray(R.array.doctors_rating).recycle();
android.R.layout.simple_list_item_multiple_choice, android_versions);
setListAdapter(adapter);
Toast.makeText(getActivity(), "Mypostion"+position+"", Toast.LENGTH_LONG).show();
return super.onCreateView(inflater, container, savedInstanceState);
}
#Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
position = getArguments().getInt("second");
}
#Override
public void onStart() {
super.onStart();
getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);
}
try List fragment like this hope it will help you
Just need to know the proper way to implement Google analytics to track when a user is on a fragment in real time this is what is do now
#Override
public void onResume() {
super.onResume();
Tracker myTracker = parentActivity.getTracker();
myTracker.setCustomMetric(1, (long) 1);
myTracker.sendView("Music View");
}
the getTracker class is in my main activity and just returns the instance of tracker in the main activity
Any help would be much appreciated!
Mochini's answer uses Google Analytics V2. Bellow you can see how to do it on V4 and V3:
V4:
Application:
public class YourApplication extends Application
{
public synchronized Tracker getTracker() {
try {
final GoogleAnalytics googleAnalytics = GoogleAnalytics.getInstance(this);
return googleAnalytics.newTracker(R.xml.analytics);
}catch(final Exception e){
Log.e(TAG, "Failed to initialize Google Analytics V4");
}
return null;
}
}
res/xml/analytics.xml (you can name it anything, it does not need to be called "analytics")
<?xml version="1.0" encoding="utf-8" ?>
<resources xmlns:tools="http://schemas.android.com/tools" tools:ignore="TypographyDashes">
<!--Replace placeholder ID with your tracking ID-->
<string name="ga_trackingId">UA-XXXXXXXX-X</string>
<!--Enable automatic activity tracking-->
<bool name="ga_autoActivityTracking">true</bool>
<!--Disable automatic exception tracking-->
<bool name="ga_reportUncaughtExceptions">false</bool>
</resources>
build.gradle:
compile 'com.google.android.gms:play-services:7.3.0'
Fragment superclass:
public abstract class TrackedFragment extends Fragment{
#Override
public void onResume() {
super.onResume();
final Tracker tracker = yourApplicationInstance.getTracker();
if(tracker != null){
tracker.setScreenName(getClass().getSimpleName());
tracker.send(new HitBuilders.ScreenViewBuilder().build());
}
}
}
V3
import android.os.Bundle;
import android.support.v4.app.Fragment;
import com.google.analytics.tracking.android.EasyTracker;
import com.google.analytics.tracking.android.Fields;
import com.google.analytics.tracking.android.MapBuilder;
import com.google.analytics.tracking.android.Tracker;
public abstract class TrackedFragment extends Fragment{
private Tracker tracker;
#Override
public void onActivityCreated(final Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
this.tracker = EasyTracker.getInstance(getActivity());
}
#Override
public void onResume() {
super.onResume();
this.tracker.set(Fields.SCREEN_NAME, getClass().getSimpleName());
this.tracker.send( MapBuilder.createAppView().build() );
}
}
Source: https://developers.google.com/analytics/devguides/collection/android/v3/migration
This an example using FragmentActivity and fragments:
Create XML file in value folder (values/analytics.xml):
<?xml version="1.0" encoding="utf-8"?>
<resources>
<!-- Replace placeholder ID with your tracking ID -->
<string name="ga_trackingId">XX-xxxxxxxx-x</string>
<!-- Enable Activity tracking -->
<bool name="ga_autoActivityTracking">true</bool>
<!-- Enable debug -->
<bool name="ga_debug">true</bool>
<!-- The screen names that will appear in your reporting -->
<string name="com.example.myapp.FragmentActivity">Fragment activity</string>
<!--
The inverval of time after all the collected data
should be sent to the server, in seconds.
-->
<integer name="ga_dispatchPeriod">20</integer>
</resources>
In your FragmentActivity class, add this:
#Override
protected void onStart() {
super.onStart();
EasyTracker.getInstance().setContext(this.getBaseContext());
EasyTracker.getInstance().activityStart(this); // Add this method
}
#Override
protected void onStop() {
super.onStop();
EasyTracker.getInstance().activityStop(this); // Add this method
}
Create new class in your package: TrackedFragment.java
public class TrackedFragment extends Fragment {
private Tracker tracker;
private String activityId;
private String fragmentId;
#Override
public void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
EasyTracker.getInstance().setContext(getActivity().getApplicationContext());
this.tracker = EasyTracker.getTracker();
this.fragmentId = getClass().getSimpleName();
this.activityId = getActivity().getClass().getSimpleName();
}
#Override
public void onResume() {
super.onResume();
this.tracker.sendView("/" + this.activityId + "/" + this.fragmentId);
}
}
Finally, your fragment should extend from TrackedFragment like:
public class NewFragment extends TrackedFragment {
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.newfragment, null);
}
}
Tracking methods section suggests that you just need to call EasyTracker.getInstance().setContext(getActivity()); first, then you can use the tracker in "other classes".
manual screen tracking section suggests that you can track a Fragment view with myTracker.sendView("Home Screen");
Another approach for V3 (since onResume() is tied to the Activity and not the Fragment. This works well when the parent/child relationships are well-known.
Parent Fragment sends initial event onStart():
public class ParentFragment extends Fragment {
private Tracker mTracker;
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
mTracker = EasyTracker.getInstance(getActivity());
}
#Override
public void onStart() {
super.onStart();
mTracker.set(Fields.SCREEN_NAME, "Parent Fragment");
mTracker.send(MapBuilder.createAppView().build());
}
}
Child Fragment overrides both onStart() and onStop() :
public class ChildFragment extends Fragment {
private Tracker mTracker;
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
mTracker = EasyTracker.getInstance(getActivity());
}
#Override
public void onStart() {
super.onStart();
mTracker.set(Fields.SCREEN_NAME, "Child Fragment");
mTracker.send(MapBuilder.createAppView().build());
}
#Override
public void onStop() {
super.onStop();
mTracker.set(Fields.SCREEN_NAME, "Parent Fragment");
mTracker.send(MapBuilder.createAppView().build());
}
}
Tiago's version can't be used in the new goole analytics v4. Instead, use this code from Google's docs
package com.google.android.apps.mobileplayground;
import com.google.android.apps.mobileplayground.AnalyticsSampleApp.TrackerName;
import com.google.android.gms.analytics.GoogleAnalytics;
import com.google.android.gms.analytics.HitBuilders;
import com.google.android.gms.analytics.Tracker;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
/**
* Class to exercise Event hits.
*/
public class EventFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
View view = inflater.inflate(R.layout.event, container, false);
setupEvent(view, R.id.video1Play, R.string.videoCategory, R.string.videoPlay, R.string.video1);
setupEvent(view, R.id.video1Pause, R.string.videoCategory, R.string.videoPause,
R.string.video1);
setupEvent(view, R.id.video2Play, R.string.videoCategory, R.string.videoPlay, R.string.video2);
setupEvent(view, R.id.video2Pause, R.string.videoCategory, R.string.videoPause,
R.string.video2);
setupEvent(view, R.id.book1View, R.string.bookCategory, R.string.bookView, R.string.book1);
setupEvent(view, R.id.book1Share, R.string.bookCategory, R.string.bookShare, R.string.book1);
final Button dispatchButton = (Button) view.findViewById(R.id.eventDispatch);
dispatchButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// Manually start a dispatch (Unnecessary if the tracker has a dispatch interval)
GoogleAnalytics.getInstance(getActivity().getApplicationContext()).dispatchLocalHits();
}
});
return view;
}
private void setupEvent(View v, int buttonId, final int categoryId, final int actionId,
final int labelId) {
final Button pageviewButton = (Button) v.findViewById(buttonId);
pageviewButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// Get tracker.
Tracker t = ((AnalyticsSampleApp) getActivity().getApplication()).getTracker(
TrackerName.APP_TRACKER);
// Build and send an Event.
t.send(new HitBuilders.EventBuilder()
.setCategory(getString(categoryId))
.setAction(getString(actionId))
.setLabel(getString(labelId))
.build());
}
});
}
}
with android google analytics v4
i tried this and it worked
refering this https://developers.google.com/analytics/devguides/collection/android/v4/events
import java.net.URLEncoder;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Xml.Encoding;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.widget.ScrollView;
import android.widget.TextView;
import com.Blog.gkgyan.AnalyticsSampleApp.TrackerName;
import com.Blog.gkgyan.parser.RSSFeed;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.AdView;
import com.google.android.gms.analytics.GoogleAnalytics;
import com.google.android.gms.analytics.HitBuilders;
import com.google.android.gms.analytics.Tracker;
public class DetailFragment extends Fragment {
private int fPos;
RSSFeed fFeed;
String country;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
fFeed = (RSSFeed)getArguments().getSerializable("feed");
fPos = getArguments().getInt("pos");
Tracker t = ((AnalyticsSampleApp) getActivity().getApplication()).getTracker(
TrackerName.APP_TRACKER);
// Build and send an Event.
t.send(new HitBuilders.EventBuilder()
.setCategory(fFeed.getItem(fPos).getTitle())
.setAction("viewpager click")
.setLabel("viewpager label")
.build());
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.detail_fragment, container, false);
// Initializr views
TextView title = (TextView)view.findViewById(R.id.title);
WebView desc = (WebView)view.findViewById(R.id.desc);
// Enable the vertical fading edge (by default it is disabled)
ScrollView sv = (ScrollView)view.findViewById(R.id.sv);
sv.setVerticalFadingEdgeEnabled(true);
// Set the views
desc.getSettings().setJavaScriptEnabled(true);
title.setText(fFeed.getItem(fPos).getTitle());
country = "<html xmlns=\"http://www.w3.org/1999/xhtml\"><head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=iso-8859-1\"><style type=\"text/css\">p{text-align:justify;font-size:125%;}</style></head><body>" + "<p>" + fFeed.getItem(fPos).getDescription()+"</p>"+"</body></html>";
//desc.loadData( country, "text/html", "UTF-8");
//desc.loadData( country, "text/html; charset=utf-8", "utf-8");
desc.loadData( URLEncoder.encode(country).replaceAll("\\+", " "), "text/html", Encoding.UTF_8.toString());
return view;
}
}