Android Fragment Not Updating Image From Interface - java

I am trying to update a image from another thread to a fragment via interface. The code does manage to get into the interface but every time it gets to Left_Image.setImageDrawable(Image_Rotated); I keep getting a null pointer exception. If on the on create for the fragment i set a image it works but as soon as it tries to do it for the interface it comes up with the null pointer exception. I used the command isAdded()) to check if the fragment is attached and that keeps coming back as nothing but i cant seem to fix it and have it attached. Here is the code
Fragment:
import android.app.Activity;
import android.app.FragmentManager;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.graphics.drawable.BitmapDrawable;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.preference.PreferenceFragment;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarActivity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;
import java.util.logging.Handler;
public class Augmented_Reality extends PreferenceFragment implements SensorEventListener {
private SensorManager mSensorManager;
private Sensor mRotationVectorSensor;
private Sensor mMagneticSensor;
private final float[] mRotationMatrix = new float[16];
private Boolean MagnetButtonPressed = false;
private Boolean Left;
private Boolean Right;
Boolean Admin_Mode;
boolean Lock = false;
public SharedPreferences sharedpreferences;
public static final String MyPREFERENCES = "MyPrefs";
ToggleButton HeadTracker;
TextView Position;
TextView Position_Left;
TextView Position_Right;
ImageView Left_Image;
ImageView Right_Image;
private Image_Packet_Flag Image_Flag;
public final byte Image_Sync_Flag = 0x09;
private Context context;
Activity activity;
public Augmented_Reality() {
Image_Flag = new Image_Packet_Flag();
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
context = activity;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
try {
mSensorManager = (SensorManager) getActivity().getSystemService(Context.SENSOR_SERVICE);
mRotationVectorSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_ROTATION_VECTOR);
mMagneticSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD);
mSensorManager.registerListener(this, mRotationVectorSensor, 10000);
mSensorManager.registerListener(this, mMagneticSensor, 10000);
} catch (Exception ex) {
Toast.makeText(getActivity().getApplicationContext(), "failed sensor", Toast.LENGTH_SHORT).show();
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
activity = getActivity();
View rootView = inflater.inflate(R.layout.augmented_reality_view, container, false);
ActionBar actionBar = ((ActionBarActivity) activity).getSupportActionBar();
actionBar.hide();
HeadTracker = (ToggleButton) rootView.findViewById(R.id.HeadTracker);
Left_Image = (ImageView) rootView.findViewById(R.id.lefty);
Right_Image = (ImageView) rootView.findViewById(R.id.righty);
Bitmap icon = BitmapFactory.decodeResource(activity.getResources(),
R.drawable.ytyty);
BitmapDrawable Image = Rotate_Image(icon);
Left_Image.setImageDrawable(Image);
return rootView;
}
#Override
public void onSensorChanged(SensorEvent event) {
if (HeadTracker.isChecked() == true) {
if (event.sensor.getType() == Sensor.TYPE_ROTATION_VECTOR) {
SensorManager.getRotationMatrixFromVector(
mRotationMatrix, event.values);
if (mRotationMatrix[2] >= 0.6 && mRotationMatrix[0] >= -0.1 && mRotationMatrix[0] <= 0.2) {
Left = true;
Right = false;
} else if (mRotationMatrix[2] <= -0.6 && mRotationMatrix[0] >= -0.1 && mRotationMatrix[0] <= 0.2) {
Left = false;
Right = true;
} else {
Left = false;
Right = false;
}
}
}
if (event.sensor.getType() == Sensor.TYPE_MAGNETIC_FIELD) {
if (event.values[2] >= 390) {
MagnetButtonPressed = true;
} else {
MagnetButtonPressed = false;
}
}
}
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
#Override
public void onPause() {
super.onPause();
mSensorManager.unregisterListener(this);
}
public BitmapDrawable Rotate_Image(Bitmap Image) {
Bitmap bitmapOrg = Image;
int width = bitmapOrg.getWidth();
int height = bitmapOrg.getHeight();
Matrix matrix = new Matrix();
matrix.postRotate(90);
Bitmap resizedBitmap = Bitmap.createBitmap(bitmapOrg, 0, 0, width, height, matrix, true);
BitmapDrawable bmd = new BitmapDrawable(resizedBitmap);
return bmd;
}
public void UpdateImages(Bitmap Image) {
System.out.println("Image Updated");
final BitmapDrawable Image_Rotated = Rotate_Image(Image);
System.out.println("Is Added Result: " + isAdded());
if(isAdded()) {
System.out.println("Fragment Added");
Left_Image.setImageDrawable(Image_Rotated);
Right_Image.setImageDrawable(Image_Rotated);
}
}
}
MainActivity:
package com.example.jaynesh.mobile_robot_interface.Main_Files;
import android.app.Fragment;
import android.app.FragmentManager;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;
import com.example.jaynesh.mobile_robot_interface.Fragments.Augmented_Reality;
import com.example.jaynesh.mobile_robot_interface.Fragments.Main_Screen;
import com.example.jaynesh.mobile_robot_interface.Fragments.Settings;
import com.example.jaynesh.mobile_robot_interface.Fragments.Mission_Data;
import com.example.jaynesh.mobile_robot_interface.Navigation_Drawer.DrawerItemCustomAdapter;
import com.example.jaynesh.mobile_robot_interface.Navigation_Drawer.ObjectDrawerItem;
import com.example.jaynesh.mobile_robot_interface.Packets.Fragment_Tags.Augmented_Reality_Identifier;
import com.example.jaynesh.mobile_robot_interface.Packets.Fragment_Tags.Main_Screen_Identifier;
import com.example.jaynesh.mobile_robot_interface.Packets.Fragment_Tags.Mission_Data_Identifier;
import com.example.jaynesh.mobile_robot_interface.Packets.Fragment_Tags.Settings_Identifier;
import com.example.jaynesh.mobile_robot_interface.R;
import com.example.jaynesh.mobile_robot_interface.Socket.ClientThread;
public class MainActivity extends ActionBarActivity implements ClientThread.Image_Listener{
// declare properties
private String[] mNavigationDrawerItemTitles;
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
// nav drawer title
private CharSequence mDrawerTitle;
// used to store app title
private CharSequence mTitle;
public SharedPreferences sharedpreferences;
public static final String MyPREFERENCES = "MyPrefs" ;
ClientThread clientThread;
private Augmented_Reality Augmented_Reality_Fragment;
private Main_Screen Main_Screen_Fragment;
private Mission_Data Mission_Data_Fragment;
private Settings Settings_Fragment;
private boolean Socket_Connected = false;
private int Current_Page = 0;
Main_Screen_Identifier MS;
Augmented_Reality_Identifier AR;
Mission_Data_Identifier MD;
Settings_Identifier SF;
Thread serverThread = null;
boolean NewPage = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
MS = new Main_Screen_Identifier();
AR = new Augmented_Reality_Identifier();
MD = new Mission_Data_Identifier();
SF = new Settings_Identifier();
NewPage = true;
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// for proper titles
mTitle = mDrawerTitle = getTitle();
// initialize properties
mNavigationDrawerItemTitles = getResources().getStringArray(R.array.navigation_drawer_items_array);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.left_drawer);
// list the drawer items
ObjectDrawerItem[] drawerItem = new ObjectDrawerItem[4];
drawerItem[0] = new ObjectDrawerItem(R.drawable.ic_action_share, "Main Screen");
drawerItem[1] = new ObjectDrawerItem(R.drawable.ic_action_share, "Augment Reality View");
drawerItem[2] = new ObjectDrawerItem(R.drawable.ic_action_share, "Mission Data");
drawerItem[3] = new ObjectDrawerItem(R.drawable.ic_action_share, "Settings");
// Pass the folderData to our ListView adapter
DrawerItemCustomAdapter adapter = new DrawerItemCustomAdapter(this, R.layout.listview_item_row, drawerItem);
// Set the adapter for the list view
mDrawerList.setAdapter(adapter);
// set the item click listener
mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
// for app icon control for nav drawer
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerToggle = new ActionBarDrawerToggle(
this, /* host Activity */
mDrawerLayout, /* DrawerLayout object */
R.drawable.ic_drawer, /* nav drawer icon to replace 'Up' caret */
R.string.drawer_open, /* "open drawer" description */
R.string.drawer_close /* "close drawer" description */
) {
/** Called when a drawer has settled in a completely closed state. */
public void onDrawerClosed(View view) {
super.onDrawerClosed(view);
getSupportActionBar().setTitle(mTitle);
}
/** Called when a drawer has settled in a completely open state. */
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
getSupportActionBar().setTitle(mDrawerTitle);
}
};
// Set the drawer toggle as the DrawerListener
mDrawerLayout.setDrawerListener(mDrawerToggle);
// enable ActionBar app icon to behave as action to toggle nav drawer
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
if (savedInstanceState == null) {
// on first time display view for first nav item
selectItem(0);
}
}
#Override
public void OnNewImageListenerBitmap(final Bitmap Image) {
if (Thread.currentThread().getName() == "main") {
Augmented_Reality_Fragment.UpdateImages(Image);
}
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
if (Augmented_Reality_Fragment != null) {
Augmented_Reality_Fragment.UpdateImages(Image);
}
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// The action bar home/up action should open or close the drawer.
// ActionBarDrawerToggle will take care of this.
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
// to change up caret
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mDrawerToggle.syncState();
}
// navigation drawer click listener
private class DrawerItemClickListener implements ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
selectItem(position);
}
}
private void selectItem(int position) {
Fragment fragment = null;
SharedPreferences.Editor editor = sharedpreferences.edit();
switch (position) {
case 0:
editor.putBoolean("Image_Listener", false);
editor.commit();
if (Main_Screen_Fragment == null) {
Main_Screen_Fragment = new Main_Screen();
}
fragment = Main_Screen_Fragment;
Current_Page = 1;
NewPage = true;
break;
case 1:
editor.putBoolean("Image_Listener", true);
editor.commit();
if (Augmented_Reality_Fragment == null) {
Augmented_Reality_Fragment = new Augmented_Reality();
}
fragment = new Augmented_Reality();
Current_Page = 2;
NewPage = true;
break;
case 2:
editor.putBoolean("Image_Listener", false);
editor.commit();
if (Mission_Data_Fragment == null) {
Mission_Data_Fragment = new Mission_Data();
}
fragment = Mission_Data_Fragment;
Current_Page = 3;
NewPage = true;
break;
case 3:
editor.putBoolean("Image_Listener", false);
editor.commit();
if (Settings_Fragment == null) {
Settings_Fragment = new Settings();
}
fragment = Settings_Fragment;
Current_Page = 4;
NewPage = true;
break;
default:
break;
}
if (fragment != null) {
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).commit();
// update selected item and title, then close the drawer
mDrawerList.setItemChecked(position, true);
mDrawerList.setSelection(position);
setTitle(mNavigationDrawerItemTitles[position]);
mDrawerLayout.closeDrawer(mDrawerList);
} else {
// error in creating fragment
Log.e("MainActivity", "Error in creating fragment");
}
}
#Override
public void setTitle(CharSequence title) {
mTitle = title;
getSupportActionBar().setTitle(mTitle);
}
#Override
public void onBackPressed() {
}
}
Thread on which Updated Interface:
if (Listener != null) {
System.out.println("Listener Found");
Image_data = BitmapFactory.decodeByteArray(tmp, 0, tmp.length);
System.out.println("Image Created");
Listener.OnNewImageListenerBitmap(Image_data);
//sendMessage(Image_Flag.to_byte_array(Image_Sync_Flag));
System.out.println("Updated");
}
Ive been stuck on this problem for a while now and im not sure whats going wrong, Any help would be awesome :)
Steve
///////////................\\\\\\
Added Crash log
08-02 01:16:29.997 26346-26346/com.interface E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ImageView.setImageDrawable(android.graphics.drawable.Drawable)' on a null object reference
at com.example.jaynesh.mobile_robot_interface.Fragments.Augmented_Reality.UpdateImages(Augmented_Reality.java:215)
at com.example.jaynesh.mobile_robot_interface.Main_Files.MainActivity$2.run(MainActivity.java:180)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5254)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)

