out of memory in MainActivity - android

Our application android use a lot of memory in MainActivity ( 32MB )
we don't know how to detect and specify where is exactly the problem
we try to comment all the code in MainActivity but No solution
Can someone help us to detect where the solution exactly in our Code ?
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
private ArrayList<String> CodeBar = new ArrayList<>();
private ArrayList<Integer> id_Four = new ArrayList<>() ;
private ArrayList<String> nomProd = new ArrayList<>() ;
private ArrayList<String> prix = new ArrayList<>() ;
private ArrayList<String> nomFour = new ArrayList<>() ;
private ArrayList<String> adresse = new ArrayList<>() ;
private ArrayList<String> tel = new ArrayList<>() ;
private ArrayList<String> description = new ArrayList<>() ;
private ArrayList<Float> ratings = new ArrayList<>() ;
private ArrayList<Integer> images;
private BitmapFactory.Options options;
private ViewPager viewPager;
private View btnNext, btnPrev;
private FragmentStatePagerAdapter adapter;
private LinearLayout thumbnailsContainer;
private ShineButton deleteLast;
private final static ArrayList<Integer> resourceIDs = new ArrayList<>();
Intent historiqueIntent;
Activity activity;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
TextView title = (TextView) findViewById(R.id.title_promo);
title.setTypeface(title.getTypeface(), Typeface.ITALIC);
deleteLast =(ShineButton)findViewById(R.id.deleteAll);
final MaterialSpinner spinner_search = (MaterialSpinner) findViewById(R.id.spinner);
// final Spinner spinner_search = (Spinner) findViewById(R.id.spinner);
ShineButton btn_search = (ShineButton) findViewById(R.id.searchView);
// spinner_search.setDropdownHeight(1000);
spinner_search.setDropdownMaxHeight(1000);
historiqueIntent = new Intent(MainActivity.this , Histourique.class);
//ArrayAdapter adapter = ArrayAdapter.createFromResource(this,R.array.Ville,android.R.layout.simple_spinner_dropdown_item);
// spinner_search.setAdapter(adapter);
VilleRemember vill = new VilleRemember(getBaseContext() , "" , 0 );
spinner_search.setSelectedIndex(vill.getindiceSelected());
spinner_search.setOnItemSelectedListener(new MaterialSpinner.OnItemSelectedListener<String>() {
#Override public void onItemSelected(MaterialSpinner view, int position, long id, String item) {
VilleRemember vill = new VilleRemember(getBaseContext() , item,position );
vill.newSelectedVille(position,item);
}
});
btn_search.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(historiqueIntent);}});
activity=this;
final FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
//rotateAnimation(fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
lanceScane(activity);
}
});
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
#Override
protected void onResume()
{
// System.gc();
super.onResume();
}
//////////////////////////////////////
Timer timer;
int page = 1;
public void pageSwitcher(int seconds) {
timer = new Timer(); // At this line a new Thread will be created
timer.scheduleAtFixedRate(new RemindTask(), 0, seconds * 1000); // delay
// in
// milliseconds
}
// this is an inner class...
class RemindTask extends TimerTask {
#Override
public void run() {
// As the TimerTask run on a seprate thread from UI thread we have
// to call runOnUiThread to do work on UI thread.
runOnUiThread(new Runnable() {
public void run() {
if (page >= 4) { // In my case the number of pages are 5
// timer.cancel();
page = 0;
// viewPager.setCurrentItem(page--);
// Showing a toast for just testing purpose
/* Toast.makeText(getApplicationContext(), "Timer stoped",
Toast.LENGTH_LONG).show(); */
} else {
viewPager.setCurrentItem(page++);
}
}
});
}
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
// getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.accueil) {
// Handle the camera action
} else if (id == R.id.historique) {
Intent i = new Intent(this , Histourique.class);
startActivity(i);
} else if (id == R.id.prefere) {
Intent i = new Intent(this , Fav_class.class);
startActivity(i);
//overridePendingTransition(R.anim.slide_in_bottom,R.anim.slide_out_bottom);
} else if (id == R.id.parametre) {
Intent i = new Intent(this , Parametres.class);
startActivity(i);
} else if (id == R.id.propose_nous) {
startActivity(new Intent(MainActivity.this, About_us.class));
finish();
} else if (id == R.id.contactez_nous) {
Intent i = new Intent(this , contact_us.class);
startActivity(i);
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
public void lanceScane(Activity activity)
{
IntentIntegrator integrator = new IntentIntegrator(activity);
integrator.setDesiredBarcodeFormats(IntentIntegrator.ALL_CODE_TYPES);
integrator.setPrompt("Scanner");
integrator.setCameraId(0);
integrator.setBeepEnabled(true);
integrator.setBarcodeImageEnabled(true);
integrator.initiateScan();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
if(result != null) {
if(result.getContents() == null) {
Log.d("MainActivity", "Cancelled scan");
Toast.makeText(this, "Cancelled", Toast.LENGTH_LONG).show();
} else {
//historiqueIntent = new Intent(MainActivity.this , Histourique.class);
//historiqueIntent.putExtra("serial",result.getContents());
//startActivity(historiqueIntent);
Intent i = new Intent(MainActivity.this,RechercheResult1.class);
i.putExtra("CodeBar",result.getContents());
Historique his = new Historique(this , result.getContents());
his.insert(result.getContents());
his.remplireDateCode();
startActivity(i);
Toast.makeText(this, "Done! " , Toast.LENGTH_SHORT).show();
}
} else {
// This is important, otherwise the result will not be passed to the fragment
super.onActivityResult(requestCode, resultCode, data);
}
}
#Override
protected void onPause()
{
// System.gc();
super.onPause();
}
//------------------------------------------------------
private View.OnClickListener onClickListener(final int i) {
return new View.OnClickListener() {
#Override
public void onClick(View v) {
if (i > 0) {
//next page
if (viewPager.getCurrentItem() < viewPager.getAdapter().getCount() - 1) {
page++;
viewPager.setCurrentItem(viewPager.getCurrentItem() + 1);
}
} else {
//previous page
if (viewPager.getCurrentItem() > 0) {
page--;
viewPager.setCurrentItem(viewPager.getCurrentItem() - 1);
}
}
}
};
}
// images dyal les produit proposses :
private void inflateThumbnails() {
System.out.println("==========>"+CodeBar.size());
TextView title = (TextView) findViewById(R.id.title_promo);
if(CodeBar.size() == 0)
{
title.setVisibility(View.INVISIBLE);
deleteLast.setVisibility(View.INVISIBLE);
}
else
{
title.setVisibility(View.VISIBLE);
deleteLast.setVisibility(View.VISIBLE);
}
thumbnailsContainer.removeAllViews();
for (int i = 0; i < CodeBar.size(); i++) {
View imageLayout = getLayoutInflater().inflate(R.layout.cardview, null);
TextView price = (TextView) imageLayout.findViewById(R.id.prixprodtestcard);
TextView name = (TextView) imageLayout.findViewById(R.id.nomprodtestcard);
TextView namfou=(TextView) imageLayout.findViewById(R.id.qtestockcard);
TextView rating=(TextView)imageLayout.findViewById(R.id.rating);
ImageView imageProd = (ImageView) imageLayout.findViewById(R.id.imageprodcard);
FloatingActionButton btnlike = (FloatingActionButton) imageLayout.findViewById(R.id.likeButtoncard);
btnlike.setVisibility(View.INVISIBLE);
price.setText(prix.get(i));
name.setText(nomProd.get(i));
namfou.setText(nomFour.get(i));
rating.setText(ratings.get(i).toString());
imageProd.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
int action = event.getAction();
switch (action) {
case MotionEvent.ACTION_DOWN:
// Disallow View pager to intercept touch events.
System.out.print("=============>ACTION_DOWN");
v.getParent().requestDisallowInterceptTouchEvent(true);
break;
case MotionEvent.ACTION_UP:
System.out.print("=============>ACTION_UP");
// Allow View pager to intercept touch events.
// v.getParent().requestDisallowInterceptTouchEvent(false);
break;
}
// Handle Listview touch events.
v.onTouchEvent(event);
return true;
}
});
Glide.with(this)
.load(new TagDatabase().URL_IMAGFOU+"fid="+id_Four.get(i)+"&&code="+CodeBar.get(i)+"&&etat= -99")
.diskCacheStrategy( DiskCacheStrategy.NONE )
.skipMemoryCache( true )
.placeholder(R.drawable.waitloat)
.thumbnail(0.1f)
.into(imageProd);
imageProd.setOnClickListener(onChagePageClickListener(i));
thumbnailsContainer.addView(imageLayout);
}
}
private View.OnClickListener onChagePageClickListener(final int i) {
return new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getBaseContext(),InformationsProduit.class);
intent.putExtra("nomProd", nomProd.get(i));
intent.putExtra("prix", prix.get(i));
intent.putExtra("nomFour",nomFour.get(i));
intent.putExtra("etatpromo", -99);//attttt
intent.putExtra("telFour",tel.get(i));
intent.putExtra("addrFour",adresse.get(i));
intent.putExtra("idFour",id_Four.get(i));
intent.putExtra("description",description.get(i));
intent.putExtra("codeBar",CodeBar.get(i));
startActivity(intent);
}
};
}
}

