delete a dynamically created button android - java

Ok, what I'm trying to do is, something like a tag search function.
What I did was create Button ArrayList, and whenever a user tries to input ",", it automatically creates a button and inserts it into the ArrayList, which ultimately registers to the LinearLayout.
It creates well, but does not delete well.
I get the error that the index is out of bounds, but was in no luck of finding out which statement should I use. Could you help me?
Thx in advance.
public class MainActivity extends AppCompatActivity {
private ArrayList<Button> tagCollection = null;
private LinearLayout llTagCollection = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tagCollection = new ArrayList<Button>();
initView();
}
#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;
}
return super.onOptionsItemSelected(item);
}
public void initView() {
final EditText etSearch = (EditText) findViewById(R.id.ET_SEARCH);
// final TextView tvResult = (TextView) findViewById(R.id.TV_RESULT);
llTagCollection = (LinearLayout) findViewById(R.id.LL_BUTTON_COLLECTION);
View currentView = new View(getApplicationContext());
/*
if(tagCollection.size() != 0) {
tagCollection.get(currentView.getId()).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
tagCollection.remove(tagCollection.get(v.getId()));
Log.e("Removed", String.valueOf(tagCollection.remove(tagCollection.get(v.getId()))));
// tagCollection.remove(this);
llTagCollection.removeAllViews();
int i = 0;
while (i < (tagCollection.size())) {
llTagCollection.addView(tagCollection.get(i));
i += 1;
}
}
});
}
*/
TextWatcher tagWatcher = new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
String convertedCharSequence = s.toString();
Log.e("ConvertedString", convertedCharSequence);
if (convertedCharSequence.length() > 0) {
String subString = convertedCharSequence.substring(convertedCharSequence.length() - 1);
Log.e("SubStringPosition", subString);
if (subString.equals(",")) {
// tvResult.setText(etSearch.getText().toString());
Button bTagButton = new Button(MainActivity.this);
bTagButton.setId(tagCollection.size());
bTagButton.setText(etSearch.getText().toString());
bTagButton.setBackgroundColor(Color.WHITE);
bTagButton.setTextColor(Color.BLACK);
/*
RelativeLayout.LayoutParams rlLayoutParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
if(tagCollection.size() != 0){
rlLayoutParams.addRule(RelativeLayout.END_OF, tagCollection.get(0).getId());
}
bTagButton.setLayoutParams(rlLayoutParams);
*/
bTagButton.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
tagCollection.remove(tagCollection.indexOf(this));
llTagCollection.removeAllViews();
int i = 0;
while (i < (tagCollection.size())) {
if(tagCollection.get(i) != null){
llTagCollection.addView(tagCollection.get(i));
}
i += 1;
}
}
});
tagCollection.add(bTagButton);
llTagCollection.removeAllViews();
int i = 0;
while (i < (tagCollection.size())) {
llTagCollection.addView(tagCollection.get(i));
i += 1;
}
// setContentView(rlTagCollection);
etSearch.setText("");
etSearch.setSelection(0);
}
}
}
#Override
public void afterTextChanged(Editable s) {
}
};
etSearch.addTextChangedListener(tagWatcher);
}
}

I solved it using indexOfChild function. It kept on throwing me indexOutOfBounds error. Thx

Because of the reputations, I can not add comment. SO I post here.
In the button click listener:
bTagButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
tagCollection.remove(tagCollection.indexOf(this));
llTagCollection.removeAllViews();
int i = 0;
while (i < (tagCollection.size())) {
if (tagCollection.get(i) != null) {
llTagCollection.addView(tagCollection.get(i));
}
i += 1;
}
}
});
You remove the button by tagCollection.remove(tagCollection.indexOf(this));. Here this means the OnClickListener instance, not the button clicked. SO you should remove buttons by:
tagCollection.remove(tagCollection.indexOf(v));

Related

NullPointerException in Share Action Provider Object