EDIT: In your case 1, be sure to use the fragment that you had set earlier
You have:
if (Augmented_Reality_Fragment == null) {
Augmented_Reality_Fragment = new Augmented_Reality();
}
fragment = new Augmented_Reality();
You should have:
if (Augmented_Reality_Fragment == null) {
Augmented_Reality_Fragment = new Augmented_Reality();
}
fragment = Augmented_Reality_Fragment;

Related

Interstitial banner application

I have a application but i want use now interstitial banner.
Now it uses only the small banner.
I need to use an interstitial banner when the user opens my application.
But I cannot use with it in my app.
My question is; how to put an interstitial banner when the user opens my application?
I don't know how to push it.
This is my main activity
import android.content.Context;
import android.content.Intent;
import com.google.android.gms.ads.AdListener;
import com.google.android.gms.ads.AdRequest;
import com.google.android.gms.ads.InterstitialAd;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.MenuItem;
import android.view.View;
import com.google.android.gms.analytics.GoogleAnalytics;
import com.mycompany.krakowiewdk.CityGuideApplication;
import com.mycompany.krakowiewdk.R;
import com.mycompany.krakowiewdk.adapter.DrawerAdapter;
import com.mycompany.krakowiewdk.database.dao.CategoryDAO;
import com.mycompany.krakowiewdk.database.model.CategoryModel;
import com.mycompany.krakowiewdk.fragment.PoiListFragment;
import com.mycompany.krakowiewdk.listener.OnSearchListener;
import com.mycompany.krakowiewdk.utility.ResourcesHelper;
import com.mycompany.krakowiewdk.view.DrawerDividerItemDecoration;
import com.mycompany.krakowiewdk.view.ScrimInsetsFrameLayout;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends ActionBarActivity implements DrawerAdapter.CategoryViewHolder.OnItemClickListener, OnSearchListener {
private DrawerLayout mDrawerLayout;
private ActionBarDrawerToggle mDrawerToggle;
private ScrimInsetsFrameLayout mDrawerScrimInsetsFrameLayout;
private DrawerAdapter mDrawerAdapter;
private static final String ADMOB_INTERSTITIAL_UNIT_ID = "ca-app-pub-9431671174707107/7681038866";
private InterstitialAd mInterstitialAd;
private CharSequence mTitle;
private CharSequence mDrawerTitle;
private List<CategoryModel> mCategoryList;
public static Intent newIntent(Context context) {
Intent intent = new Intent(context, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
return intent;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setupActionBar();
setupRecyclerView();
setupDrawer(savedInstanceState);
// init analytics tracker
((CityGuideApplication) getApplication()).getTracker();
}
#Override
public void onStart() {
super.onStart();
// analytics
GoogleAnalytics.getInstance(this).reportActivityStart(this);
}
#Override
public void onResume() {
super.onResume();
}
#Override
public void onPause() {
super.onPause();
}
#Override
public void onStop() {
super.onStop();
// analytics
GoogleAnalytics.getInstance(this).reportActivityStop(this);
}
#Override
public void onDestroy() {
super.onDestroy();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// open or close the drawer if home button is pressed
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
// action bar menu behaviour
switch (item.getItemId()) {
default:
return super.onOptionsItemSelected(item);
}
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
mDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfiguration) {
super.onConfigurationChanged(newConfiguration);
mDrawerToggle.onConfigurationChanged(newConfiguration);
}
#Override
public void setTitle(CharSequence title) {
mTitle = title;
getSupportActionBar().setTitle(mTitle);
}
#Override
public void onItemClick(View view, int position, long id, int viewType) {
// position
int categoryPosition = mDrawerAdapter.getCategoryPosition(position);
selectDrawerItem(categoryPosition);
}
#Override
public void onSearch(String query) {
Fragment fragment = PoiListFragment.newInstance(query);
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.activity_main_container, fragment).commitAllowingStateLoss();
mDrawerAdapter.setSelected(mDrawerAdapter.getRecyclerPositionByCategory(0));
setTitle(getString(R.string.title_search) + ": " + query);
}
private void setupActionBar() {
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
ActionBar bar = getSupportActionBar();
bar.setDisplayUseLogoEnabled(false);
bar.setDisplayShowTitleEnabled(true);
bar.setDisplayShowHomeEnabled(true);
bar.setDisplayHomeAsUpEnabled(true);
bar.setHomeButtonEnabled(true);
}
private void setupRecyclerView() {
// reference
RecyclerView recyclerView = getRecyclerView();
// set layout manager
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
recyclerView.setLayoutManager(linearLayoutManager);
// load categories from database
loadCategoryList();
// set adapter
if (recyclerView.getAdapter() == null) {
// create adapter
mDrawerAdapter = new DrawerAdapter(mCategoryList, this);
} else {
// refill adapter
mDrawerAdapter.refill(mCategoryList, this);
}
recyclerView.setAdapter(mDrawerAdapter);
// add decoration
List<Integer> dividerPositions = new ArrayList<>();
dividerPositions.add(3);
RecyclerView.ItemDecoration itemDecoration = new DrawerDividerItemDecoration(
this,
null,
dividerPositions,
getResources().getDimensionPixelSize(R.dimen.global_spacing_xxs));
recyclerView.addItemDecoration(itemDecoration);
}
private void setupDrawer(Bundle savedInstanceState) {
mTitle = getTitle();
mDrawerTitle = getTitle();
// reference
mDrawerLayout = (DrawerLayout) findViewById(R.id.activity_main_layout);
mDrawerScrimInsetsFrameLayout = (ScrimInsetsFrameLayout) findViewById(R.id.activity_main_drawer);
// set drawer
mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
mDrawerLayout.setStatusBarBackgroundColor(ResourcesHelper.getValueOfAttribute(this, R.attr.colorPrimaryDark));
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.string.drawer_open, R.string.drawer_close) {
#Override
public void onDrawerClosed(View view) {
getSupportActionBar().setTitle(mTitle);
supportInvalidateOptionsMenu();
}
#Override
public void onDrawerOpened(View drawerView) {
getSupportActionBar().setTitle(mTitle);
supportInvalidateOptionsMenu();
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
// show initial fragment
if (savedInstanceState == null) {
selectDrawerItem(0);
}
}
private void selectDrawerItem(int position) {
Fragment fragment = PoiListFragment.newInstance(mCategoryList.get(position).getId());
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.activity_main_container, fragment).commitAllowingStateLoss();
mDrawerAdapter.setSelected(mDrawerAdapter.getRecyclerPositionByCategory(position));
setTitle(mCategoryList.get(position).getName());
mDrawerLayout.closeDrawer(mDrawerScrimInsetsFrameLayout);
}
private void loadCategoryList() {
try {
mCategoryList = CategoryDAO.readAll(-1l, -1l);
} catch (SQLException e) {
e.printStackTrace();
}
CategoryModel all = new CategoryModel();
all.setId(PoiListFragment.CATEGORY_ID_ALL);
all.setName(getResources().getString(R.string.drawer_category_all));
all.setImage("drawable://" + R.drawable.ic_category_all);
CategoryModel favorites = new CategoryModel();
favorites.setId(PoiListFragment.CATEGORY_ID_FAVORITES);
favorites.setName(getResources().getString(R.string.drawer_category_favorites));
favorites.setImage("drawable://" + R.drawable.ic_category_favorites);
mCategoryList.add(0, all);
mCategoryList.add(1, favorites);
}
private RecyclerView getRecyclerView() {
return (RecyclerView) findViewById(R.id.activity_main_drawer_recycler);
}
}
Issue is resolved, i put code in mainactivity and show fine.