Related

Android - display progress bar when click on any sound from listview

this is what i want but dont know how to do it.Below is the code of my main activity. I have a listview of sound clips and i want to show a progressbar and button when we click on any sound, that progress bar should indicate the progress of the respective sound clip and button shoud be change to stop icon. i am using adapterview with arraylist.i have attached an image of that
public class MainActivity extends AppCompatActivity implements AdapterView.OnItemClickListener,NavigationView.OnNavigationItemSelectedListener {
private ArrayList<String> songList;
private ListView songView;
SearchView searchView;
private MediaPlayer mp;
ProgressBar progressBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
songList = new ArrayList<>();
mp = new MediaPlayer();
songView = findViewById(R.id.song_list);
progressBar=findViewById(R.id.progressBar);
try {
getSongList();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
ArrayAdapter<String> listAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, songList);
songView.setAdapter(listAdapter);
songView.setOnItemClickListener(this);
registerForContextMenu(songView);
Intent serviceIntent =
new Intent("com.android.vending.billing.InAppBillingService.BIND");
serviceIntent.setPackage("com.android.vending");
bindService(serviceIntent, mServiceConn, Context.BIND_AUTO_CREATE);
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// code for scroll to top button
FloatingActionButton fab = findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
songView.setSelection(0);
}
});
DrawerLayout drawer = findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.addDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
}
IInAppBillingService mService;
ServiceConnection mServiceConn = new ServiceConnection() {
#Override
public void onServiceDisconnected(ComponentName name) {
mService = null;
}
#Override
public void onServiceConnected(ComponentName name,
IBinder service) {
mService = IInAppBillingService.Stub.asInterface(service);
}
};
public void getSongList() throws IllegalAccessException {
Field[] fields = R.raw.class.getFields();
// loop for every file in raw folder
for (Field field : fields) {
int rid = field.getInt(field);
// Use that if you just need the file name
String filename = field.getName();
songList.add(filename);
songList
}
}
#Override
public void onBackPressed() {
DrawerLayout drawer = findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
public void onDestroy() {
super.onDestroy();
if (mService != null) {
unbindService(mServiceConn);
}
}
#Override
public boolean onCreateOptionsMenu(final Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
searchView = (SearchView) MenuItemCompat.getActionView(menu.findItem(R.id.action_search));
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
return true;
}
});
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_remove_ads) {
} else if (id == R.id.nav_share) {
try {
Intent i = new Intent(Intent.ACTION_SEND);
i.setType("text/plain");
i.putExtra(Intent.EXTRA_SUBJECT, "SoundBoard");
String sAux = "\nGet this app on Google Play\n\n";
sAux = sAux + "https://play.google.com/store/apps/details?id=com.facebook.orca \n\n";
i.putExtra(Intent.EXTRA_TEXT, sAux);
startActivity(Intent.createChooser(i, "choose one"));
} catch (Exception e) {
//e.toString();
}
} else if (id == R.id.nav_rate) {
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse("https://play.google.com/store/apps/details?id=com.facebook.orca"));
startActivity(intent);
} else if (id == R.id.about_us) {
}
DrawerLayout drawer = findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
// selected item
TextView txtView = (TextView) view;
String fname = txtView.getText().toString().toLowerCase();
int resID = getResources().getIdentifier(fname, "raw", getPackageName());
Toast.makeText(getApplicationContext(), "Hello Javatpoint"+getResources().getResourceName(resID), Toast.LENGTH_SHORT).show();
MediaPlayer mediaPlayer = MediaPlayer.create(this, resID);
mediaPlayer.start();
if (mp.isPlaying()) {
mp.reset();
}
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
if (v.getId() == R.id.song_list) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_list, menu);
}
}
#Override
public boolean onContextItemSelected(MenuItem item) {
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) item.getMenuInfo();
View view = info.targetView;
TextView txtView = (TextView) view;
String fname = txtView.getText().toString().toLowerCase();
int resID = getResources().getIdentifier(fname, "raw", getPackageName());
switch (item.getItemId()) {
case R.id.share:
// add stuff here
//String sharepath=
//Uri uri = Uri.parse(view.getResources().getResourceName(resID));
//String sharePath = Environment.getExternalStorageDirectory().getPath()
// + "/Soundboard/Ringtones/custom_ringtone.ogg";
//Uri uri = Uri.parse(sharePath);
// Use this to load the file
Uri uri=Uri.parse("file://" +getResources().getResourceEntryName(resID)+".mp3");
String str=("content://"+uri);
Intent share = new Intent(Intent.ACTION_SEND);
share.setType("audio/mp3");
share.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
share.putExtra(Intent.EXTRA_STREAM,uri);
startActivity(Intent.createChooser(share, "Share Sound File"));
return true;
case R.id.notification:
// edit stuff here
uri=Uri.parse("file://" +getResources().getResourceEntryName(resID)+".mp3");
str=("content://"+uri);
Toast.makeText(getApplicationContext(), ""+uri, Toast.LENGTH_SHORT).show();
return true;
case R.id.ringtone:
// remove stuff here
return true;
default:
return super.onContextItemSelected(item);
}
}
}

