Screen rotation - how to override the onSaveInstanceState and onRestoreInstanceState? - java

I need to keep and restore the results of a search while rotating the screen by override the onSaveInstanceState and onRestoreInstanceState... I don't know how to do this and where to use it.
someone got a clue about this ?
This is a part of the MainActivity:
public class MainActivity extends AppCompatActivity {
private static final String LOG_TAG = MainActivity.class.getName();
/**
* URL for book data from the Google books dataset
*/
private static final String G_BOOKS_REQUEST_URL =
"https://www.googleapis.com/books/v1/volumes?q=";
/**
* Adapter for the list of books
*/
private BookAdapter mAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
..............

Save the URL search result json/xml in savedInstanceState. When rotate screen test if result exist in savedInstanceState
savedInstanceState.putString("result", <serach result json/xml>);

final EditText searchTextView = (EditText) findViewById(R.id.search_bar);
Button searchButton = (Button) findViewById(R.id.search_button);
ListView bookListView = (ListView) findViewById(R.id.list);
mAdapter = new BookAdapter(this, new ArrayList<Book>());
bookListView.setAdapter(mAdapter);
bookListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
Book currentBook = mAdapter.getItem(position);
Uri bookUri = Uri.parse(currentBook.getmUrl());
Intent websiteIntent = new Intent(Intent.ACTION_VIEW, bookUri);
startActivity(websiteIntent);
}
});
searchButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String newQuery = searchTextView.getText().toString();
BookAsyncTask task = new BookAsyncTask();
task.execute(G_BOOKS_REQUEST_URL + newQuery);
}
});
}
#Override
protected List<Book> doInBackground(String... urls) {
// Don't perform the request if there are no URLs, or the first URL is null
if (urls.length < 1 || urls[0] == null) {
return null;
}
List<Book> result = QueryUtils.fetchBookData(urls[0]);
return result;
}
#Override
protected void onPostExecute(List<Book> data) {
mAdapter.clear();
if (data != null && !data.isEmpty()) {
mAdapter.addAll(data);
}
}
}
}

Related

Cannot restore Scroll position