intent to activity in Side-Menu.Android of material design

in https://github.com/Yalantis/Side-Menu.Android
please help me :(
How can when i click on each item in side menu, go to command "intent to other activity" instead of transport between images
import android.content.res.Configuration;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.animation.AccelerateInterpolator;
import android.widget.LinearLayout;
import java.util.ArrayList;
import java.util.List;
import io.codetail.animation.SupportAnimator;
import io.codetail.animation.ViewAnimationUtils;
import yalantis.com.sidemenu.interfaces.Resourceble;
import yalantis.com.sidemenu.interfaces.ScreenShotable;
import yalantis.com.sidemenu.model.SlideMenuItem;
import yalantis.com.sidemenu.sample.fragment.ContentFragment;
import yalantis.com.sidemenu.util.ViewAnimator;
public class MainActivity extends ActionBarActivity implements ViewAnimator.ViewAnimatorListener {
private DrawerLayout drawerLayout;
private ActionBarDrawerToggle drawerToggle;
private List<SlideMenuItem> list = new ArrayList<>();
private ContentFragment contentFragment;
private ViewAnimator viewAnimator;
private int res = R.drawable.content_music;
private LinearLayout linearLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
contentFragment = ContentFragment.newInstance(R.drawable.content_music);
getSupportFragmentManager().beginTransaction()
.replace(R.id.content_frame, contentFragment)
.commit();
drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
drawerLayout.setScrimColor(Color.TRANSPARENT);
linearLayout = (LinearLayout) findViewById(R.id.left_drawer);
linearLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
drawerLayout.closeDrawers();
}
});
setActionBar();
createMenuList();
viewAnimator = new ViewAnimator<>(this, list, contentFragment, drawerLayout, this);
}
private void createMenuList() {
SlideMenuItem menuItem0 = new SlideMenuItem(ContentFragment.CLOSE, R.drawable.icn_close);
list.add(menuItem0);
SlideMenuItem menuItem = new SlideMenuItem(ContentFragment.BUILDING, R.drawable.icn_1);
list.add(menuItem);
SlideMenuItem menuItem2 = new SlideMenuItem(ContentFragment.BOOK, R.drawable.icn_2);
list.add(menuItem2);
SlideMenuItem menuItem3 = new SlideMenuItem(ContentFragment.PAINT, R.drawable.icn_3);
list.add(menuItem3);
SlideMenuItem menuItem4 = new SlideMenuItem(ContentFragment.CASE, R.drawable.icn_4);
list.add(menuItem4);
SlideMenuItem menuItem5 = new SlideMenuItem(ContentFragment.SHOP, R.drawable.icn_5);
list.add(menuItem5);
SlideMenuItem menuItem6 = new SlideMenuItem(ContentFragment.PARTY, R.drawable.icn_6);
list.add(menuItem6);
SlideMenuItem menuItem7 = new SlideMenuItem(ContentFragment.MOVIE, R.drawable.icn_7);
list.add(menuItem7);
}
private void setActionBar() {
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setHomeButtonEnabled(true);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
drawerToggle = new ActionBarDrawerToggle(
this, /* host Activity */
drawerLayout, /* DrawerLayout object */
toolbar, /* nav drawer icon to replace 'Up' caret */
R.string.drawer_open, /* "open drawer" description */
R.string.drawer_close /* "close drawer" description */
) {
/** Called when a drawer has settled in a completely closed state. */
public void onDrawerClosed(View view) {
super.onDrawerClosed(view);
linearLayout.removeAllViews();
linearLayout.invalidate();
}
#Override
public void onDrawerSlide(View drawerView, float slideOffset) {
super.onDrawerSlide(drawerView, slideOffset);
if (slideOffset > 0.6 && linearLayout.getChildCount() == 0)
viewAnimator.showMenuContent();
}
/** Called when a drawer has settled in a completely open state. */
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
}
};
drawerLayout.setDrawerListener(drawerToggle);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
drawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
drawerToggle.onConfigurationChanged(newConfig);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (drawerToggle.onOptionsItemSelected(item)) {
return true;
}
switch (item.getItemId()) {
case R.id.action_settings:
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private ScreenShotable replaceFragment(ScreenShotable screenShotable, int topPosition) {
this.res = this.res == R.drawable.content_music ? R.drawable.content_films : R.drawable.content_music;
View view = findViewById(R.id.content_frame);
int finalRadius = Math.max(view.getWidth(), view.getHeight());
SupportAnimator animator = ViewAnimationUtils.createCircularReveal(view, 0, topPosition, 0, finalRadius);
animator.setInterpolator(new AccelerateInterpolator());
animator.setDuration(ViewAnimator.CIRCULAR_REVEAL_ANIMATION_DURATION);
findViewById(R.id.content_overlay).setBackgroundDrawable(new BitmapDrawable(getResources(), screenShotable.getBitmap()));
animator.start();
ContentFragment contentFragment = ContentFragment.newInstance(this.res);
getSupportFragmentManager().beginTransaction().replace(R.id.content_frame, contentFragment).commit();
return contentFragment;
}
#Override
public ScreenShotable onSwitch(Resourceble slideMenuItem, ScreenShotable screenShotable, int position) {
switch (slideMenuItem.getName()) {
case ContentFragment.CLOSE:
return screenShotable;
default:
return replaceFragment(screenShotable, position);
}
}
#Override
public void disableHomeButton() {
getSupportActionBar().setHomeButtonEnabled(false);
}
#Override
public void enableHomeButton() {
getSupportActionBar().setHomeButtonEnabled(true);
drawerLayout.closeDrawers();
}
#Override
public void addViewToContainer(View view) {
linearLayout.addView(view);
}
}
Very Thanks for All
Hi currently I also using that library. I've attached my working code.
(In this case im using fragment)
Go and find how to use startActivity then you can use Intent & putExtra your resId.
#Override
public ScreenShotable onSwitch(Resourceble resourceble, ScreenShotable screenShotable, int position) {
int primaryColorCanvas = R.color.colorPrimary;
switch (resourceble.getName()) {
case ContentFragment.CLOSE:
return screenShotable;
case ContentFragment.DASHBOARD:
DashboardFragment fragment = DashboardFragment.newInstance(primaryColorCanvas);
getSupportFragmentManager().beginTransaction().replace(R.id.content_frame, fragment).commit();
return replaceFragment(fragment, position);
case ContentFragment.FRIDGE:
FridgeFragment fragment2 = FridgeFragment.newInstance(primaryColorCanvas);
getSupportFragmentManager().beginTransaction().replace(R.id.content_frame, fragment2).commit();
return replaceFragment(fragment2, position);
case ContentFragment.COOKBOOK:
DashboardFragment fragment3 = DashboardFragment.newInstance(primaryColorCanvas);
getSupportFragmentManager().beginTransaction().replace(R.id.content_frame, fragment3).commit();
return replaceFragment(fragment3, position);
case ContentFragment.SHOPPINGLIST:
case ContentFragment.FEEDBACK:
ContentFragment fragment4 = ContentFragment.newInstance(primaryColorCanvas);
getSupportFragmentManager().beginTransaction().replace(R.id.content_frame,fragment4).commit();
return replaceFragment(fragment4, position);
default:
ContentFragment fragment0 = ContentFragment.newInstance(primaryColorCanvas);
getSupportFragmentManager().beginTransaction().replace(R.id.content_frame,fragment0).commit();
return replaceFragment(fragment0, position);
}
}
private ScreenShotable replaceFragment(ScreenShotable screenShotable, int position) {
int finalRadius = Math.max(contentFrame.getWidth(), contentFrame.getHeight());
SupportAnimator animator = ViewAnimationUtils.createCircularReveal(contentFrame, 0, position, 0, finalRadius);
animator.setInterpolator(new AccelerateInterpolator());
animator.setDuration(ViewAnimator.CIRCULAR_REVEAL_ANIMATION_DURATION);
findViewById(R.id.content_overlay).setBackground(new BitmapDrawable(getResources(), screenShotable.getBitmap()));
animator.start();
return screenShotable;
}
private void initializedMenu() {
SlideMenuItem menuItem0 = new SlideMenuItem(contentFragment.CLOSE, R.drawable.back_btn);
list.add(menuItem0);
SlideMenuItem menuItem = new SlideMenuItem(contentFragment.DASHBOARD, R.drawable.dashboard_icon_a);
list.add(menuItem);
SlideMenuItem menuIte2 = new SlideMenuItem(contentFragment.FRIDGE, R.drawable.fridge_icon_a);
list.add(menuIte2);
SlideMenuItem menuItem3 = new SlideMenuItem(contentFragment.COOKBOOK, R.drawable.cookbook_icon_a);
list.add(menuItem3);
SlideMenuItem menuItem4 = new SlideMenuItem(contentFragment.SHOPPINGLIST, R.drawable.right_icon_a);
list.add(menuItem4);
SlideMenuItem menuItem5 = new SlideMenuItem(contentFragment.FEEDBACK, R.drawable.feedback_icon_a);
list.add(menuItem5);
}
Remember that I've assigned static string variable in ContentFragment.
You can see at the initializedMenu().
Hope that help!