Navigation Drawer doesn't work onBackPressed in different Activities

I am using common navigation drawer for different activities where I am extending BaseActivity , although it works fine but i am unable to open the drawer if I pressed back button to go to the previous activity.
This is my code:
public class BaseActivity extends ActionBarActivity {
public static DrawerLayout mDrawerLayout;
public static ListView mDrawerList;
private ActionBarDrawerToggle mDrawerToggle;
protected RelativeLayout _completeLayout, _activityLayout;
// nav drawer title
private CharSequence mDrawerTitle;
Context context;
// used to store app title
private CharSequence mTitle;
ImageView viewImage;
private ArrayList<NavDrawerItem> navDrawerItems;
private NavDrawerListAdapter adapter;
private String selectedImagePath = "";
final private int PICK_IMAGE = 1;
final private int CAPTURE_IMAGE = 2;
private String imgPath;
private TextView tv_user_name;
private ProfilePictureView profilepic;
CallbackManager callbackManager;
private GoogleApiClient client;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FacebookSdk.sdkInitialize(getApplicationContext());
setContentView(R.layout.activity_base);
client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
callbackManager = CallbackManager.Factory.create();
// --------- login = (LoginButton)findViewById(R.id.login_button);
// profilepic = (ProfilePictureView)findViewById(R.id.fb_profile_pic);
// fetchDetailsViaFb();
}
public void setNavigationHeader() {
LayoutInflater inflater = getLayoutInflater();
View listHeaderView = inflater.inflate(R.layout.navigation_drawer_header, null, false);
mDrawerList.addHeaderView(listHeaderView);
viewImage = (ImageView) findViewById(R.id.profileImage);
tv_user_name=(TextView) findViewById(R.id.tv_user_name);
tv_user_name.setTextColor(Color.WHITE);
profilepic = (ProfilePictureView)findViewById(R.id.fb_profile_pic);
}
public void set(String[] navMenuTitles, TypedArray navMenuIcons) {
mTitle = mDrawerTitle = getTitle();
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.left_drawer);
navDrawerItems = new ArrayList<NavDrawerItem>();
// adding nav drawer items
if (navMenuIcons == null) {
for (int i = 0; i < navMenuTitles.length; i++) {
navDrawerItems.add(new NavDrawerItem(navMenuTitles[i]));
}
} else {
for (int i = 0; i < navMenuTitles.length; i++) {
navDrawerItems.add(new NavDrawerItem(navMenuTitles[i],
navMenuIcons.getResourceId(i, -1)));
}
}
mDrawerList.setOnItemClickListener(new SlideMenuClickListener());
// setting the nav drawer list adapter
adapter = new NavDrawerListAdapter(getApplicationContext(), navDrawerItems);
mDrawerList.setAdapter(adapter);
// enabling action bar app icon and behaving it as toggle button
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
// getSupportActionBar().setIcon(R.drawable.ic_drawer);
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, null, R.string.app_name, R.string.app_name) {
public void onDrawerClosed(View view) {
getSupportActionBar().setTitle(mTitle);
// calling onPrepareOptionsMenu() to show action bar icons
supportInvalidateOptionsMenu();
}
public void onDrawerOpened(View drawerView) {
getSupportActionBar().setTitle(mDrawerTitle);
// calling onPrepareOptionsMenu() to hide action bar icons
supportInvalidateOptionsMenu();
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
setNavigationHeader();
}
#Override
public void onStart() {
super.onStart();
client.connect();
Action viewAction = Action.newAction(
Action.TYPE_VIEW,
"Base Page",
Uri.parse("http://host/path"),
Uri.parse("android-app://android.sit.findpro/http/host/path")
);
AppIndex.AppIndexApi.start(client, viewAction);
}
#Override
public void onStop() {
super.onStop();
Action viewAction = Action.newAction(
Action.TYPE_VIEW,
"Base Page",
Uri.parse("http://host/path"),
Uri.parse("android-app://android.sit.findpro/http/host/path")
);
AppIndex.AppIndexApi.end(client, viewAction);
client.disconnect();
}
private class SlideMenuClickListener implements
ListView.OnItemClickListener {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,long id) {
// display view for selected nav drawer item
displayView(position);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
if (mDrawerLayout.isDrawerOpen(mDrawerList)) {
mDrawerLayout.closeDrawer(mDrawerList);
} else {
mDrawerLayout.openDrawer(mDrawerList);
}
}
return super.onOptionsItemSelected(item);
}
/***
* Called when invalidateOptionsMenu() is triggered
*/
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
// if nav drawer is opened, hide the action items
// boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
// menu.findItem(R.id.action_settings).setVisible(!drawerOpen);
return super.onPrepareOptionsMenu(menu);
}
/**
* Displaying fragment view for selected nav drawer list item
*/
private void displayView(int position) {
switch (position) {
case 0:
if(LogInActivity.userLoginViaFb){
profilepic.setVisibility(View.VISIBLE);
viewImage.setVisibility(View.GONE);
fetchDetailsViaFb();
}
viewImage.setVisibility(View.VISIBLE);
profilepic.setVisibility(View.GONE);
selectImage();
/* editor.putString("namePreferance", itemNAme);
editor.putString("imagePreferance", encodeToBase64(yourBitmap));
editor.commit();*/
break;
case 1:
Toast.makeText(BaseActivity.this, "Coming Soon", Toast.LENGTH_SHORT).show();
break;
case 2:
viewImage.setVisibility(View.VISIBLE);
selectImage();
break;
case 3:
Toast.makeText(BaseActivity.this, "Coming Soon", Toast.LENGTH_SHORT).show();
break;
case 4:
Intent sharingIntent = new Intent(Intent.ACTION_SEND);
sharingIntent.setType("text/html");
sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, Html.fromHtml("<p>This is the text that will be shared.</p>"));
startActivity(Intent.createChooser(sharingIntent,"Share using"));
break;
default:
break;
}
mDrawerList.setItemChecked(position, true);
mDrawerList.setSelection(position);
mDrawerLayout.closeDrawer(mDrawerList);
}
#Override
public void setTitle(CharSequence title) {
mTitle = title;
getActionBar().setTitle(mTitle);
}
/**
* When using the ActionBarDrawerToggle, you must call it during
* onPostCreate() and onConfigurationChanged()...
*/
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle sttate after onResoreInstanceState has occurred.
mDrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Pass any configuration change to the drawer toggls
mDrawerToggle.onConfigurationChanged(newConfig);
}
public void fetchDetailsViaFb(){
GraphRequest request = GraphRequest.newMeRequest(AccessToken.getCurrentAccessToken(), new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject object, GraphResponse response) {
JSONObject json = response.getJSONObject();
try {
if (json != null) {
String name = json.getString("name");
tv_user_name.setText(Html.fromHtml(name));
profilepic.setProfileId(json.getString("id"));
}
} catch (JSONException e) {
e.printStackTrace();
}
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id,name,link,email,picture");
request.setParameters(parameters);
request.executeAsync();
}
private void selectImage() {
AlertDialog.Builder builder = new AlertDialog.Builder(BaseActivity.this);
builder.setTitle("Choose Profile Pic");
builder.setItems(new CharSequence[]{"Take a Photo", "Choose from Gallery", "Cancel"},
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
switch (which) {
case 0:
Intent intent1 = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent1.putExtra(MediaStore.EXTRA_OUTPUT, setImageUri());
startActivityForResult(intent1, CAPTURE_IMAGE);
break;
case 1:
// GET IMAGE FROM THE GALLERY
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, ""), PICK_IMAGE);
break;
case 2:
dialog.dismiss();
default:
break;
}
}
});
builder.show();
profilepic.setVisibility(View.GONE);
}
public Uri setImageUri() {
File file = new File(Environment.getExternalStorageDirectory(), "image" + new Date().getTime() + ".png");
Uri imgUri = Uri.fromFile(file);
this.imgPath = file.getAbsolutePath();
return imgUri;
}
public String getImagePath() {
return imgPath;
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode != Activity.RESULT_CANCELED) {
if (requestCode == PICK_IMAGE) {
selectedImagePath = getAbsolutePath(data.getData());
System.out.println("path" + selectedImagePath);
viewImage.setImageBitmap(decodeFile(selectedImagePath));
PreferenceHandler.encodeToBase64(decodeFile(selectedImagePath)); //uy7igyoiugo
} else if (requestCode == CAPTURE_IMAGE) {
selectedImagePath = getImagePath();
Toast.makeText(this,"path" + selectedImagePath,Toast.LENGTH_LONG).show();
System.out.println("path" + selectedImagePath);
viewImage.setImageBitmap(decodeFile(selectedImagePath));
String img= PreferenceHandler.encodeToBase64(decodeFile(selectedImagePath));//uyiyuogo
PreferenceHandler.writeString(BaseActivity.this,PreferenceHandler.PROFILE_IMAGE,img);
} else {
super.onActivityResult(requestCode, resultCode, data);
}
}
}
public Bitmap decodeFile(String path) {
try {
// Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeFile(path, o);
// The new size we want to scale to
final int REQUIRED_SIZE = 70;
// Find the correct scale value. It should be the power of
// 2.
int scale = 1;
while (o.outWidth / scale / 2 >= REQUIRED_SIZE
&& o.outHeight / scale / 2 >= REQUIRED_SIZE)
scale *= 2;
// Decode with inSampleSize
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
return BitmapFactory.decodeFile(path, o2);
} catch (Throwable e) {
e.printStackTrace();
}
return null;
}
public String getAbsolutePath(Uri uri) {
String[] projection = { MediaStore.MediaColumns.DATA };
Cursor cursor = managedQuery(uri, projection, null, null, null);
if (cursor != null) {
int column_index = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
} else
return null;
}
/* We can override onBackPressed method to toggle navigation drawer*/
#Override
public void onBackPressed() {
if(mDrawerLayout.isDrawerOpen(mDrawerList)){
mDrawerLayout.closeDrawer(mDrawerList);
}else {
// mDrawerLayout.openDrawer(mDrawerList);
super.onBackPressed();
}
}
}
There is something wrong with your code. In onOptionsItemSelected there is wrong code. Replace that code with this code and everything should work fine:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// This makes sure the NavigationDrawer gets opened when the upper left button is pressed
if (drawerToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
If you want to do something when you come back on an activity you have to do it in onResume.
Overiding OnBackPressed in class which is extending BaseClass.
#Override
public void onBackPressed() {
if(mDrawerLayout.isDrawerOpen(mDrawerList)){
mDrawerLayout.closeDrawer(mDrawerList);
}else {
// mDrawerLayout.openDrawer(mDrawerList);
super.onBackPressed();
}
}

Moving the Drawer Toggle From Left To Right in Action Bar

In my Activity I have a drawer list that pops from the right but I'm not able to move the drawer toggle from the left to the right side. Please if somebody can help me solve this issue.I just want to move the toggle to the right of the action bar.
package com.parse.starter;
import com.parse.ParseUser;
public class UserDrawer extends AppCompatActivity {
//Declaring Variables
private ListView DrawerList;
private ArrayAdapter<String> Adapter;
private ActionBarDrawerToggle DrawerToggle;
private DrawerLayout DrawerLayout;
private String ActivityTitle;
final ParseUser currentUser = ParseUser.getCurrentUser();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_user_drawer);
DrawerList = (ListView) findViewById(R.id.navList);
DrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
ActivityTitle = getTitle().toString();
addDrawerItems();
setupDrawer();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
Button Sample = (Button) findViewById(R.id.button);
}
//Method To Add Items To The List View
private void addDrawerItems() {
String[] DArray = {"Job List", "Notifications", "Messages", "Log Out"};
Adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, DArray);
DrawerList.setAdapter(Adapter);
DrawerList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if (position == 0) {
Intent i0 = new Intent(UserDrawer.this, Set_Info.class);
startActivity(i0);
} else if (position == 1) {
//Intent i1 = new Intent(Drawer1.this, AddPatient.class);
//startActivity(i1);
} else if (position == 2) {
//Intent i2 = new Intent(Drawer1.this, Notifications.class);
//startActivity(i2);
} else if (position == 3) {
//Intent i3 = new Intent(Drawer1.this, Message_Log.class);
//startActivity(i3);
} else if (position == 4) {
Intent i4 = new Intent(UserDrawer.this, MainActivity.class);
startActivity(i4);
Toast.makeText(getApplicationContext(), "You are Logged Out", Toast.LENGTH_LONG).show();
finish();
}
}
});
}
private void setupDrawer() {
DrawerToggle = new ActionBarDrawerToggle(this, DrawerLayout,
R.string.drawer_open, R.string.drawer_close) {
/** Called when a drawer has settled in a completely open state. */
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
getSupportActionBar().setTitle("Menu");
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
/** Called when a drawer has settled in a completely closed state. */
public void onDrawerClosed(View view) {
super.onDrawerClosed(view);
getSupportActionBar().setTitle(ActivityTitle);
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
};
DrawerToggle.setDrawerIndicatorEnabled(true);
DrawerLayout.setDrawerListener(DrawerToggle);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if(item != null && item.getItemId()==android.R.id.home){
if(DrawerLayout.isDrawerOpen(Gravity.RIGHT)){
//Notice the Gravity.Right
DrawerLayout.closeDrawer(Gravity.RIGHT);
}else{
DrawerLayout.openDrawer(Gravity.RIGHT);
}
}
return false;
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
DrawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
DrawerToggle.onConfigurationChanged(newConfig);
}
#SuppressWarnings("ResourceType")
public void SampleClick(View view) {
try {
Intent i = new Intent(UserDrawer.this,Set_Info.class);
startActivity(i);
} catch (Exception e) {
}
}
}