Im stuck here 2 days. I am trying to restore scroll position after device rotation.
Im saving an arraylist in the onSaveInstance, adding the movies i have to it and trying to set the adapter.
If i switch shorting criteria and rotate the device, it scrolls up to the top and not retaining its position. Here's my code
public class MainActivity extends AppCompatActivity {
public static final String MOVIE_LIST = "instanceMovieList";
public static final String RECYCLER_VIEW_STATE_KEY = "RECYCLER_VIEW_STATE_KEY";
private static final String LOG_TAG = MainActivity.class.getSimpleName();
Context mContext;
Toolbar mToolBar;
#BindView(R.id.prefSpinnner)
Spinner prefSpinner;
#BindView(R.id.noDataTv)
TextView noDataTv;
#BindView(R.id.rv_movies)
RecyclerView mMoviesRV;
private AppDatabase mDb;
private String userOption = "Most Popular";
private ArrayList<Movie> mMoviesList = new ArrayList<>();
private MovieRecycleViewAdapter movieRecycleViewAdapter;
private RecyclerView.LayoutManager mLayoutManager;
private Parcelable mListState;
#Override
protected void onSaveInstanceState(Bundle outState) {
if (mMoviesList != null) {
outState.putParcelableArrayList(MOVIE_LIST, mMoviesList);
mListState = mLayoutManager.onSaveInstanceState();
outState.putParcelable(RECYCLER_VIEW_STATE_KEY, mListState);
}
super.onSaveInstanceState(outState);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
GridLayoutManager gridLayoutManager = new GridLayoutManager(this, 2);
mMoviesRV.setLayoutManager(gridLayoutManager);
mMoviesRV.setHasFixedSize(true);
movieRecycleViewAdapter = new MovieRecycleViewAdapter(MainActivity.this, mMoviesList);
mMoviesRV.setAdapter(movieRecycleViewAdapter);
mLayoutManager = mMoviesRV.getLayoutManager();
if (savedInstanceState != null && savedInstanceState.containsKey(MOVIE_LIST)) {
ArrayList<Movie> savedMovieList = savedInstanceState.getParcelableArrayList(MOVIE_LIST);
Log.d(LOG_TAG, "getting movies from instance ");
mMoviesList.addAll(savedMovieList);
movieRecycleViewAdapter = new MovieRecycleViewAdapter(MainActivity.this, mMoviesList);
mMoviesRV.setAdapter(movieRecycleViewAdapter);
}
mToolBar = findViewById(R.id.toolbar);
mToolBar.setTitle(getResources().getString(R.string.app_name));
ArrayAdapter<String> spinAdapter = new ArrayAdapter<String>(MainActivity.this, R.layout.pref_spinner_item_list, getResources().getStringArray(R.array.userPrefs));
spinAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
prefSpinner.setAdapter(spinAdapter);
prefSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
userOption = prefSpinner.getSelectedItem().toString();
if (userOption.contentEquals("Most Popular") || userOption.contentEquals("Highest Rated")) {
PopulateMoviesTask newTask = new PopulateMoviesTask();
newTask.execute();
} else {
setUpViewModel();
}
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
PopulateMoviesTask newTask = new PopulateMoviesTask();
newTask.execute();
}
});
mDb = AppDatabase.getInstance(getApplicationContext());
}
private void setUpViewModel() {
MainViewModel viewModel = ViewModelProviders.of(this).get(MainViewModel.class);
viewModel.getMovies().observe(this, new Observer<List<Movie>>() {
#Override
public void onChanged(#Nullable List<Movie> movies) {
Log.d(LOG_TAG, "updating list of movies from livedata in viewmodel");
movieRecycleViewAdapter.setMovies(movies);
}
});
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
if (savedInstanceState != null) {
mMoviesList = savedInstanceState.getParcelableArrayList(MOVIE_LIST);
mListState = savedInstanceState.getParcelable(RECYCLER_VIEW_STATE_KEY);
}
}
#Override
protected void onResume() {
super.onResume();
if (mListState != null) {
mLayoutManager.onRestoreInstanceState(mListState);
}
}
private class PopulateMoviesTask extends AsyncTask<URL, Void, String> {
#Override
protected String doInBackground(URL... urls) {
URL searchMovieObjectUrl = NetworkUtils.createUrl(userOption);
String jsonString = "";
try {
jsonString = NetworkUtils.makeHttpRequest(searchMovieObjectUrl);
} catch (IOException e) {
Log.e("Main Activity", "Problem making the HTTP request.", e);
}
return jsonString;
}
#Override
protected void onPostExecute(String jsonString) {
if (jsonString == null) {
mMoviesRV.setVisibility(View.GONE);
noDataTv.setVisibility(View.VISIBLE);
} else {
mMoviesRV.setVisibility(View.VISIBLE);
noDataTv.setVisibility(View.GONE);
mMoviesList = JsonUtils.extractFeatureFromJson(jsonString);
}
movieRecycleViewAdapter = new MovieRecycleViewAdapter(MainActivity.this, mMoviesList);
mMoviesRV.setAdapter(movieRecycleViewAdapter);
}
}
}
Use this
private Parcelable recyclerViewState;// global
onResume
#Override
public void onResume() {
super.onResume();
mMoviesRV.getLayoutManager().onRestoreInstanceState(recyclerViewState);
}
onPasue
#Override
public void onPause() {
super.onPause();
recyclerViewState= mMoviesRV.getLayoutManager().onSaveInstanceState();
}
Since i found out what was going on, i think i should post an answer.
#Override protected void onSaveInstanceState(Bundle outState) {
if (mMoviesList != null) {
outState.putParcelableArrayList(MOVIE_LIST, mMoviesList);
mListState = mLayoutManager.onSaveInstanceState();
outState.putParcelable(RECYCLER_VIEW_STATE_KEY, mListState);
}
super.onSaveInstanceState(outState);
}
is enough to save the moviesList through lifecycle and then retrieve it
if (savedInstanceState != null && savedInstanceState.containsKey(MOVIE_LIST)) {
mMoviesList = savedInstanceState.getParcelableArrayList(MOVIE_LIST);
This answers the original question
But the problem was in my adapter and WHEN i was initializing it.
The adapter should only be initialized in onCreate (in my case at least) and then notify it if the Arraylist data changed more info here.

main activity reads the data again from the firebase database after coming back to the mainactivity

this is my MainActivity
private DatabaseReference mDatabaseReference;
private RecyclerView recyclerView;
private PlaceRecyclerAdapter placeRecyclerAdapter;
private List<Places> placesList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mDatabaseReference = FirebaseDatabase.getInstance().getReference().child("Places");
placesList = new ArrayList<>();
recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main_menu,menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId()==R.id.action_add)
{
startActivity(new Intent(MainActivity.this,AddPostActivity.class));
finish();
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onStart() {
super.onStart();
mDatabaseReference.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
Places places = dataSnapshot.getValue(Places.class);
placesList.add(places);
placeRecyclerAdapter = new PlaceRecyclerAdapter(MainActivity.this,placesList);
recyclerView.setAdapter(placeRecyclerAdapter);
placeRecyclerAdapter.notifyDataSetChanged();
}
I am using this RecyclerAdapter to load cardview cards in the main activity
public PlaceRecyclerAdapter(Context context, List<Places> placesList) {
this.context = context;
this.placesList = placesList;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.post_row,parent,false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
Places places = placesList.get(position);
//String imageUrl= null;
holder.place.setText(places.getPlace());
holder.desc.setText(places.getDesc());
//imageUrl= places.getImage();
//todo: Use piccasso library to load images
//Picasso.with(context).load(imageUrl).into(holder.image);
}
#Override
public int getItemCount() {
return placesList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
public TextView place;
public TextView desc;
//public ImageView image;
public ViewHolder(View view) {
super(view);
place = (TextView) view.findViewById(R.id.postTitleList);
desc = (TextView) view.findViewById(R.id.postDescList);
//image = (ImageView) view.findViewById(R.id.postImageList);
view.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Context context = v.getContext();
int pos = getAdapterPosition();
if (pos != RecyclerView.NO_POSITION) {
Places clickedDataItem = placesList.get(pos);
//Toast.makeText(v.getContext(), "You clicked " + clickedDataItem.getPlace(), Toast.LENGTH_SHORT).show();
Intent intent = new Intent(context, Details.class);
intent.putExtra("NAME", clickedDataItem.getPlace());
intent.putExtra("DESC", clickedDataItem.getDesc());
intent.putExtra("IMG", clickedDataItem.getImage());
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
context.startActivity(intent);
}
}
and here is my Details activity
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_details);
dPlace = (TextView) findViewById(R.id.detail_title);
dDesc = (TextView) findViewById(R.id.detail_desc);
dImage = (ImageView) findViewById(R.id.detail_image);
Bundle bundle = getIntent().getExtras();
if (bundle != null) {
String name = bundle.getString("NAME");
String desc = bundle.getString("DESC");
String img = bundle.getString("IMG");
dPlace.setText(name);
dDesc.setText(desc);
Picasso.with(this).load(img).into(dImage);
now, clicking on a item in MainActivity I am able to go to the Details activity. suppose there are 3 items in database, and at first main activity shows only 3 items. but after going to Details activity, and then coming back to main activity, there are 6 items, the earlier 3 items are repeated. and if again I go to the Details activity and come back, there will be 9 items. I used (Activity)context).finish(); in RecyclerViewAdapter to finish the main activity, but I think it finishes the context from which I am able to get the details.
please help.
Sorry for my bad english.
Your firebase loading data items needs to go inside onCreate() as it will only gets called only once if its on backstack an onStart() will get called twice. So just implement the data item loading logic in onCreate instead of onStart()
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mDatabaseReference.addChildEventListener(new ChildEventListener() {
#Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
Places places = dataSnapshot.getValue(Places.class);
placesList.add(places);
placeRecyclerAdapter = new PlaceRecyclerAdapter(MainActivity.this,placesList);
recyclerView.setAdapter(placeRecyclerAdapter);
placeRecyclerAdapter.notifyDataSetChanged();
}
}
Update
placesList.clear();
placesList.add(places);

Load JSON arraylist in separate class and load in another activity

I am trying to load some items from JSON, I am able to get and parse the JSON and load it up in listview when using one activity. However, I want to use a LoadJSON.class to load the JSON, and then the activity can call the json passed and show it in the listview in that activity.
Here is what I have tried:
SongsManager.class
public class SongsManager {
private String TAG = SongsManager.class.getSimpleName();
private static final String API_URL = "http://xxxxxxxxxxxxx.com/jame/mp3/songlist.json";
private List<SolTracks> solTracksList;
private ProgressDialog pDialog;
private final Activity activity;
public SongsManager(Activity activity) {
this.activity = activity;
solTracksList = new ArrayList<>();
pDialog = new ProgressDialog(activity);
fetchSongs();
}
private void fetchSongs() {
pDialog.setMessage("Fetching Playlist...");
pDialog.show();
// Volley's json array request object
JsonArrayRequest req = new JsonArrayRequest(API_URL,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
Log.d(TAG, "Responser = " + response.toString());
pDialog.hide();
if (response.length() > 0) {
// looping through json and adding to movies list
for (int i = 0; i < response.length(); i++) {
try {
JSONObject movieObj = response.getJSONObject(i);
String songTitle = movieObj.getString("title");
String songId = movieObj.getString("id");
String streamUrl = movieObj.getString("stream_url");
SolTracks m = new SolTracks(songTitle, songId, streamUrl);
solTracksList.add(m);
Collections.sort(solTracksList, new TrackComparator());
} catch (JSONException e) {
Log.e(TAG, "JSON Parsing error: " + e.getMessage());
}
}
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e(TAG, "Server Error: " + error.getMessage());
pDialog.hide();
Snackbar snackbar = Snackbar
.make(activity.findViewById(android.R.id.content), "PLEASE CHECK YOUR INTERNET", Snackbar.LENGTH_LONG)
.setAction("DISMISS", new View.OnClickListener() {
#Override
public void onClick(View view) {
}
});
// Changing snackbar background
snackbar.getView().setBackgroundColor(ContextCompat.getColor(activity, R.color.colorPrimary));
// Changing message text color
snackbar.setActionTextColor(Color.YELLOW);
// Changing action button text color
View sbView = snackbar.getView();
TextView textView = (TextView) sbView.findViewById(android.support.design.R.id.snackbar_text);
textView.setTextColor(Color.WHITE);
snackbar.show();
}
});
req.setRetryPolicy(new DefaultRetryPolicy(0, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
// Adding request to request queue
AppController.getInstance().addToRequestQueue(req);
}
public List<SolTracks> getList() {
return solTracksList;
}
Activity class
public class TheMain1 extends AppCompatActivity {
private SwipeRefreshLayout swipeRefreshLayout;
private String TAG = TheMain1.class.getSimpleName();
private static final String API_URL = "http://xxxxxxxxxxx.com/jame/mp3/songlist.json";
private ListView listView;
private SolTracksAdapter adapter;
private ProgressDialog pDialog;
private List<SolTracks> songslist;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_the_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
listView = (ListView) findViewById(R.id.track_list_view);
songslist = new ArrayList<>();
SongsManager songsManager = new SongsManager(this);
songslist = songsManager.getList();
adapter = new SolTracksAdapter(this, songslist);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
SolTracks track = songslist.get(position);
final String stream_url = track.stream_url;
final String id_url = track.id;
Intent intent = new Intent(TheMain1.this, PlayerActivity.class);
intent.putExtra("songPosition", position);
intent.putExtra("streamUrl", stream_url);
startActivity(intent);
}
}
);
}
As it is right now, I know the JSON is loaded from SongsManager, but its just not displaying in the listview of the Activity class. Can anyone help, and show what I'm doing wrong? Thanks
I was able to fix this by implementing Parcelable to send the list to the receiving activity.
public class SolTracks implements Parcelable {
public String title;
public String id;
public String stream_url;
}
Sending the list from the Activity A:
Intent intent = new Intent(TheMain.this, PlayerActivity.class);
Bundle bundle = new Bundle();
bundle.putParcelableArrayList("mylist", solTracksList);
intent.putExtras(bundle);
intent.putExtra("songPosition", position);
startActivity(intent);
and then receiving in Activity B:
Bundle extras = getIntent().getExtras();
if (extras != null) {
songPosition = extras.getInt("songPosition");
trackList = extras.getParcelableArrayList("mylist");
}