How to refer to a fragment within a ViewPager with FragmentManager?

So I've been working on a basic weather app for android, and after implementing a viewpager with tabs the app throws a NullPointerException every time I try to use the changeCity method within the main activity; this needs to refer to the fragment and since I have changed the way the fragment is instantiated I have no clue how to do this.
My main activity:
import android.app.AlertDialog;
import android.support.v4.app.FragmentManager;
import android.content.DialogInterface;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.InputType;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.EditText;
import android.widget.RelativeLayout;
public class WeatherActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_weather);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout);
tabLayout.addTab(tabLayout.newTab().setText("Current Weather"));
tabLayout.addTab(tabLayout.newTab().setText("Forecast"));
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
final ViewPager viewPager = (ViewPager) findViewById(R.id.pager);
final PagerAdapter adapter = new PagerAdapter
(getSupportFragmentManager(), tabLayout.getTabCount());
viewPager.setAdapter(adapter);
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
tabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
/*if(savedInstanceState == null){
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new WeatherFragment())
.commit();
}*/
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_weather, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.change_city) {
showInputDialog();
}
return false;
}
private void showInputDialog(){
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Change city");
final EditText input = new EditText(this);
input.setInputType(InputType.TYPE_CLASS_TEXT);
builder.setView(input);
builder.setPositiveButton("Go", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
changeCity(input.getText().toString());
}
});
builder.show();
}
public void changeCity(String city){
FragmentManager fm = getSupportFragmentManager();
WeatherFragment wf = (WeatherFragment)fm.findFragmentById(R.id.fragment_weather);
//EXCEPTION IS THROWN HERE
wf.changeCity(city);
new CityPreference(this).setCity(city);
}
public void changeBackground(String timeOfDay) {
String day = "DAY";
String dusk = "DUSK";
String night = "NIGHT";
RelativeLayout layout = (RelativeLayout) findViewById(R.id.container);
if (timeOfDay.equals(day)) {
layout.setBackgroundColor(getResources().getColor(R.color.background_day));
//setTheme(R.style.CustomAppTheme_NoActionBarTitle_Day);
} else if(timeOfDay.equals(dusk)){
layout.setBackgroundColor(getResources().getColor(R.color.background_dusk));
//setTheme(R.style.CustomAppTheme_NoActionBarTitle_Dusk);
} else if(timeOfDay.equals(night)){
layout.setBackgroundColor(getResources().getColor(R.color.background_night));
//setTheme(R.style.CustomAppTheme_NoActionBarTitle_Night);
}
}
}
My PagerAdapter class where the fragments get instantiated:
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
/**
* Created by User on 31/08/2015.
*/
public class PagerAdapter extends FragmentStatePagerAdapter {
int mNumOfTabs;
public PagerAdapter(FragmentManager fm, int NumOfTabs){
super(fm);
this.mNumOfTabs = NumOfTabs;
}
#Override
public Fragment getItem(int position) {
switch (position) {
case 0:
WeatherFragment tab1 = new WeatherFragment();
return tab1;
case 1:
ForecastFragment tab2 = new ForecastFragment();
return tab2;
default:
return null;
}
}
#Override
public int getCount() {
return mNumOfTabs;
}
}
The WeatherFragment class:
import android.graphics.Typeface;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;
import android.os.Handler;
import org.json.JSONObject;
import java.text.DateFormat;
import java.util.Date;
import java.util.Locale;
/**
* Weather app fragment, handles the display of all elements within the FrameLayout of the main
* activity.
*/
public class WeatherFragment extends Fragment {
public static final String TAG = "SimpleWeather Fragment";
Typeface weatherFont;
TextView cityField;
TextView updatedField;
TextView localTimeField;
TextView detailsField;
TextView currentTemperatureField;
TextView weatherIcon;
ImageButton refreshButton;
Handler handler;
public WeatherFragment(){
handler = new Handler();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_weather, container, false);
cityField = (TextView)rootView.findViewById(R.id.city_field);
updatedField = (TextView)rootView.findViewById(R.id.updated_field);
localTimeField = (TextView)rootView.findViewById(R.id.local_time_field);
detailsField = (TextView)rootView.findViewById(R.id.details_field);
currentTemperatureField = (TextView)rootView.findViewById(R.id.current_temperature_field);
weatherIcon = (TextView)rootView.findViewById(R.id.weather_icon);
refreshButton = (ImageButton)rootView.findViewById(R.id.refresh_button);
refreshButton.setOnClickListener(new View.OnClickListener(){
public void onClick(View v) {
updateWeatherData(new CityPreference(getActivity()).getCity());
}
});
weatherIcon.setTypeface(weatherFont);
return rootView;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
weatherFont = Typeface.createFromAsset(getActivity().getAssets(), "fonts/weather.ttf");
updateWeatherData(new CityPreference(getActivity()).getCity());
}
private void updateWeatherData(final String city){
new Thread(){
public void run(){
final JSONObject json = RemoteFetch.getJSON(getActivity(), city);
if (json == null){
handler.post(new Runnable(){
public void run(){
Toast.makeText(getActivity(),
getActivity().getString(R.string.place_not_found),
Toast.LENGTH_LONG).show();
}
});
} else {
handler.post(new Runnable(){
#Override
public void run() {
renderWeather(json);
}
});
}
}
}.start();
}
private void renderWeather(JSONObject json){
try {
cityField.setText(json.getString("name").toUpperCase(Locale.UK) +
"," +
json.getJSONObject("sys").getString("country"));
JSONObject details = json.getJSONArray("weather").getJSONObject(0);
JSONObject main = json.getJSONObject("main");
detailsField.setText(
details.getString("description").toUpperCase(Locale.UK) +
"\n" + "Humidity: " + main.getString("humidity") + "%" +
"\n" + "Pressure: " + main.getString("pressure") + "hPa");
currentTemperatureField.setText(
String.format("%.2f", main.getDouble("temp")) + " ℃");
DateFormat df = DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.MEDIUM);
String updatedOn = df.format(new Date(json.getLong("dt") * 1000));
updatedField.setText("Last update: " + updatedOn);
/* TODO local time field */
setWeatherIcon(details.getInt("id"),
json.getJSONObject("sys").getLong("sunrise") * 1000,
json.getJSONObject("sys").getLong("sunset") * 1000);
String t = new TimeOfDay().getTimeOfDay(
json.getJSONObject("sys").getLong("sunrise") * 1000,
json.getJSONObject("sys").getLong("sunset") * 1000);
((WeatherActivity)getActivity()).changeBackground(t);
}catch (Exception e) {
Log.e("SimpleWeather", "One or more fields not found in JSON data");
}
}
private void setWeatherIcon(int id, long sunrise, long sunset){
int shortId = id / 100;
long currentTime = new Date().getTime();
String icon = "";
if(id==800 || id==801 || id==802 || id==803 || shortId==3){
if (currentTime>=sunrise && currentTime<sunset) {
if(shortId==3){
icon = getActivity().getString(R.string.weather_day_showers);
} else {
switch (id) {
case 800 : icon = getActivity().getString(R.string.weather_sunny);
break;
case 801 : icon = getActivity().getString(R.string.weather_day_few_clouds);
break;
case 802: icon = getActivity().getString(R.string.weather_day_overcast);
break;
case 803: icon = getActivity().getString(R.string.weather_day_overcast);
break;
}
}
} else {
if (shortId==3){
icon = getActivity().getString(R.string.weather_night_showers);
} else {
switch (id) {
case 800: icon = getActivity().getString(R.string.weather_clear_night);
break;
case 801: icon = getActivity().getString(R.string.weather_night_few_clouds);
break;
case 802: icon = getActivity().getString(R.string.weather_night_overcast);
break;
case 803: icon = getActivity().getString(R.string.weather_night_overcast);
break;
}
}
}
} else {
switch (shortId) {
case 2 : icon = getActivity().getString(R.string.weather_thunder);
break;
case 7 : icon = getActivity().getString(R.string.weather_foggy);
break;
case 8 : icon = getActivity().getString(R.string.weather_cloudy);
break;
case 6 : icon = getActivity().getString(R.string.weather_snowy);
break;
case 5 : icon = getActivity().getString(R.string.weather_rainy);
break;
}
}weatherIcon.setText(icon);
}
public void changeCity(String city){
updateWeatherData(city);
}
}
And the LogCat:
08-31 14:57:15.704 15649-15649/simpleweather.ockmore.will.simpleweather E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: simpleweather.ockmore.will.simpleweather, PID: 15649
java.lang.NullPointerException: Attempt to invoke virtual method 'void simpleweather.ockmore.will.simpleweather.WeatherFragment.changeCity(java.lang.String)' on a null object reference
at simpleweather.ockmore.will.simpleweather.WeatherActivity.changeCity(WeatherActivity.java:95)
at simpleweather.ockmore.will.simpleweather.WeatherActivity$2.onClick(WeatherActivity.java:84)
at com.android.internal.app.AlertController$ButtonHandler.handleMessage(AlertController.java:162)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5343)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:905)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:700)
The Fragments are auto Tagged by the ViewPager
private static String makeFragmentName(int viewPagerId, int index) {
return "android:switcher:" + viewPagerId + ":" + index;
}
see Android getting fragment that is in FragmentPagerAdapter