I am getting a null pointer exception in the following statement :-
MenuSAP = (ShareActionProvider) item.getActionProvider(); in onCreateOptionsMenu(Menu menu) method.
MainActivity.java
public class MainActivity extends Activity {
protected static final int REQUEST_OK = 1;
ListView l1;
ArrayList<Array_songs> songlist;
EditText e1;
Song_adapter adp;
private ShareActionProvider MenuSAP;
ImageButton ib;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ActionBar actionBar = getActionBar();
//actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_HOME | ActionBar.DISPLAY_SHOW_TITLE);
actionBar.setDisplayShowHomeEnabled(true);
actionBar.setIcon(R.drawable.iconw);
l1=(ListView)findViewById(R.id.lv1);
ib=(ImageButton)findViewById(R.id.ib1);
songlist=new ArrayList<Array_songs>();
e1= (EditText)findViewById(R.id.editText1);
e1.addTextChangedListener(tw);
ib.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i=new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
i.putExtra(RecognizerIntent.EXTRA_LANGUAGE, "en-US");
try{
startActivityForResult(i,REQUEST_OK );
}catch(ActivityNotFoundException r){
Toast.makeText(getApplicationContext(),"song cant be played", Toast.LENGTH_SHORT).show();
}
}
});
adp=new Song_adapter(MainActivity.this, songlist, this.getApplication());
l1.setAdapter(adp);
getSongList("");
l1.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position,long arg3) {
int sCB = getVar();
if(sCB == 0) {
Array_songs slist = songlist.get(position);
String Song_Title = slist.get_title();
String Song_Artist = slist.get_artist();
long Song_ID = slist.get_id();
//Toast.makeText(getApplicationContext(), Song_Artist + Song_Title + String.valueOf(Song_ID), Toast.LENGTH_SHORT).show();
// TODO Auto-generated method stub
Uri song_path = ContentUris.withAppendedId(android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, Song_ID);
Intent musicplayer = new Intent(Intent.ACTION_VIEW);
musicplayer.setDataAndType(song_path, "audio/*");
try {
startActivity(musicplayer);
} catch (ActivityNotFoundException e) {
Toast.makeText(getApplicationContext(), "Try Again", Toast.LENGTH_SHORT).show();
}
}
else
{
}
}
});
l1.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> adapterView, View view, int i, long l) {
changeVar();
vibrate();
int select = l1.getSelectedItemPosition();
l1.setItemChecked(select, true);
adp.notifyDataSetChanged();
return false;
}
});
}
private void vibrate() {
Vibrator v = (Vibrator) this.getSystemService(Context.VIBRATOR_SERVICE);
v.vibrate(120);
}
private void changeVar() {
((SyncClass) this.getApplication()).setShowCheckBox(1);
}
private int getVar()
{
Integer sCB = Integer.parseInt(((SyncClass) this.getApplication()).getShowCheckBox());
return sCB;
}
TextWatcher tw=new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// TODO Auto-generated method stub
songlist.clear();
adp.notifyDataSetChanged();
getSongList(s.toString());
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
}
};
protected void onActivityResult(int requestcode,int resultcode,Intent data){
super.onActivityResult(requestcode, resultcode, data);
if(requestcode==REQUEST_OK && resultcode==RESULT_OK){
ArrayList<String> ls=data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
e1.setText(ls.get(0));
}
}
public void getSongList(String stitle){
ContentResolver cr= getContentResolver();
Uri music=android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
Cursor mus=cr.query(music, null, null, null, null);
if(mus != null && mus.moveToFirst()){
int titleint=mus.getColumnIndex(android.provider.MediaStore.Audio.Media.TITLE);
int artistint= mus.getColumnIndex(android.provider.MediaStore.Audio.Media.ARTIST);
int songid=mus.getColumnIndex(android.provider.MediaStore.Audio.Media._ID);
do{
String songTitle=mus.getString(titleint);
String songArtist=mus.getString(artistint);
long songId=mus.getLong(songid);
if(songTitle.toUpperCase().contains(stitle.toUpperCase())){
songlist.add(new Array_songs(songId, songTitle, songArtist));
}
}while(mus.moveToNext());
}
}
#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);
MenuItem item = menu.findItem(R.id.menu_item_share);
MenuSAP = new ShareActionProvider(this);
MenuSAP.setShareIntent(createShareIntent());
MenuSAP = (ShareActionProvider) item.getActionProvider();
return super.onCreateOptionsMenu(menu);
}
private Intent createShareIntent() {
Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.setType("audio/*");
shareIntent.putExtra(Intent.EXTRA_MIME_TYPES,"audio/*");
return shareIntent;
}
#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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onBackPressed() {
int check;
check = getVar();
if(check == 1)
{
((SyncClass) this.getApplication()).setShowCheckBox(0);
adp.notifyDataSetChanged();
}
else
{
super.onBackPressed();
}
}
}
SongAdapter.java
public class Song_adapter extends BaseAdapter {
private ArrayList<Array_songs> song_ob;
private LayoutInflater inflator_ob;
private Application xyz;
//private int sCB = ((SyncClass) this.getApplication()).getSomeVariable();
public Song_adapter(Context c,ArrayList<Array_songs> songlist, Application a)
{
song_ob=songlist;
inflator_ob= LayoutInflater.from(c);
xyz = a;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return song_ob.size();
}
#Override
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(int position, View v, ViewGroup parent) {
// TODO Auto-generated method stub
LinearLayout lin_ob =(LinearLayout)inflator_ob.inflate(R.layout.song_content, parent,false) ;
Array_songs ars_ob= song_ob.get(position);
TextView title= (TextView)lin_ob.findViewById(R.id.song_name);
TextView artist= (TextView)lin_ob.findViewById(R.id.artist);
//CheckBox check = (CheckBox) lin_ob.findViewById(R.id.cbselect);
if(((SyncClass) xyz).getShowCheckBox() == "1")
{
lin_ob.findViewById(R.id.cbselect).setVisibility(View.VISIBLE);
}
else
{
lin_ob.findViewById(R.id.cbselect).setVisibility(View.GONE);
}
String stitle= ars_ob.get_title();
String sartist= ars_ob.get_artist();
title.setText(stitle);
artist.setText(sartist);
return lin_ob;
}
}
SyncClass.java
public class SyncClass extends Application {
private String showCheckBox = "0";
public String getShowCheckBox()
{
return showCheckBox;
}
public void setShowCheckBox(int showCheckBox)
{
this.showCheckBox = Integer.toString(showCheckBox);
}
}
menu_main.xml
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" tools:context=".MainActivity">
<item
android:id="#+id/action_settings"
android:title="#string/action_settings"
android:orderInCategory="100"
android:showAsAction="never" />
<item
android:id="#+id/menu_item_share"
android:showAsAction="ifRoom"
android:title="Share"
android:actionProviderClass="android.widget.ShareActionProvider" />
</menu>
Please do help. Am new to android and need help..!!
Instead of using getActionProvider, try to use
MenuItemCompat.setActionProvider(item, menuSAP);
Have a look at this answer for more informations :
why MenuItemCompat.getActionProvider returns null?