specific sound must play when item is clicked

I am making dictionary app having sound sample, when an item in the list is click, a new activity will open containing details view and a button. Can someone help me how can I assign the specific sound to the button. The sound files are placed in raw folder. for example, I click the item 'araw',the details will show and the button must play the sound araw...Pls help me...
heres the codes:
ListView lv;
SearchView sv;
String[] tagalog= new String[] {"alaala (png.)","araw (png.)","baliw (png.)","basura (png.)",
"kaibigan (png.)","kakatuwa (pu.)", "kasunduan (png.)","dambuhala (png.)",
"dulo (png.)","gawin (pd.)","guni-guni (png.)","hagdan (png.)","hintay (pd.)",
"idlip (png.)","maganda (pu.)","masarap (pu.)", "matalino (pu.)"};
ArrayAdapter<String> adapter;
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lv = (ListView) findViewById(R.id.listView1);
sv = (SearchView) findViewById(R.id.searchView1);
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,tagalog);
lv.setAdapter(adapter);
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String tagword =tagalog[position];
String[] definition = getResources().getStringArray(R.array.definition);
final String definitionlabel = definition[position];
String[] cuyuno = getResources().getStringArray(R.array.cuyuno);
final String cuyunodefinition = cuyuno[position];
String[] english = getResources().getStringArray(R.array.english);
final String englishdefinition = english[position];
Intent intent = new Intent(getApplicationContext(), DefinitionActivity.class);
intent.putExtra("tagword", tagword);
intent.putExtra("definitionlabel", definitionlabel);
intent.putExtra("cuyunodefinition",cuyunodefinition);
intent.putExtra("englishdefinition", englishdefinition);
startActivity(intent);
}
});
sv.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String text) {
return false;
}
#Override
public boolean onQueryTextChange(String text) {
adapter.getFilter().filter(text);
return false;
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
return super.onCreateOptionsMenu(menu);
}
}
DefinitionActivity.java
public class DefinitionActivity extends AppCompatActivity {
String tagalogword;
String worddefinition;
String cuyunoword;
String englishword;
int[] sounds = new int[]{R.raw.alaala,
R.raw.araw,
R.raw.baliw,
R.raw.basura,
R.raw.kaibigan,
R.raw.kakatuwa,
R.raw.kasunduan,
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_definition);
TextView wordtv = (TextView) findViewById(R.id.wordtv);
TextView definitiontv = (TextView) findViewById(R.id.definitiontv);
TextView cuyunotv = (TextView) findViewById(R.id.cuyunotv);
TextView englishtv = (TextView) findViewById(R.id.englishtv);
Button play = (Button) findViewById(R.id.playbty);
final Bundle extras = getIntent().getExtras();
if (extras != null) {
tagalogword = extras.getString("tagword");
wordtv.setText(tagalogword);
worddefinition = extras.getString("definitionlabel");
definitiontv.setText(worddefinition);
cuyunoword = extras.getString("cuyunodefinition");
cuyunotv.setText(cuyunoword);
englishword = extras.getString("englishdefinition");
englishtv.setText(englishword);
}
play.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// I do not know how to play the audio when button click
}
});
}
}
Like Pedif said, you should use SoundPool for playing short sounds.
Here is Code from my Tetris like game, the Activity creates the Instance and get a callback when sounds were loaded.
Example as Singleton:
public class Sounds {
private Context ctx;
private static Sounds mSounds = null;
private static SoundPool mSPool = null;
private int sound_gameover;
private int sound_teil_drehen;
private int sound_1_zeile;
private int sound_2_zeile;
private int sound_3_zeile;
private int sound_4_zeile;
private int soundsToLoad = 6;
/**
* Volumecontrol
*/
private AudioManager audioManager;
private float actualVolume;
private float maxVolume;
private float volume;
private IOnSoundReady callback = null;
public static Sounds getInstance(Context ctx, IOnSoundReady mCallback){
if(mSPool == null){
mSounds = new Sounds(ctx, mCallback);
}
return mSounds;
}
private Sounds(Context ctx, IOnSoundReady mIOSoundReady) {
this.ctx = ctx;
this.callback = mIOSoundReady;
initVolume();
AsyncTask<Void, Void, Void> mTask = new AsyncTask<Void, Void, Void>() {
#Override
protected Void doInBackground(Void... params) {
initSoundPool();
return null;
}
};
mTask.execute();
}
public void unprepare() {
if (mSPool == null) return;
mSPool.release();
mSPool = null;
}
private void initSoundPool(){
mSPool = new SoundPool(6, AudioManager.STREAM_MUSIC, 0);
mSPool.setOnLoadCompleteListener(new SoundPool.OnLoadCompleteListener() {
#Override
public void onLoadComplete(SoundPool soundPool, int sampleId, int status) {
Log.w(TAG, "loaded soundid: " + sampleId);
if(--soundsToLoad == 0 && callback != null){
callback.onSoundReady();
}
}
});
sound_gameover = mSPool.load(ctx, R.raw.game_over, 1);
sound_teil_drehen = mSPool.load(ctx, R.raw.rotate, 1);
sound_1_zeile = mSPool.load(ctx, R.raw.line_1,1);
sound_2_zeile = mSPool.load(ctx, R.raw.line_2, 1);
sound_3_zeile = mSPool.load(ctx, R.raw.line_3, 1);
sound_4_zeile = mSPool.load(ctx, R.raw.line_4, 1);
}
/**
* calculate volume
*/
private void initVolume(){
audioManager = (AudioManager) ctx.getSystemService(SpielActivity.AUDIO_SERVICE);
actualVolume = (float) audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
maxVolume = (float) audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
volume = actualVolume / maxVolume;
}
/**
* plays a sound
* #param soundid
*/
public void playSound(int soundid){
mSPool.play(soundid, volume, volume,1, 0, 1f);
}
}
Interface used when sounds are loaded, implemented by activity:
public interface IOnSoundReady {
void onSoundReady();
}
Usage in your activity:
Sounds mySounds = Sounds.getInstance(this, this);
Play sound:
public static void playSound(int soundid) {
mySounds.playSound(soundid);
}
Hope I could help a bit.
// Try this way
ListView lv;
SearchView sv;
String[] tagalog= new String[] {"alaala (png.)","araw (png.)","baliw (png.)","basura (png.)",
"kaibigan (png.)","kakatuwa (pu.)", "kasunduan (png.)","dambuhala (png.)",
"dulo (png.)","gawin (pd.)","guni-guni (png.)","hagdan (png.)","hintay (pd.)",
"idlip (png.)","maganda (pu.)","masarap (pu.)", "matalino (pu.)"};
ArrayAdapter<String> adapter;
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lv = (ListView) findViewById(R.id.listView1);
sv = (SearchView) findViewById(R.id.searchView1);
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,tagalog);
lv.setAdapter(adapter);
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String tagword =tagalog[position];
String[] definition = getResources().getStringArray(R.array.definition);
final String definitionlabel = definition[position];
String[] cuyuno = getResources().getStringArray(R.array.cuyuno);
final String cuyunodefinition = cuyuno[position];
String[] english = getResources().getStringArray(R.array.english);
final String englishdefinition = english[position];
Intent intent = new Intent(getApplicationContext(), DefinitionActivity.class);
intent.putExtra("tagword", tagword);
intent.putExtra("definitionlabel", definitionlabel);
intent.putExtra("cuyunodefinition",cuyunodefinition);
intent.putExtra("englishdefinition", englishdefinition);
// put position of the file
intent.putExtra("position", position);
startActivity(intent);
}
});
sv.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String text) {
return false;
}
#Override
public boolean onQueryTextChange(String text) {
adapter.getFilter().filter(text);
return false;
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
return super.onCreateOptionsMenu(menu);
}
// DictionaryActivity.class
public class DefinitionActivity extends AppCompatActivity {
String tagalogword;
String worddefinition;
String cuyunoword;
String englishword;
int[] sounds = new int[]{R.raw.alaala,
R.raw.araw,
R.raw.baliw,
R.raw.basura,
R.raw.kaibigan,
R.raw.kakatuwa,
R.raw.kasunduan,
};
private int songPosition = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_definition);
TextView wordtv = (TextView) findViewById(R.id.wordtv);
TextView definitiontv = (TextView) findViewById(R.id.definitiontv);
TextView cuyunotv = (TextView) findViewById(R.id.cuyunotv);
TextView englishtv = (TextView) findViewById(R.id.englishtv);
Button play = (Button) findViewById(R.id.playbty);
final Bundle extras = getIntent().getExtras();
if (extras != null) {
tagalogword = extras.getString("tagword");
wordtv.setText(tagalogword);
worddefinition = extras.getString("definitionlabel");
definitiontv.setText(worddefinition);
cuyunoword = extras.getString("cuyunodefinition");
cuyunotv.setText(cuyunoword);
englishword = extras.getString("englishdefinition");
englishtv.setText(englishword);
songPosition = extras.getInt("position");
}
play.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Play it here like
MediaPlayer mediaPlayer=MediaPlayer.create(DictionaryActivity.class,sounds[position]);
mediaPlayer.start();
}
});
}
}
You have to use SoundPool.
For sound effects which are short you would use SoundPool otherwise you should use MediaPlayer.