Android su commands not working when called for modifying /system in android

What i basically have is a simple android navigation drawer with some fragments , i have a checkbox called from a Fragment placed in the main activity which then when clicked executes a root command that should modify the build.prop file in /system but unfortunately it doesn't seem to work and i get this in the logs -->
D/su (17546): su invoked.
D/su (17546): starting daemon client 10129 10129
D/su (17548): remote pid: 17546
D/su (17548): remote pts_slave:
D/su (17548): waiting for child exit
D/su (17550): su invoked.
D/su (17550): db allowed
D/su (17550): 10129 /system/xbin/su executing 0 /system/bin/sh using binary
/system/bin/sh : sh
D/su (17548): sending code
D/su (17548): child exited
D/su (17546): client exited 0
D/AndroidRuntime(17551):
D/AndroidRuntime(17551): >>>>>> AndroidRuntime START com.android.internal.os.Run
timeInit <<<<<<
D/AndroidRuntime(17551): CheckJNI is OFF
D/AndroidRuntime(17551): Calling main entry com.android.commands.am.Am
here is the code of my Activity (AboutActivity)
package com.adromo.tweaker.activities;
import android.app.ActionBar;
import android.app.Fragment;
import android.app.FragmentManager;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.res.AssetManager;
import android.content.res.Configuration;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.view.GravityCompat;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.ListView;
import android.widget.Toast;
import com.adromo.tweaker.R;
import com.adromo.tweaker.fragments.InitD;
import com.adromo.tweaker.fragments.StartFragment;
import com.adromo.tweaker.widget.CustomDrawerLayout;
import com.ikimuhendis.ldrawer.ActionBarDrawerToggle;
import com.ikimuhendis.ldrawer.DrawerArrowDrawable;
import org.sufficientlysecure.rootcommands.Shell;
import org.sufficientlysecure.rootcommands.command.SimpleCommand;
import java.io.BufferedOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.concurrent.TimeoutException;
public class AboutActivity extends FragmentActivity {
public static Context appContext;
//==================================
// Drawer
//==================================
private static final String STATE_SELECTED_POSITION = "selected_navigation_drawer_position";
private ActionBarDrawerToggle mDrawerToggle;
private CustomDrawerLayout mDrawerLayout;
private ListView mDrawerListView;
private View mFragmentContainerView;
private int mCurrentSelectedPosition = 0;
private boolean mFromSavedInstanceState;
private ListView mDrawerList;
private DrawerArrowDrawable drawerArrow;
private boolean drawerArrowColor;
private static int DRAWER_MODE = 0;
private SharedPreferences mPreferences;
private static final int MENU_BACK = Menu.FIRST;
String titleString[];
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
appContext = getApplicationContext();
setContentView(R.layout.drawer_main);
mDrawerListView = (ListView) findViewById(R.id.dw_navigation_drawer);
mDrawerListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
selectItem(position);
}
});
mDrawerListView.setAdapter(new ArrayAdapter<String>(
getActionBar().getThemedContext(),
R.layout.drawer_list,
android.R.id.text1,
getTitles()));
mDrawerListView.setItemChecked(mCurrentSelectedPosition, true);
setUpNavigationDrawer(
findViewById(R.id.dw_navigation_drawer),
(CustomDrawerLayout) findViewById(R.id.dw_drawer_layout));
ActionBar ab = getActionBar();
ab.setDisplayHomeAsUpEnabled(true);
ab.setHomeButtonEnabled(true);
if (savedInstanceState != null) {
mCurrentSelectedPosition = savedInstanceState.getInt(STATE_SELECTED_POSITION);
mFromSavedInstanceState = true;
}
File folder = new File(Environment.getExternalStorageDirectory() + "/Adromo");
boolean success = true;
if (!folder.exists()) {
success = folder.mkdir();
}
CopyAssets();
}
private void CopyAssets() {
AssetManager assetManager = getAssets();
String[] files = null;
try {
files = assetManager.list("Files");
} catch (IOException e) {
Log.e("tag", e.getMessage());
}
for(String filename : files) {
System.out.println("File name => "+filename);
InputStream in = null;
OutputStream out = null;
try {
in = assetManager.open("Files/"+filename); // if files resides inside the "Files" directory itself
out = new FileOutputStream("/sdcard/Adromo/" + filename );
copyFile(in, out);
in.close();
in = null;
out.flush();
out.close();
out = null;
} catch(Exception e) {
Log.e("tag", e.getMessage());
}
}
}
private void copyFile(InputStream in, OutputStream out) throws IOException {
byte[] buffer = new byte[1024];
int read;
while((read = in.read(buffer)) != -1){
out.write(buffer, 0, read);
}
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
mDrawerToggle.onConfigurationChanged(newConfig);
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt(STATE_SELECTED_POSITION, mCurrentSelectedPosition);
}
#Override
public void onResume() {
super.onResume();
}
#Override
public void onPause() {
super.onPause();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
menu.add(0, MENU_BACK, 0, R.string.toggle_back_cfibers)
.setIcon(R.drawable.ic_back)
.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS | MenuItem.SHOW_AS_ACTION_WITH_TEXT);
restoreActionBar();
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
switch (item.getItemId()) {
case MENU_BACK:
onBackPressed();
return true;
default:
return super.onContextItemSelected(item);
}
}
//==================================
// Methods
//==================================
/**
* Users of this fragment must call this method to set up the
* navigation menu_drawer interactions.
*
* #param fragmentContainerView The view of this fragment in its activity's layout.
* #param drawerLayout The DrawerLayout containing this fragment's UI.
*/
public void setUpNavigationDrawer(View fragmentContainerView, CustomDrawerLayout drawerLayout) {
mFragmentContainerView = fragmentContainerView;
mDrawerLayout = drawerLayout;
mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
drawerArrow = new DrawerArrowDrawable(this) {
#Override
public boolean isLayoutRtl() {
return false;
}
};
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
drawerArrow, R.string.navigation_drawer_open,
R.string.navigation_drawer_close) {
public void onDrawerClosed(View view) {
super.onDrawerClosed(view);
invalidateOptionsMenu();
}
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
invalidateOptionsMenu();
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
mDrawerToggle.syncState();
mDrawerToggle.setDrawerIndicatorEnabled(true);
if (!mFromSavedInstanceState) {
mDrawerLayout.openDrawer(mFragmentContainerView);
}
mDrawerLayout.post(new Runnable() {
#Override
public void run() {
mDrawerToggle.syncState();
}
});
mDrawerLayout.setDrawerListener(mDrawerToggle);
selectItem(mCurrentSelectedPosition);
}
public boolean isDrawerOpen() {
return mDrawerLayout != null && mDrawerLayout.isDrawerOpen(mFragmentContainerView);
}
/**
* Restores the action bar after closing the menu_drawer
*/
public void restoreActionBar() {
ActionBar actionBar = getActionBar();
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
actionBar.setDisplayShowTitleEnabled(false);
actionBar.setTitle(getTitle());
}
private void selectItem(int position) {
mCurrentSelectedPosition = position;
if (mDrawerListView != null) {
mDrawerListView.setItemChecked(position, true);
}
if (mDrawerLayout != null) {
mDrawerLayout.closeDrawer(mFragmentContainerView);
}
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.dw_container, PlaceholderFragment.newInstance(getPosition(position)))
.commit();
}
/**
* Depending on if the item is shown or not, it increases
* the position to make the activity load the right fragment.
*
* #param pos The selected position
* #return the modified position
*/
public int getPosition(int pos) {
int position = pos;
switch (DRAWER_MODE) {
default:
case 0:
position = pos;
break;
case 1:
if (pos > 0) position = pos + 1;
break;
case 2:
if (pos > 3) position = pos + 1;
break;
case 3:
if (pos > 0) position = pos + 1;
if (pos > 3) position = pos + 2;
break;
}
return position;
}
/**
* Get a list of titles for the tabstrip to display depending on if the
* voltage control fragment and battery fragment will be displayed. (Depends on the result of
* Helpers.voltageTableExists() & Helpers.showBattery()
*
* #return String[] containing titles
*/
private String[] getTitles() {
String titleString[];
DRAWER_MODE = 0;
titleString = new String[]{
getString(R.string.start_title),
getString(R.string.navdraw_initd),};
return titleString;
}
//==================================
// Internal Classes
//==================================
public static final int FRAGMENT_ID_StartFragment = 0;
public static final int FRAGMENT_ID_InitD = 1;
public static class PlaceholderFragment extends Fragment {
/**
* Returns a new instance of this fragment for the given section
* number.
*/
public static Fragment newInstance(int fragmentId) {
Fragment fragment;
switch (fragmentId) {
default:
case FRAGMENT_ID_StartFragment:
fragment = new StartFragment();
break;
case FRAGMENT_ID_InitD:
fragment = new InitD();
break;
}
return fragment;
}
public PlaceholderFragment() {
// intentionally left blank
}
}
// begin initd checkboxes
public void initd1(View view) {
// Is the view now checked?
boolean checked = ((CheckBox) view).isChecked();
// Check which checkbox was clicked
switch(view.getId()) {
case R.id.initd1:
if (checked){
try {
Shell shell = Shell.startRootShell();
SimpleCommand command2 = new SimpleCommand("su -c cp /system/build.prop /system/build.prop.bak");
shell.add(command2).waitForFinish();
shell.close();
} catch (IOException e) {
e.printStackTrace();
} catch (TimeoutException e) {
e.printStackTrace();
}
} else {
Toast.makeText(getApplicationContext(), "LOL",
Toast.LENGTH_SHORT).show();
}
// Remove the meat
break;
}
}
}
here is the code of my fragment
/*
* Copyright (C) 2013 Carbon Development
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.adromo.tweaker.fragments;
import android.os.Bundle;
import android.preference.PreferenceFragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.adromo.tweaker.R;
public class InitD extends PreferenceFragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.initd, container, false);
}
}
the library i am using is called rootcommands (i think this shouldn't matter as every library i try gives me the same exact result)
i am running android lolipop 5.0.1 on an SGS4
Make sure you have mounted /system as read-write.
Run this command for mounting r/w:
mount -o remount,rw /system
And for mounting read-only again do:
mount -o remount,ro /system
Never forget this or you cannot write to /system.

Android:Painting in FragmentClass

I am using navigationdrawer in an activity.If I click any of the item in the navigation drawer
in default with some color it should allow us to paint some thing.But I tried for a long time i was unable to do it.Kindly hep as soon as possible.Below is my code which i am using.
Painting.java
package com.example.painturselfnew;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.widget.DrawerLayout;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
#TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
public class Painting extends Activity {
private ListView mdrawerlist;
private DrawerLayout mdrawerlayout;
private ActionBarDrawerToggle mDrawerToggle;
private CharSequence mdrawertitle;
private CharSequence mtitle;
private String[] mfragmenttitles;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_painting);
mtitle = mdrawertitle = getTitle();
mfragmenttitles = getResources().getStringArray(R.array.widgets);
mdrawerlayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mdrawerlist = (ListView) findViewById(R.id.left_drawer);
mdrawerlist.setAdapter(new ArrayAdapter<String>(this,
R.layout.drawer_list_item, mfragmenttitles));
getActionBar().setDisplayShowHomeEnabled(true);
getActionBar().setDisplayHomeAsUpEnabled(true);
mdrawerlist.setOnItemClickListener(new DrawerItemClickListener());
mDrawerToggle = new ActionBarDrawerToggle(this, mdrawerlayout,
R.drawable.ic_launcher, R.string.drawer_open,
R.string.drawer_close) {
public void onDrawerClosed(View view) {
getActionBar().setTitle(mtitle);
invalidateOptionsMenu();
}
public void onDrawerOpened(View drawerView) {
getActionBar().setTitle(mdrawertitle);
invalidateOptionsMenu();
}
};
mdrawerlayout.setDrawerListener(mDrawerToggle);
if (savedInstanceState == null) {
selectItem(0);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.painting, menu);
return true;
}
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
boolean draweropen = mdrawerlayout.isDrawerOpen(mdrawerlist);
menu.findItem(R.id.action_settings).setVisible(!draweropen);
return super.onPrepareOptionsMenu(menu);
}
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_settings:
if (mdrawerlayout.isDrawerOpen(mdrawerlist)) {
mdrawerlayout.closeDrawer(mdrawerlist);
} else {
mdrawerlayout.openDrawer(mdrawerlist);
}
mdrawerlayout.openDrawer(mdrawerlist);
/*
* Toast.makeText(getApplicationContext(), "Options Selected",
* Toast.LENGTH_LONG).show();
*/
return true;
case android.R.id.home:
startActivity(new Intent(Painting.this, MainActivity.class));
break;
default:
return super.onOptionsItemSelected(item);
}
return true;
}
private class DrawerItemClickListener implements
ListView.OnItemClickListener {
public void onItemClick(AdapterView<?> parent, View v, int position,
long id) {
selectItem(position);
}
}
private void selectItem(int position) {
Fragment fragment = new Fragment();
Bundle args = new Bundle();
// args.putInt(Fragment.ARG_PLANET_NUMBER, position);
fragment.setArguments(args);
FragmentManager fragmentManager = getFragmentManager();
switch (position) {
case 0:
fragment = new Fragment1();
Toast.makeText(getApplicationContext(), "Camera Selected",
Toast.LENGTH_LONG).show();
break;
case 1:
fragment = new Fragment2();
Toast.makeText(getApplicationContext(), "Color Selected",
Toast.LENGTH_LONG).show();
break;
case 2:
/*
* PaintFragment fragment1; fragment1 = new PaintFragment();
*/
PaintFragment fragment1 = new PaintFragment();
Toast.makeText(getApplicationContext(), "Paint Selected",
Toast.LENGTH_LONG).show();
break;
case 3:
fragment = new Fragment4();
Toast.makeText(getApplicationContext(), "Save selected",
Toast.LENGTH_LONG).show();
break;
case 4:
fragment = new Fragment5();
Toast.makeText(getApplicationContext(), "Share Selected",
Toast.LENGTH_LONG).show();
break;
case 5:
fragment = new Fragment6();
Toast.makeText(getApplicationContext(), "ArtBy Selected",
Toast.LENGTH_LONG).show();
break;
case 6:
fragment = new Fragment7();
Toast.makeText(getApplicationContext(), "Refresh Selected",
Toast.LENGTH_LONG).show();
break;
}
fragmentManager.beginTransaction()
.replace(R.id.content_frame, fragment).commit();
mdrawerlist.setItemChecked(position, true);
setTitle(mfragmenttitles[position]);
mdrawerlayout.closeDrawer(mdrawerlist);
}
#Override
public void setTitle(CharSequence title) {
mtitle = title;
getActionBar().setTitle(mtitle);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Pass any configuration change to the drawer toggls
mDrawerToggle.onConfigurationChanged(newConfig);
}
}
PainitngFragment.java
package com.example.painturselfnew;
import android.annotation.TargetApi;
import android.app.ActionBar.LayoutParams;
import android.app.Activity;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.os.Build;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
public class PaintFragment extends Activity {
/*private static int displayWidth = 0;
private static int displayHeight = 0;
*/
/*
* #Override public void onCreate(Bundle savedInstanceState) {
* super.onCreate(savedInstanceState);
* //setContentView(R.layout.activity_fragment3); //setContentView(new
* MyView(this));
*
*
* }
*/
/*public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {*/
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
BrushView view=new BrushView(this);
setContentView(view);
addContentView(view.btnEraseAll, view.params);
/*
* View view = inflater.inflate(R.layout.activity_fragment3, container,
* false);
*/
// getActivity();
/*
* Display display =
* ((WindowManager)this.getSystemService(Context.WINDOW_SERVICE
* )).getDefaultDisplay(); displayWidth = display.getWidth();
* displayHeight = display.getHeight();
*/
//ImageView iv = (ImageView) view.findViewById(R.id.imageView1);
/*
* iv.setOnClickListener(new View.OnClickListener() {
*
* #Override public void onClick(View arg0) { // TO DO Auto-generated
* method stub
*
* BrushView view = new BrushView(getActivity()); //setContentView(new
* BrushView(this)); } });
*/
//return view;
}
#Override
protected void onPause() {
super.onPause();
finish();
}
public class BrushView extends View {
private Paint brush = new Paint();
private Path path = new Path();
public Button btnEraseAll;
public LayoutParams params;
public BrushView(Context paintFragment) {
super(paintFragment);
brush.setAntiAlias(true);
brush.setColor(Color.BLUE);
brush.setStyle(Paint.Style.STROKE);
brush.setStrokeJoin(Paint.Join.ROUND);
brush.setStrokeWidth(15f);
btnEraseAll = new Button(paintFragment);
btnEraseAll.setText("Erase Everything!!");
params = new LayoutParams(LayoutParams.MATCH_PARENT,
LayoutParams.WRAP_CONTENT);
btnEraseAll.setLayoutParams(params);
btnEraseAll.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// reset the path
path.reset();
// invalidate the view
postInvalidate();
}
});
}
#Override
public boolean onTouchEvent(MotionEvent event) {
float pointX = event.getX();
float pointY = event.getY();
// Checks for the event that occurs
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
path.moveTo(pointX, pointY);
return true;
case MotionEvent.ACTION_MOVE:
path.lineTo(pointX, pointY);
break;
case MotionEvent.ACTION_UP:
break;
default:
return false;
}
// Force a view to draw.
postInvalidate();
return false;
}
#Override
protected void onDraw(Canvas canvas) {
canvas.drawPath(path, brush);
}
}
}
Thanks In Advance...

Categories