Override Back button to save data using SharedPreferences

When using my app the users inputs data and the data is supposed to be saved. However at the moment the back button erases the data from the EditText. Here is my java file for the activity, this activity is activated by a button press from the Main Activity. I've already tried to override the back button with no success. Any suggestions?
public class NewLocation extends ActionBarActivity {
public String coName;
public String coAddress;
public String coContact;
public String sqFt;
public String taxed;
public String concerns;
public EditText editCoName;
public EditText editCoAddress;
public EditText editCoContact;
public EditText editSqFt;
public EditText editTaxed;
public EditText editConcerns;
public static final String DEFAULT = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new_location);
findViewById(R.id.button3).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(NewLocation.this, RoomList.class));
}
});
editCoName = (EditText) findViewById(R.id.CoName);
editCoAddress = (EditText) findViewById(R.id.CoAddress);
editCoContact = (EditText) findViewById(R.id.CoContact);
editSqFt = (EditText) findViewById(R.id.SqFt);
editTaxed = (EditText) findViewById(R.id.Taxed);
editConcerns = (EditText) findViewById(R.id.Concerns);
coName = editCoName.getText().toString();
coAddress = editCoAddress.getText().toString();
coContact = editCoContact.getText().toString();
sqFt = editSqFt.getText().toString();
taxed = editTaxed.getText().toString();
concerns = editConcerns.getText().toString();
LoadPreferences();
}
#Override
public void onSaveInstanceState(Bundle outState, PersistableBundle outPersistentState) {
super.onSaveInstanceState(outState, outPersistentState);
outState.putString("coName", coName);
outState.putString("coAddress", coAddress);
outState.putString("coContact", coContact);
outState.putString("sqFt", sqFt);
outState.putString("taxed", taxed);
outState.putString("concerns", concerns);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
coName = savedInstanceState.get("coName").toString();
coAddress = savedInstanceState.get("coAddress").toString();
coContact = savedInstanceState.get("coContact").toString();
sqFt = savedInstanceState.get("sqFt").toString();
taxed = savedInstanceState.get("taxed").toString();
concerns = savedInstanceState.get("concerns").toString();
}
private void SavePreferences()
{
SharedPreferences sharedPreferences = getSharedPreferences("New Location Data", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("coName", coName);
editor.putString("coAddress", coAddress);
editor.putString("coContact", coContact);
editor.putString("sqFt", sqFt);
editor.putString("taxed", taxed);
editor.putString("concerns", concerns);
editor.apply();
}
private void LoadPreferences()
{
SharedPreferences sharedPreferences = getSharedPreferences("New Location Data", Context.MODE_PRIVATE);
coName = sharedPreferences.getString("coName", DEFAULT);
coAddress = sharedPreferences.getString("coAddress", DEFAULT);
coContact = sharedPreferences.getString("coContact", DEFAULT);
sqFt = sharedPreferences.getString("sqFt", DEFAULT);
taxed = sharedPreferences.getString("taxed", DEFAULT);
concerns = sharedPreferences.getString("concerns", DEFAULT);
editCoName.setText(coName);
editCoAddress.setText(coAddress);
editCoContact.setText(coContact);
editSqFt.setText(sqFt);
editTaxed.setText(taxed);
editConcerns.setText(concerns);
}
#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_new_location, 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;
}
switch(item.getItemId())
{
case R.id.home:
SavePreferences();
startActivity(new Intent(getApplicationContext(), MainPage.class));
break;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onBackPressed() {
SavePreferences();
super.onBackPressed();
}
}
You should save/restore the persistent state of the activity in onSaveInstanceState/onRestoreInstanceState methods. You already override those, so just call SavePreferences/LoadPreferences from them.
Overriding the back button is not a good idea and saving state in onDestroy is also not recommended. Either onSaveInstanceState or onPause is intended for that.
If the data needs to be saved whenever the user leaves that activity, you could approach the problem with a TextWatcher. Override the onTextChanged() method of the TextWatcher with something like this:
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (s.length > 0) coName = s;
}
And then override onPause() to save the state of your variables if necessary.
[Edited] You can try:
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
SavePreferences();
finish(); //<-- You need finish your activity after saved
return true;
}
return super.onKeyDown(keyCode, event);
}