Creating a list within a list

With support, I have created a list of arrays that populates JSON data. When a user clicks on an item in the list of arrays, it takes them to an activity page that provides them more information about that particular item.
In particular, below are my 3 questions:
In the single item page, I added an "add more" button, and I would want that when the button is click, that particular item gets recorded until 3 different item in the list of arrays have been selected.
I would want to update the user of how many item have been selected thus far in a textview in the single item page.
I have added a confirm button, but I would want to set a condition, where it would only go to the next activity once 3 item have been selected.
Transmit the user recorded information to parse.com. Where every time, a user click on add more, it updates parse on the activity that have been selected by the user, where I could have three column for activity 1, activity 2, and activity 3 within my class.
Below is my list of arrays code:
public class EventsActivity extends Activity{
private static final String URL_WEB_SERVICE = "http://dooba.ca/analytics/ed.php";
private GridView gv;
private ArrayList<Events_List> container;
private ArrayList<Events_List> items;
public Uri list_item_bac;
public String list_item_name;
public String list_item_description;
public String single_list_item_description;
public String list_item_price;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.events_list_layout);
gv = (GridView) findViewById(R.id.gridview);
container = new ArrayList<Events_List>();
//download JSON
listDownload();
GridView s = (GridView) findViewById(R.id.gridview);
s.setOnItemClickListener(new OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(EventsActivity.this,EventSingleItemActivity.class);
intent.putExtra("list_item_name", container.get(position).getList_item_title());
intent.putExtra("single_list_item_description", container.get(position).getSingle_list_item_description());
startActivity(intent); //start Activity
}
});
}
public void listDownload(){
RequestQueue volley = Volley.newRequestQueue(this);
JsonObjectRequest json = new JsonObjectRequest(Method.GET, URL_WEB_SERVICE, null, ResponseListener(), ErrorListener());
volley.add(json);
}
private Response.Listener<JSONObject> ResponseListener() {
return new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
//your JSON Array
JSONArray array = response.getJSONArray("list_item");
for(int i = 0; i < array.length(); i++){
container.add(convertirAnuncio(array.getJSONObject(i)));
}
} catch (JSONException e) {
e.printStackTrace();
}
gv.setAdapter(new AdapterEvents(getApplicationContext(),container));
}
};
};
private Response.ErrorListener ErrorListener() {
return new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) { }
};
}
//object JSON
private final Events_List convertirAnuncio(JSONObject obj) throws JSONException {
long id = obj.getLong("id"); //id
String list_item_name = obj.getString("list_item_name");
String list_item_description = obj.getString("list_item_description");
String single_list_item_description = obj.getString("single_list_item_description");
Uri uri = Uri.parse(obj.getString("list_item_bac"));
return new Events_List(id,single_list_item_description,list_item_name,list_item_description,list_item_price, uri);
}
}
Below is my single item click page
public class EventSingleItemActivity extends Activity {
// Declare Variables
String list_item_name;
String list_item_description;
String list_item_price;
String single_list_item_description;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_events_single_item);
Intent i = getIntent();
list_item_name = i.getStringExtra("list_item_name");
single_list_item_description = i.getStringExtra("single_list_item_description");
TextView txtname = (TextView) findViewById(R.id.name);
TextView txtsdescription = (TextView) findViewById(R.id.sdescription);
// Set results to the TextViews
txtname.setText(list_item_name);
txtsdescription.setText(single_list_item_description);
Button mConfirm2 = (Button)findViewById(R.id.bConfirm2);
mConfirm2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
EventSingleItemActivity.this.startActivity(new Intent(EventSingleItemActivity.this, MatchingActivity.class));
}
});
Button mcancel = (Button)findViewById(R.id.bRemove);
mcancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
EventSingleItemActivity.this.startActivity(new Intent(EventSingleItemActivity.this, EventsActivity.class));
}
});
}
}
I have looked into the following tutorial:
http://theopentutorials.com/tutorials/android/listview/android-multiple-selection-listview/
but this is not exactly what I want to achieve.
ArrayList< ArrayList > yourVar = new ArrayList< ArrayList >();
same should apply for a list, you can also use a 2d array, but those are annoying to fill.

Categories