I'm developing an android Wallpaper app consists of 2 activity, main activity displays the images from the internet in ListView and the second activity displays the preview of that image.
my problem is when I press the back button in preview activity to go back to the main activity, the main activity displays the images from the beginning and I would like to display the images from the last I clicked on.
The following code in onCreate() method in Main Activity:
// Find a reference to the {#link ListView} in the layout
ListView gameListView = findViewById(R.id.list);
mEmptyStateTextView = findViewById(R.id.empty_view);
gameListView.setEmptyView(mEmptyStateTextView);
// Create a new adapter that takes an empty list of games as input
mAdapter = new GamesAdapter(this, new ArrayList<Games>());
// Set the adapter on the {#link ListView}
// so the list can be populated in the user interface
gameListView.setAdapter(mAdapter);
// Set an item click listener on the ListView, which sends an intent to a web browser
// to open a website with more information about the selected game.
gameListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
// Find the current game that was clicked on
Games currentGame = mAdapter.getItem(position);
// Convert the String URL into a URI object (to pass into the Intent constructor)
Uri gameUri = Uri.parse(currentGame.getUrl());
String name = currentGame.getName();
// Create a new intent to view the game URI
Intent i = new Intent(GamesActivity.this, PreviewActivity.class);
i.setData(gameUri);
i.putExtra("name", name);
startActivity(i);
}
});
The following code in onCreate() method in Preview Activity:
final Uri i = getIntent().getData();
String profile = getIntent().getStringExtra("name");
photographer.setText(profile);
Picasso.with(this).load(i).into(img);
saveImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
downloadFile(i);
}
});
I think what your are looking for is the method onSaveInstanceState(Bundle outState) here you can save your values in the outState and get them in onCreate() at the savedInstanceState
here is a very good example how to use it.
I think you want to preserve the scroll distance. For that what you need to do is you can preserve using Bundle object. But you can also clear current activity then you will get the same results.
Add this outside the onCreate() method(this is java):
#Override
public void onBackPressed() {
this.finish(); //important
}
finish() clears activity from back stack.
Related
I have a ListView being populated via a SimpleCursorAdapter. The row uses a FrameLayout to allow the user to tap on the left or right side of the row, which will trigger two different activities. I have the tap working and they go to the appropriate activities, but I am stuck on figuring out how to make the resulting views show the data related to the row tapped on.
The code used to go to the new activities are:
public void goToCaptureBonus (View View) {
Log.e(TAG,"goToCaptureBonus");
Intent goToCaptureBonus = new Intent(this,captureBonus.class);
startActivity(goToCaptureBonus);
}
public void goToBonusDetail (View View) {
Log.e(TAG,"goToBonusDetail");
Intent goToBonusDetail = new Intent(this,bonusDetail.class);
startActivity(goToBonusDetail);
}
I am currently using the following in my onCreate, but I think this is trying to read the entire list view, not just the two frames I made in my row.
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent nextActivity = new Intent(bonusListing.this, bonusListing.class);
startActivity(nextActivity);
}
});
I want to have the app pass the row data to the goToCaptureBonus and goToBonusDetail activities when their associated frames are tapped, so that those activities will know what data to read from my DB.
I have a RecyclerView list of CardViews created when a user enters a bunch of data with some EditTexts. A click on a single CardView from the list loads a DetailsActivity that shows only that specific CardView to the user. Another click on that CardView loads an EditActivity that allows the user to edit the original data they entered.
When the user saves any edited data, the EditActivity closes and the user is returned to the specific CardView. But the CardView is not updated with the edited data. The RecyclerView list of CardViews does update as expected because if I backspace out of the DetailsActivity and return to the MainActivity, then the CardView that was edited shows up correctly. How do I refresh the view for the single CardView in the DetailsActivity?
MainActivity (the RecyclerView list)
...
#Override
public void onItemClick(int position, final View view) {
// Create a new intent to send data from this MainActivity to the DetailsActivity
Intent intent = new Intent(this,CardViewDetails.class);
// Send the position of the CardView item that was clicked on in the intent.
intent.putExtra("position",position);
startActivity(intent);
}
DetailsActivity (for the single CardView)
...
// Get the position of the clicked on RecyclerView list CardView from
// the MainActivity's intent bundle.
Bundle extras = getIntent().getExtras();
if (extras != null) {
// get the CardView item using the int position from the
// MainActivity's onItemClick() and the putExtra in the intent.
position = extras.getInt("position", 0); // 0 is default value
}
cardView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// pass the position variable to the start method of
// EditActivity so get the correct data from the db can
// be loaded onto the EditText lines, etc. of the
// EditActivity and that can then be used to pass the
// data back to the MainActivity.
EditActivity.start(CardViewDetails.this,listItems.get(position));
}
});
EditActivity (for editing the original CardView data)
...
// Launches the activity to edit an Item (CardView) that was clicked on from the
// RecyclerView list in the MainActivity file. The intent brings the item's
// position in the RecyclerView Adapter so the correct Item is edited.
public static void start(Context context, ListItem item) {
Intent intent = new Intent(context, ActActivity.class);
// From the OnItemClick method in the MainActivity the RecyclerView item
// position from the Adapter is passed into a putExtra bundle that the
// intent carries to this Activity. The data is then copied in the onCreate()
// below using getIntent().getParcelableExtra(). So this is to update an
// existing CardView item.
intent.putExtra(ActActivity.class.getSimpleName(),item);
context.startActivity(intent);
}
public void onClickSaveEdits(View v) {
// Update the user EditText input to the database.
sqLiteDB.update(item);
// Close the EditActivity.
finish();
**what am I missing here to update/refresh the view for the just edited CardView that is shown in the DetailsActivity?**
}
Call notifyDataSetChanged() on your adapter whenever you make a change to the data you're using for the RecyclerView.
For example, your onClickSaveEdits(View v) method would look as follows:
public void onClickSaveEdits(View v) {
// Update the user EditText input to the database.
sqLiteDB.update(item);
adapterObjectHere.notifyDataSetChanged();
// Close the EditActivity.
finish();
}
My first activity contains a listview with textviews in each cell and uses a custom adapter. So if you click on any of the items, it will open up a form activity containing textfields. The user can fill up the details and once they press the save form button the details appear on the listview. Now I am trying to add items to the list dynamically. I have created a button which when clicked adds a new instance item so that more users can register the same way. I have been able to implement these functions. However, my problem now is when i click on the newly added item and go to the form activity and click save, i am not able to see the newly added entry after i come back to the listview activity.All I see is the first entry alone. So i am guessing it gets destroyed as soon as i leave the activity. How to ensure all newly added items are not destroyed when i keep moving between these two activities.
Here is my code of the ListView Activity:
public class FormTableActivity extends Activity {
private PassengerListAdapter adapter;
Button add_passenger;
String mrzdata,ic_data,name_data;
SharedPreferences nPref;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.final_display_listview);
nPref = PreferenceManager.getDefaultSharedPreferences(this);
mrzdata = nPref.getString("MRZ", "");
name_data = nPref.getString("resultData", "");
ic_data = nPref.getString("icdata", "");
final ListView lv1 = (ListView) findViewById(R.id.custom_list);
adapter = new PassengerListAdapter(this);
adapter.add(new CustomerDetails(ic_data, name_data, mrzdata));
add_passenger = (Button) findViewById(R.id.add_user);
add_passenger.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// mrzdata = "";
// name_data = "";
// ic_data = "";
adapter.add(new CustomerDetails(ic_data, name_data, mrzdata));
}
});
lv1.setAdapter(adapter);
lv1.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> a, View v, int position, long id) {
Intent intent = new Intent(v.getContext(), FirstActivity.class);
startActivity(intent);
}
});
}
The easiest way to pass data between Intent is
Intent intent = new Intent(getBaseContext(), your_list_view_activity.class);
intent.putExtra("String_Key", data1);
//data1 could be an array of string where you have hold the values previously
startActivity(intent);
now on your list_view_activity
Bundle extras = getIntent().getExtras();
if (extras != null) {
String [] value = extras.getString("String_Key");
}
This way you won't get any exception but you get to populate your listView if there is data.
Another way to get data is via SharedPreference but I won't recommend it as it increases the size of the app.
You have to save these newly added items somewhere , e.g. to a SQLite database and retrieve them on create to populate the listview
You can see here if You want, the code is commented ,
here I have a listview with custom adapter with two items
the feed's name and it's url
i add URL and name using a text input dialog (with two edit text), save to DB, and retrieve them on create to populate the listview
https://github.com/enricocid/iven-feed-reader/blob/master-as/project/app/src/main/java/com/iven/lfflfeedreader/mainact/ListActivity.java
Explaining the structure: In MainActivity I have a drawer menu and a fragment to display contents. From the drawer I can choose a category and a list of items in that category is read from database and is displayed in a listView in the content fragment.
When an item from the list view is clicked, a DetailActivity will start.
Problem: In the DetailActivity there is a button to remove the item from database. When this Item is pressed the DetailActivity closes. And the previous content fragment in the MainActivity is displayed. (like pressing back button) But the problem is that the item I deleted is still shown in the listView. I have go to the relevant category so that the listView refreshes and that item isn't there anymore.
What I expect: What I want is that when I delete the item in the DetailActivity and return to the previous activity, the listView is automatically updated.
What I've done: I know I can use onActivityResult like this:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
// Refresh Bookmarks page when a bookmark is deleted
if (requestCode == LESSON_DETAIL_ACTIVITY && resultCode == -1) {
datasource.open();
lessons = datasource.findMyLessons();
refreshDisplay(context, view, category, i); // Problem Here!
}
}
As you see my refreshDisplay method takes 4 arguments. Originally these arguments are sent to the DetailActivity. (when a list item is clicked in the fragment inside MainActivity)
When I press "delete item" button in the DetailActivity and it closes. I don't know how to retrieve those argument so that I can refresh the list.
Here I post the code of my refreshDisplay method and how I call it just in case its needed.
I call refreshDisplay method inside a fragment (in the MainActivity) and the refreshDisplay itself is in the MainActivity.
public static class contentFragment extends Fragment {
public static final String ARG_CATEGORY_NUMBER = "category_number";
public contentFragment() {
// Empty constructor required for fragment subclasses
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_content, container, false);
int i = getArguments().getInt(ARG_CATEGORY_NUMBER);
String category = getResources().getStringArray(R.array.category)[i];
((MainActivity) this.getActivity()).refreshDisplay(this.getActivity(),rootView, category, i);
getActivity().setTitle(category);
return rootView;
}
}
my refreshDisplay method is:
public void refreshDisplay(Context context, View view, String category, int i) {
List<Lesson> lessonByCategory = datasource.findByCategory(category, i);
final ListView lv = (ListView) view.findViewById(R.id.listView);
final ArrayAdapter<Lesson> adapter = new LessonListAdapter(context, lessonByCategory);
lv.setAdapter(adapter);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick (AdapterView<?> parent, View view, int position, long id) {
Log.i(LOGTAG, "onListItemClick called");
ArrayAdapter<Lesson> m_adapter = adapter;
// get the Lesson object for the clicked row
Lesson lesson = m_adapter.getItem(position);
// use this if your `refreshDisplay()` method is in your activity
Intent intent = new Intent(MainActivity.this, LessonDetailActivity.class);
isStared = datasource.isStared(lesson);
intent.putExtra(".model.Lesson", lesson);
intent.putExtra("isStared", isStared);
startActivityForResult(intent, LESSON_DETAIL_ACTIVITY);
}
});
}
Can anyone please help me?
Edit 1: In my code, in the onActivityResult I have called refreshDisplay(context, view, category, i); But please notice those arguments I have passed are not defined. Without the correct arguments refreshDisplay doesn't work!
Edit 2: I have a drawer navigation that contains a list of categories. When I click on one of the categories, In my content fragment the onCreateView calls refreshDisplay ** and puts context & View arguments plus category & i which are the name and position of the category chosen. Now refreshDisplay takes those arguments and and creates the list of items of that category and shows it in the content Fragment. refreshDisplay has a list adapter and listener that when clicked opens DetailActivity. From DetailActivity I can delete that item and DetailActivity is closed. I'm back to the list. The list still shows that deleted item. I want to update the list.
Just try my hints on you code .... I hope it might be solve your problem
call this method after delete item from you adapter. It will refresh the adapter content.
notifyDataSetChanged()
You can pass the Context to following method as first param..
refreshDisplay(/*this.getActivity()/ context,rootView, category, i);
Solution:-
declare your list listCategory static in your Activity class(global variable)
declare your listView as instance variable of your activity class.
In DetailActivity delete the listCategory item(You can access it cause it is static)
like this:-
MainActivity.listCategory.remove(<the position of that detail>);
declare your adapter also as instance variable of your activity class.
no need of your refreshDisplay method just use adapter.notifyDataSetChanged() in onActivityResult() method
I am kind of new to Android development. Could you please tell me, how to navigate to another screen using onListItemClick. I have 200 items in a ListView. If i click an item from the ListView, it has to navigate to another screen which should show the details of the clicked item.
To get what you want you can do something like this...
1>create another activity with certains controls in which you can place your values...
2>on itemclick() of listview...
a>create intent and set values to pass to new activity
b>start new activity with this intent.
3>in oncreate() of new activity
a>retrive the values from intent
b>populate your controls using the values...
I am assuming you are getting the list and detail of actor from database.
I have used the same walk through to display recipe detail of selected recipe in my app.
public class ActorList extends Activity {
ListView myActorList=null;
public final static String selectedActor_ID="will Keep Actor ID";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_actor_list);
//initialize controls
myActorList.setAdapter(adapter);
myActorList.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View v,
int position, long id) {
// TODO Auto-generated method stub
Intent i= new Intent(ActorList.this,ActorDetail.class);
// you have to pass the actor id to next activity
// you can get this actor id from argument of type "long"
i.putExtra(selectedActor_ID, String.valueOf(id));
startActivity(i);
}
});
}
}
//Other Activity To show Detail..
//get the ID of Selected Actor on other activity say "ActorDetail"
public class ActorDetail extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_actor_detail);
ActorID=getIntent().getStringExtra(ActorList.selectedActor_ID);
// now as you have the id here for that particular actor
//fetch the detail of that selected actor thru id and bind it to your layout.
}
}
You need to register the other activity in Manifest file also like this
<activity
android:name=".otherscreenActivity"
</activity>