How to get Background from another Activity?

I want to change the background-color of another Activity (start) in my Settings-Activity (choose between different colors, sounds etc.).
How can I change the color of another Activity?
I tried to get the Background from my start-Activity (id:start) with:
final RelativeLayout background = (RelativeLayout) findViewById(R.id.start);
but it seems it doesn´t work.
Full Code of the Settings-Activity:
public class activity_settings extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_activity_settings);
ColorChange();
}
public void ColorChange() {
final RelativeLayout background = (RelativeLayout) findViewById(R.id.start);
final RadioButton ChangeToBlue = (RadioButton) findViewById(R.id.button_blue);
final RadioButton ChangeToRed = (RadioButton) findViewById(R.id.button_red);
final Button button_save = (Button) findViewById(R.id.button_save);
button_save.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
ChangeOption(background);
}
});
ChangeToBlue.setOnCheckedChangeListener(new RadioButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
ChangeToBlue(background);
}
});
ChangeToRed.setOnCheckedChangeListener(new RadioButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
ChangeToRed(background);
}
});
}
public void ChangeOption(RelativeLayout background) {
if (background.isEnabled()) {
background.setEnabled(false);
} else {
background.setEnabled(true);
}
}
public void ChangeToBlue(RelativeLayout background) {
background.setBackgroundColor(Color.BLUE);
background.invalidate();
}
public void ChangeToRed(RelativeLayout background) {
background.setBackgroundColor(Color.RED);
background.invalidate();
}
#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_activity_settings, 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;
}
return super.onOptionsItemSelected(item);
}}
Save color code i.e. #F0F0F0 from your setting-activity in a sharedPreference and get this value in onCreate() of activity in which you want to set background.

Android - Why RAM usage continues to increase after fragment replace?