Android restore listview content

I have got two activities. In first you can input jobname and job place into inputtext views. First activity contains also navigation-draver menu (appearing from left side of screen). After clicking "Searc" button, results are shown in listview in second activity. You can long-click on any listview item and then it will be added to navigation-drawer in first activity. You can go back to first activity by clicking "back" arrow. The problem is, that when I will go back to first activity, press "Search" button again and then go back to first activity again, the navigation drawer menu is empty again (all items, which were added on first try are deleted). How to fix that?
Here is pic with my activities (sorry for poor quality):
1- first activity; 2- navigation drawer in first activity with added items from second activity' listview; 3- second activity (listview with search results)
EDIT:
My code from two activities (without imports to shorten it a little):
First (main):
public class MainActivity extends ActionBarActivity {
ListviewActivity lv = new ListviewActivity();
private ListView mDrawerList;
private DrawerLayout mDrawerLayout;
public ArrayAdapter<String> mAdapter;
private ActionBarDrawerToggle mDrawerToggle;
private String mActivityTitle;
ArrayList<String> arrayFav = new ArrayList<String>();
ArrayList<String> arrayLin = new ArrayList<String>();
private ImageView mImageViewLogo;
private Button mButtonSzukaj;
private EditText mEditTextPraca;
private EditText mEditTextMiejsce;
public static String nazwaStanowiska;
public static String nazwaMiejscowosci;
private Settings mSettings;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.start_layout);
mDrawerList = (ListView)findViewById(R.id.navList);mDrawerLayout = (DrawerLayout)findViewById(R.id.drawer_layout);
mActivityTitle = getTitle().toString();
addDrawerItems();
setupDrawer();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
mImageViewLogo = (ImageView)findViewById(R.id.imageViewLogo);
mButtonSzukaj = (Button) findViewById(R.id.buttonSzukaj);
mEditTextPraca = (EditText)findViewById(R.id.editTextPraca);
mEditTextMiejsce = (EditText)findViewById(R.id.editTextMiejsce);
final String mPrBefore = mEditTextPraca.getText().toString();
final String mPrAfter = mPrBefore.trim();
final String mMiBefore = mEditTextMiejsce.getText().toString();
final String mMiAfter = mMiBefore.trim();
mEditTextPraca.setText(mPrAfter);
mEditTextMiejsce.setText(mMiAfter);
mSettings = new Settings(this);
mAdapter.notifyDataSetChanged();
if(mAdapter.isEmpty()){
arrayFav.add("Brak ofert");
mDrawerList.setOnItemClickListener(null);
mDrawerList.setOnItemLongClickListener(null);
}
mAdapter.notifyDataSetChanged();
mButtonSzukaj.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (TextUtils.isEmpty(mEditTextPraca.getText().toString()) && (TextUtils.isEmpty(mEditTextMiejsce.getText().toString()))) {
mEditTextPraca.setError("Pole obowiązkowe!");
mEditTextMiejsce.setError("Pole obowiązkowe!");
return;
} else if (TextUtils.isEmpty(mEditTextPraca.getText().toString())) {
mEditTextPraca.setError("Pole obowiązkowe!");
return;
} else if (TextUtils.isEmpty(mEditTextMiejsce.getText().toString())) {
mEditTextMiejsce.setError("Pole obowiązkowe!");
return;
} else {
nazwaStanowiska = mEditTextPraca.getText().toString();
nazwaMiejscowosci = mEditTextMiejsce.getText().toString();
Intent myIntent = new Intent(MainActivity.this, ListviewActivity.class);
MainActivity.this.startActivityForResult(myIntent, 1);
mSettings.setmText1(mEditTextPraca.getText().toString());
mSettings.setmText2(mEditTextMiejsce.getText().toString());
mSettings.save();
}
}
});
readPreferences();
}
protected void readPreferences(){
mEditTextPraca.setText(mSettings.getmText1());
mEditTextMiejsce.setText(mSettings.getmText2());
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1) {
if(resultCode == RESULT_OK){
ArrayList<String> passedText = data.getStringArrayListExtra("text");
ArrayList<String> passedLink = data.getStringArrayListExtra("link");
//arrayFav.clear();
//arrayLin.clear();
arrayFav.addAll(passedText);
arrayLin.addAll(passedLink);
addDrawerItems();
}
}
}
#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) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
if (id == R.id.podziel_sie_opinia) {
Intent mIntent = new Intent(Intent.ACTION_SENDTO, Uri.parse("smsto:661249888"));
mIntent.putExtra("sms_body", "Uważam, że aplikacja...");
startActivity(mIntent);
return true;
}
// Activate the navigation drawer toggle
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
}
private void addDrawerItems() {
mAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, arrayFav);
mDrawerList.setAdapter(mAdapter);
mDrawerList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(getApplicationContext(), "Tu pojawi się kliknięta oferta", Toast.LENGTH_LONG).show();
/*Intent myBrowserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.onet.pl"));
startActivity(myBrowserIntent);*/
Intent myBrowserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(arrayLin.get(position)));
myBrowserIntent.putExtra("paramPosition", position);
startActivity(myBrowserIntent);
}
});
mDrawerList.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(getApplicationContext(), "Usunięto z ulubionych!", Toast.LENGTH_SHORT).show();
mAdapter.remove(mAdapter.getItem(position));
mAdapter.notifyDataSetChanged();
if(mAdapter.isEmpty()){
arrayFav.add("Brak ofert");
}
mAdapter.notifyDataSetChanged();
return false;
}
});
}
private void setupDrawer() {
mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.string.drawer_open, R.string.drawer_close) {
/** Called when a drawer has settled in a completely open state. */
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
getSupportActionBar().setTitle("Twoje oferty");
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
/** Called when a drawer has settled in a completely closed state. */
public void onDrawerClosed(View view) {
super.onDrawerClosed(view);
getSupportActionBar().setTitle(mActivityTitle);
invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
};
mDrawerToggle.setDrawerIndicatorEnabled(true);
mDrawerLayout.setDrawerListener(mDrawerToggle);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mDrawerToggle.syncState();
}
#Override
protected void onResume() {
super.onResume();
mAdapter.notifyDataSetChanged();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
mDrawerToggle.onConfigurationChanged(newConfig);
}
}
and the second one (listview with results):
public class ListviewActivity extends ActionBarActivity {
int global_position =0;
boolean longClick = false;
static String wybranaOferta = "";
ArrayList<String> choosedOffer = new ArrayList<String>();
ArrayList<String> choosedLink = new ArrayList<String>();
MainActivity mainActiv;
static List<String> mLista = new ArrayList<>();
static ArrayList<String> positionArr = new ArrayList<String>();
static List<String> mListaTest1 = new ArrayList<>();
static List<String> mListaTest2 = new ArrayList<>();
static List<String> mListaLinki = new ArrayList<>();
static List<String> mListaNazwy = new ArrayList<>();
static List<String> mListaFirmy = new ArrayList<>();
private JobListAdapter mAdapter;
public Elements jobName, jobName2, jobNameComp, jobName2Comp;
private ProgressBar mProgress;
private Context context;
public ArrayList<String> workList = new ArrayList<String>();
public ArrayList<String> companyList = new ArrayList<String>();
public ArrayList<String> jobList = new ArrayList<String>();
private ArrayAdapter<String> adapter;
private JazzyListView mListView;
public String doURLpraca = MainActivity.nazwaStanowiska;
public String doURLmiejsce = MainActivity.nazwaMiejscowosci;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_listview);
mListView = (JazzyListView) findViewById(R.id.list);
mListView.setTransitionEffect(new FanEffect());
mListView.setItemsCanFocus(true);
//Progress bar
mListView.setEmptyView(findViewById(R.id.progressBarLoading));
Toast.makeText(getApplicationContext(), "Wyszukiwanie ofert...", Toast.LENGTH_LONG).show();
new NewThread().execute();
mAdapter = new JobListAdapter(this, jobList);
mListView.setAdapter(mAdapter);
mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent myBrowserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(mListaLinki.get(position)));
myBrowserIntent.putExtra("paramPosition", position);
startActivity(myBrowserIntent);
}
});
mListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
choosedOffer.add(mListaTest1.get(position).toString());
choosedLink.add(mListaLinki.get(position).toString());
Toast.makeText(getApplicationContext(), "Dodano do ulubionych!", Toast.LENGTH_SHORT).show();
return false;
}
});
}
protected void onPreExecute() {
}
public void onBackPressed() {
Intent intent = new Intent(ListviewActivity.this, MainActivity.class);
intent.putStringArrayListExtra("text", choosedOffer);
intent.putStringArrayListExtra("link", choosedLink);
setResult(RESULT_OK, intent);
finish();
}
public class NewThread extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... arg) {
String doURLwork = mainActiv.nazwaStanowiska;
String doURLplace = mainActiv.nazwaMiejscowosci;
Document doc, doc2;
Elements classs, lins;
String uerele;
try {
doc = (Document) Jsoup.connect("http://www.infopraca.pl/praca?q=" + doURLwork + "&lc=" + doURLplace)
.userAgent("Mozilla/5.0 (Windows NT 6.1; WOW64; rv:5.0) Gecko/20100101 Firefox/5.0").get();
doc2 = (Document) Jsoup.connect("http://www.pracuj.pl/praca/" + doURLwork + ";kw/" + doURLplace + ";wp")
.userAgent("Mozilla/5.0 (Windows NT 6.1; WOW64; rv:5.0) Gecko/20100101 Firefox/5.0").get();
//Oferty
jobName = doc.select("h2.p-job-title a[href]"); //Infopraca
jobName2 = doc2.select("h2.offer__list_item_link a[href]"); //pracuj.pl
//Firmy
jobNameComp = doc.select("h3.p-name.company a[href]"); //Infopraca
jobName2Comp = doc2.select("h3.offer__list_item_link a[href]"); //pracuj.pl
//Oferty pracy
//Infopraca
mListaTest1.clear();
for (Element jobNames : jobName) {
mListaTest1.add(jobNames.text() + "\n");
}
//Pracuj.pl
for (Element jobNames2 : jobName2) {
mListaTest1.add(jobNames2.text() + "\n");
}
if(mListaTest1.size()==0){
Toast.makeText(getApplicationContext(), "Zmień parametry wyszukiwania!", Toast.LENGTH_LONG).show();
}
//--------------------------------------------------
//Firmy
//Infopraca
mListaTest2.clear();
for (Element jobNames : jobNameComp) {
mListaTest2.add(jobNames.text() + "\n");
}
//Pracuj.pl
for (Element jobNames2 : jobName2Comp) {
mListaTest2.add(jobNames2.text() + "\n");
}
//Linki do ofert
//Infopraca
for (Element link : jobName) {
mListaLinki.add(link.attr("abs:href"));
}
//Pracuj.pl
for (Element link : jobName2) {
mListaLinki.add(link.attr("abs:href"));
}
//Łączenie wyników - oferta + nazwa firmy
jobList.clear();
for(int i=0; i<mListaTest1.size(); i++){
jobList.add(mListaTest1.get(i)+"\n"+mListaTest2.get(i));
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
protected void onPreExecute(String result) {
}
#Override
protected void onPostExecute(String result) {
mAdapter.notifyDataSetChanged();
}
}
}
Generally, the first activity may be destroyed and recreated each time you go back to it. You might have to save list view items in activity's
onSaveInstanceState(Bundle)
method and load them again in onCreate. A simple example can be found in the first answer here
Or, you can just use fragments instead of two activities.
EDIT:
It seems like onSaveInstanceState only works when the activity is being closed by force, and it's philosophy is that onDestroy() method is not a safe place to save your data since it might not get called for various reasons.
The easiest way to do this is to use fragments instead of separate activities. The list adapter should be a member of activity and instead of opening a new activity, a fragment transaction would take place.
Using the back stack of fragment manager, the back button navigation will also be no problem and it would return the app to its initial state. Since the list is a field of the activity it can be easily shared between the fragments and it would not change due to fragment transactions.

NavigationDrawer and Up Navigation

I implemented a BaseActivity which extends the ActionBarActivity and implements a NavigationDrawer. All my Activities are inheriting from this BaseActivity.
Im now wondering if i can implement a NavigationDrawer and still have the proper up navigation using the toolbar or is the device back button supposed to work as the up navigation button when i implemented a NavigationDrawer?
EDIT:
Custom NavigationDrawer with Toolbar
public abstract class NavigationActivity extends ActionBarActivity {
private Toolbar toolbar = null;
private DrawerLayout drawerLayout = null;
private ActionBarDrawerToggle drawerToggle = null;;
private ListView listView = null;
private CharSequence drawerTitle = null;
private CharSequence title = null;
private NavigationDrawerConfiguration navigationConfig = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.navigationConfig = this.getNavigationDrawerConfiguration();
this.setContentView(this.navigationConfig.getMainLayout());
this.toolbar = (Toolbar) this.findViewById(R.id.app_bar);
this.drawerLayout = (DrawerLayout) this.findViewById(navigationConfig.getDrawerLayoutId());
this.listView = (ListView) this.findViewById(navigationConfig.getLeftDrawerId());
this.listView.setAdapter(navigationConfig.getBaseAdapter());
this.listView.setOnItemClickListener(new DrawerItemClickListener());
this.drawerTitle = this.getTitle();
this.title = this.getTitle();
this.setSupportActionBar(this.toolbar);
this.getSupportActionBar().setDisplayHomeAsUpEnabled(true);
this.getSupportActionBar().setHomeButtonEnabled(true);
this.drawerToggle = new ActionBarDrawerToggle(this, drawerLayout, this.toolbar, this.navigationConfig.getDrawerOpenDesc(), this.navigationConfig.getDrawerCloseDesc()) {
#Override
public void onDrawerClosed(View view) {
getSupportActionBar().setTitle(title);
invalidateOptionsMenu();
}
#Override
public void onDrawerOpened(View drawerView) {
getSupportActionBar().setTitle(drawerTitle);
invalidateOptionsMenu();
}
};
this.drawerLayout.setDrawerListener(this.drawerToggle);
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
this.drawerToggle.syncState();
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
this.drawerToggle.onConfigurationChanged(newConfig);
}
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
if (this.navigationConfig.getActionMenuItemsToHideWhenDrawerOpen() != null) {
boolean drawerOpen = this.drawerLayout.isDrawerOpen(listView);
for (int item : this.navigationConfig.getActionMenuItemsToHideWhenDrawerOpen()) {
menu.findItem(item).setVisible(!drawerOpen);
}
}
return super.onPrepareOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (this.drawerToggle.onOptionsItemSelected(item)) {
return true;
} else {
return false;
}
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_MENU) {
if (this.drawerLayout.isDrawerOpen(this.listView)) {
this.drawerLayout.closeDrawer(this.listView);
} else {
this.drawerLayout.openDrawer(this.listView);
}
return true;
}
return super.onKeyDown(keyCode, event);
}
protected NavigationDrawerConfiguration getNavigationDrawerConfiguration() {
NavigationDrawerItem[] menu = new NavigationDrawerItem[] {
// NavigationMenuSection.create(100, "Demos"),
NavigationMenuItem.create(100, "Item 1", "ic_measure", false, this),
NavigationMenuItem.create(200, "Item 2", "ic_list", false, this),
// NavigationMenuSection.create(200, "General"),
NavigationMenuItem.create(300, "Item 3", "ic_diagrams", false, this),
NavigationMenuItem.create(400, "Item 4", "ic_calculator", false, this),
NavigationMenuItem.create(500, "Item 5", "ic_scanner", false, this),
NavigationMenuItem.create(600, "Item 6", "ic_profile", false, this),
NavigationMenuItem.create(700, "Item 7", "ic_follower", false, this),
NavigationMenuItem.create(800, "Item 8", "ic_settings", false, this)
};
NavigationDrawerConfiguration navigationDrawerConfiguration = new NavigationDrawerConfiguration();
navigationDrawerConfiguration.setMainLayout(R.layout.activity_menu_slide);
navigationDrawerConfiguration.setDrawerLayoutId(R.id.menu_slide_layout);
navigationDrawerConfiguration.setLeftDrawerId(R.id.menu_slide_list);
navigationDrawerConfiguration.setNavigationItems(menu);
navigationDrawerConfiguration.setDrawerOpenDesc(R.string.open_navigation_drawer);
navigationDrawerConfiguration.setDrawerCloseDesc(R.string.close_navigation_drawer);
navigationDrawerConfiguration.setBaseAdapter(new NavigationDrawerAdapter(this, R.layout.activity_menu_slide_item_row, menu));
return navigationDrawerConfiguration;
}
public void selectItem(int position) {
NavigationDrawerItem selectedItem = this.navigationConfig.getNavigationItems()[position];
this.onNavigationItemSelected(selectedItem.getId());
this.listView.setItemChecked(position, true);
if (selectedItem.updateActionBarTitle()) {
this.setTitle(selectedItem.getLabel());
}
if (this.drawerLayout.isDrawerOpen(this.listView)) {
this.drawerLayout.closeDrawer(this.listView);
}
}
protected void onNavigationItemSelected(int id) {
Intent intent = null;
switch ((int) id) {
case 100:
intent = new Intent(this, MeasureDataActivity.class);
break;
case 200:
intent = new Intent(this, MeasureDataListActivity.class);
break;
case 300:
intent = new Intent(this, DiagramsActivity.class);
break;
case 400:
intent = new Intent(this, CalcActivity.class);
break;
case 500:
intent = new Intent(this, RecipeActivity.class);
break;
case 600:
intent = new Intent(this, ProfileActivity.class);
break;
case 700:
intent = new Intent(this, FollowerActivity.class);
break;
case 800:
intent = new Intent(this, SettingsActivity.class);
break;
}
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
this.startActivity(intent);
}
protected int getDrawerIcon() {
return R.drawable.ic_navigation_drawer;
}
protected DrawerLayout getDrawerLayout() {
return this.drawerLayout;
}
protected ActionBarDrawerToggle getDrawerToggle() {
return this.drawerToggle;
}
#Override
public void setTitle(CharSequence title) {
this.title = title;
this.getSupportActionBar().setTitle(title);
}
private class DrawerItemClickListener implements ListView.OnItemClickListener {
/**
*
*/
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
selectItem(position);
}
}
}
I think in the onCreate after the super() call you can do this:
mDrawerToggle.setDrawerIndicatorEnabled(false);
If this alone doesn't work (or just doesn't work) try this:
getActionBar().setDisplayHomeAsUpEnabled(true);
Follow this link: Missing Up navigation icon after switching from ICS ActionBar to Lollipop Toolbar
Original poster found this link

Categories

Resources