I am using NavigationDrawer and replace fragments like this:
ft.setCustomAnimations(
android.R.anim.slide_in_left, android.R.anim.slide_out_right
);
ft.replace(container, fragment);
// Start the animated transition.
ft.commit();
When Application start and First fragment is loaded, allocation heap is ~15 MB.
After I replace first fragment with second and doing some work, allocation heap ~40MB.
Then I replace second fragment with third, allocation heap maintains at ~40MB ( if force garbage collection) allocation heap decreases by ~7 mb.
If, I will not load second fragment and will go to third from first, allocation heap will maintain at ~17 MB.
Is second fragment destroyed at all, and if it is destroyed, why memmory is not freed?
As I understand without addToBackStack() fragments are not added to back stack and should be destroyed after removing ( as replace call remove and add)
Second fragment is basicly a listview
public class ArtistListFragment extends Fragment {
private FragmentArtistAdapter adapter;
private static final List<ArtistsEntity> articles = new ArrayList<>();
private GetAdds feed = new GetAdds();
private GridView list;
private String request = "new";
private ToggleButton tbLeft;
private ToggleButton tbRight;
private ToggleButton tbAbc;
public ArtistListFragment() {
// Required empty public constructor
}
private Tracker t;
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
t = ((UILApplication) getActivity().getApplication()).getTracker();
t.setScreenName("Artist List Screen");
t.send(new HitBuilders.EventBuilder()
.setCategory("Open Screen")
.build());
t.send(new HitBuilders.EventBuilder()
.setCategory("view")
.setAction("choose")
.setLabel("new")
.build());
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_artist_list, container, false);
setSwipeLayout(view);
eVideoScroll.resetState();
adapter = new FragmentArtistAdapter(getActivity(), articles);
list = (GridView) view.findViewById(R.id.gridview);
tbLeft = (ToggleButton) view.findViewById(R.id.tb_left);
tbRight = (ToggleButton) view.findViewById(R.id.tb_right);
tbAbc = (ToggleButton) view.findViewById(R.id.tb_abc);
tbLeft.setOnCheckedChangeListener(leftListener);
tbRight.setOnCheckedChangeListener(rightListener);
tbAbc.setOnCheckedChangeListener(abcListener);
tbLeft.setClickable(false);
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
BusProvider.getInstance().post(new OpenArtistInfo(
articles.get(position)
.getSlug()));
}
});
feed = new GetAdds();
feed.execute();
list.setOnScrollListener(eVideoScroll);
return view;
}
private SwipeRefreshLayout swipeLayout;
private void setSwipeLayout(View view) {
swipeLayout = (SwipeRefreshLayout) view.findViewById(R.id.swipe_container);
swipeLayout.setOnRefreshListener(refreshPage);
swipeLayout.setColorSchemeResources(android.R.color.holo_blue_bright,
android.R.color.holo_green_light,
android.R.color.holo_orange_light,
android.R.color.holo_red_light);
}
private final SwipeRefreshLayout.OnRefreshListener refreshPage = new SwipeRefreshLayout.OnRefreshListener() {
#Override
public void onRefresh() {
new ResetVideoSelection().execute();
}
};
boolean checkInternetConnection() {
ConnectivityManager cm = (ConnectivityManager) getActivity()
.getSystemService(Context.CONNECTIVITY_SERVICE);
// test for connection
if (cm.getActiveNetworkInfo() != null
&& cm.getActiveNetworkInfo().isAvailable()
&& cm.getActiveNetworkInfo().isConnected()) {
return true;
} else {
AlertDialog alertDialog = new AlertDialog.Builder(getActivity()).create();
alertDialog.setTitle(getString(R.string.no_internet_conection));
alertDialog
.setMessage(getString(R.string.open_network_settings));
alertDialog.setButton(AlertDialog.BUTTON_POSITIVE, getString(R.string.yes_response),
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(
Settings.ACTION_WIRELESS_SETTINGS);
startActivity(intent);
}
});
alertDialog.setButton(AlertDialog.BUTTON_NEGATIVE, getString(R.string.no_response),
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alertDialog.setIcon(R.drawable.ic_launcher);
alertDialog.show();
return false;
}
}
void emptyResultDialog() {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setMessage(ErrorMessage.INSTANCE.getErrorMessage())
.setCancelable(false)
.setPositiveButton(R.string.close_response,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
});
Dialog dialog = builder.create();
dialog.show();
}
private class GetAdds extends AsyncTask<Void, Void, List<ArtistsEntity>> {
#Override
protected void onPreExecute() {
if (!checkInternetConnection()) {
swipeLayout.setRefreshing(true);
cancel(true);
eVideoScroll.loading = false;
} else {
if (!swipeLayout.isRefreshing())
swipeLayout.setRefreshing(true);
}
}
#Override
protected List<ArtistsEntity> doInBackground(Void... params) {
int trial = 0;
MaterialRequest jParse = new MaterialRequest();
List<ArtistsEntity> result = null;
int page = PaggingData.INSTANCE.artistListCurrentPage + 1;
while (result == null && trial < 5 && !isCancelled()) {
trial++;
result = jParse.getArtists(request, page);
}
return result;
}
#Override
protected void onPostExecute(List<ArtistsEntity> result) {
super.onPostExecute(result);
if (result != null && result.size() > 0) {
if (PaggingData.INSTANCE.artistListCurrentPage <= 1)
articles.clear();
articles.addAll(result);
adapter.notifyDataSetChanged();
} else
emptyResultDialog();
eVideoScroll.loading = false;
swipeLayout.setRefreshing(false);
}
}
private final CompoundButton.OnCheckedChangeListener leftListener = new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
if (isChecked) {
request = "new";
new ResetVideoSelection().execute();
tbRight.setChecked(false);
tbAbc.setChecked(false);
tbLeft.setClickable(false);
t.send(new HitBuilders.EventBuilder()
.setCategory("view")
.setAction("choose")
.setLabel("new")
.build());
} else {
tbLeft.setClickable(true);
}
}
};
private final CompoundButton.OnCheckedChangeListener rightListener = new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
if (isChecked) {
request = "popular";
new ResetVideoSelection().execute();
tbLeft.setChecked(false);
tbAbc.setChecked(false);
tbRight.setClickable(false);
t.send(new HitBuilders.EventBuilder()
.setCategory("view")
.setAction("choose")
.setLabel("popular")
.build());
} else {
tbRight.setClickable(true);
}
}
};
private final CompoundButton.OnCheckedChangeListener abcListener = new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
if (isChecked) {
request = "abc";
new ResetVideoSelection().execute();
tbRight.setChecked(false);
tbLeft.setChecked(false);
tbAbc.setClickable(false);
t.send(new HitBuilders.EventBuilder()
.setCategory("view")
.setAction("choose")
.setLabel("abc")
.build());
} else {
tbAbc.setClickable(true);
}
}
};
private class ResetVideoSelection extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
eVideoScroll.resetState();
list.setSelection(0);
}
#Override
protected Void doInBackground(Void... params) {
// if (videoArticles.size() > 0)
// while (listVideo.getSelectedItemPosition() != 0) {
//
// }
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
feed = new GetAdds();
feed.execute();
}
}
private final EndlessVideoScrollListener eVideoScroll = new EndlessVideoScrollListener();
private class EndlessVideoScrollListener implements AbsListView.OnScrollListener {
private int visibleThreshold = 5;
private int previousTotal = 0;
private boolean loading = true;
public void resetState() {
visibleThreshold = 5;
previousTotal = 0;
loading = true;
PaggingData.INSTANCE.artistListPages = 0;
PaggingData.INSTANCE.artistListCurrentPage = 0;
}
public EndlessVideoScrollListener() {
}
public EndlessVideoScrollListener(int visibleThreshold) {
this.visibleThreshold = visibleThreshold;
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
if (loading) {
if (totalItemCount > previousTotal) {
// loading = false;
previousTotal = totalItemCount;
}
}
if (!loading
&& (totalItemCount - visibleItemCount) <= (firstVisibleItem + visibleThreshold)) {
// I load the next page of gigs using a background task,
// but you can call any function here.
if (PaggingData.INSTANCE.artistListCurrentPage + 1 <= PaggingData.INSTANCE.artistListPages) {
feed = new GetAdds();
feed.execute();
loading = true;
}
}
}
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
}
}
#Override
public void onPause() {
super.onPause();
feed.cancel(true);
swipeLayout.setRefreshing(false);
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
((NavigationDrawerActivity) activity).onSectionAttached(getArguments().getString("title"));
}
}
Indeed, Fragments are destroyed and created anew as they shift in and out of view (unlike Activitys), provided addToBackStack() is not used.
I suspect that
1. You have set android:largeHeap = true in your app manifest.
2. Your Fragments are possibly making use of heavy ImageViews / VideoViews or cached Bitmaps with static references, which can also be a cause of unrestricted heap growth.
These are some reasons off the top of my head that I can think of in a situation like this.

Convert Editable to Edittext

I have set a tag to An Edittext variable.i want get that tag inside text TextWatcher afterTextChanged method.but there is a Editable parameter not Edittext.
here is my code.....
EditText filled = new EditText(DamageCount.this);
filled.setId(100);
filled.setTag(5);
and i want get that tag in
#Override
public void afterTextChanged(Editable s) {
}
this method
------Edited----------------
my whole java class
public class DamageCount extends Activity {
private Button button_next;
static TableLayout tl = null;
private DbWorker dbworker;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_damage_count);
DamageCount.this
.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
button_next = (Button) findViewById(R.id.button_next);
tl = (TableLayout) findViewById(R.id.show_competitor_product);
dbworker = new DbWorker(this);
Static_Values.arrayListdam_no = new ArrayList<DamegeItemSerialNoModel>();
button_next.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
/*Intent new_one = new Intent(DamageCount.this,
Invoice_or_prev.class);
startActivity(new_one);
finish();*/
for(DamegeItemSerialNoModel dmmm :Static_Values.arrayListdam_no)
{
System.out.println("Item id is "+dmmm.getItem_id()+" serial no is "+dmmm.getSerial_no());
}
}
});
Cursor cur_products= dbworker.getAllProduct();
int i=0;
if(cur_products.moveToFirst())
{
do{
i++;
// Static_Values.item.put(, value)
add_tbl_row(i,cur_products.getString(3),cur_products.getString(1));
}
while(cur_products.moveToNext());
}
else {
}
cur_products.close();
}
public void add_tbl_row(int value, String name, String tag) {
Static_Values.damaged_id=tag;
TableRow new_row = new TableRow(DamageCount.this);
System.out.println(Static_Values.damaged_id+" id bbb");
ImageView imageView = new ImageView(this);
imageView.setImageResource(R.drawable.ic_launcher);
new_row.addView(imageView);
TextView size = new TextView(DamageCount.this);
size.setId(1);
size.setText(name);
size.setPadding(5, 5, 5, 5);
new_row.addView(size);
EditText filled = new EditText(DamageCount.this);
filled.setId(100 * value);
filled.setTag(tag);
filled.setHint("Enter Damaged");
filled.setInputType(InputType.TYPE_CLASS_NUMBER);
new_row.addView(filled);
filled.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void afterTextChanged(Editable s) {
// Toast.makeText(DamageCount.this, s.toString(), Toast.LENGTH_SHORT).show();
if(s.toString().equals("")==false)
{
final LinearLayout layout = new LinearLayout(DamageCount.this);
layout.setOrientation(LinearLayout.VERTICAL);
Button dialogButton = new Button(DamageCount.this);
dialogButton.setText("Add");
// dialogButton.setBackgroundColor(R.drawable.yellobutton);
Static_Values.num_of_serials=Integer.parseInt(s.toString());
for(int i=1;i<Integer.parseInt(s.toString())+1;i++)
{
EditText serial = new EditText(DamageCount.this);
serial.setId(33*i);
serial.setHint("Enter serial");
layout.addView(serial);
}
layout.addView(dialogButton);
final Dialog dialog = new Dialog(DamageCount.this);
dialog.setContentView(layout);
dialog.setTitle("Serial Numbers");
dialog.getWindow().setTitleColor(Color.BLUE);
// set the custom dialog components - text, image and button
// dialog.setContentView(filled);
// dialog.getOwnerActivity().setContentView(filled);
// if button is clicked, close the custom dialog
dialogButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
for (int i = 1; i < Static_Values.num_of_serials+1; i++) {
View vv = dialog.findViewById(33*i);
EditText et=(EditText)vv;
System.out.println(et.getText().toString());
DamegeItemSerialNoModel dism = new DamegeItemSerialNoModel();
dism.setItem_id(Static_Values.damaged_id);
System.out.println(Static_Values.damaged_id);
dism.setSerial_no(et.getText().toString());
Static_Values.arrayListdam_no.add(dism);
}
Static_Values.num_of_serials = 0;
dialog.dismiss();
}
});
dialog.show();
}
}
});
tl.addView(new_row, new TableLayout.LayoutParams(
LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
}
}
Create a constructor in yout Textwatcher class and pass the editext to it.
public class MyTextWatcher implements TextWatcher
{
private transient EditText editText = null;
public MyTextWatcher(EditText editText)
{
super();
this.editText = editText;
}
#Override
public void afterTextChanged(Editable arg0)
{
// TODO Auto-generated method stub
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3)
{
// TODO Auto-generated method stub
}
#Override
public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3)
{
// TODO Auto-generated method stub
}
}
If you want to convert Editable to simple text line (String), use this in your method:
#Override
public void afterTextChanged(Editable s) {
String str = s.toString();
}

Categories

Resources