I have an android app where a listview displays a few items - 'films', and when you click on an item it gives you the option to delete or update the item. The delete works fine, and when you click update it opens up a new fragment with the details of the film correctly populated in edit text boxes. I'm trying to figure out how to get the update button on this new Fragment to work.
Firstly I have it extending FragmentActivity, so is this an Activity, or a Fragment? Should I be using something else? When I go to add my button on click listener like I did in the previous 'ListFragment' it won't let me call 'getActivity()' or to reference the currently selected item in the list 'getListAdapter()'. What should I be calling here/how do I reference the current Fragment/Activity?
Should I have these outside of the onCreate in a separate method? I know there is a lot of questions here, but I am really trying to understand what exactly is going on. Any help would be really appreciated. Here is what my code looks like for the FragmentActivity
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.film_activity);
//adds listeners to buttons
updateButton = (Button) findViewById(R.id.update_button);
filmTitleView = (EditText) findViewById(R.id.textView_title);
filmDirectorView = (EditText) findViewById(R.id.textView_director);
filmYearView = (EditText) findViewById(R.id.textView_year);
//retrieves object from intent sent through from previous activity
//assigns variables
Intent intObj = getIntent();
filmTitle = (String) intObj
.getSerializableExtra("title");
filmDirector = (String) intObj
.getSerializableExtra("director");
filmYear = (String) intObj
.getSerializableExtra("year");
filmID = (Integer) intObj
.getSerializableExtra("id");
//Greeting message text set
filmTitleView.setText(filmTitle);
filmDirectorView.setText(filmDirector);
filmYearView.setText(filmYear);
System.getProperty("line.separator");
final Film f1 = (Film)(getListAdapter()).getItem(filmID);
updateButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(getActivity(),MainActivity.class);
Context context = getActivity();
FilmStoreOpenHelper helper = new FilmStoreOpenHelper(context);
SQLiteDatabase db = helper.getWritableDatabase();
FilmDAO dao = SQLiteFilmDAO.getInstance(db);
FilmStore fs1 = FilmStore.getInstance(context);
fs1.addFilm(f1);
boolean updated = dao.update(f1);
if (deleted){
Toast.makeText(getActivity(), ("Film " + f1.getTitle() + " Updated"), Toast.LENGTH_LONG).show();
db.close();
startActivity(i);
}else{
Toast.makeText(getActivity(), "Not Updated, try again", Toast.LENGTH_LONG).show();
}
}
});
}
Replace any calls to getActivity() with this. A FragmentActivity is a special Activity from the support package that is designed to be used with Fragments. If you're developing for higher than API 11, you can use a regular Activity.
Related
I'm trying to add details of movies to Recyclerview on Button Click. I have 2 Activities. I can add the details of movies in the first activity and I can view the list of movies in the Second Activity. The first activity contains a submit button to add movies.
But the issue I'm facing is that I can add movies to the first row only. If i try to add another movie it replaces the first row. I want to create a list of movies on button click. How do I do this? The below code is the Main Activity (First Activity).
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setActionBarColour();
clickEvents();
}
private void clickEvents()
{
final EditText editTextMovieName = findViewById(R.id.movieName);
final EditText editTextGenre = findViewById(R.id.genre);
final EditText editTextReleaseYear = findViewById(R.id.year);
Button submit = findViewById(R.id.btnSubmit);
Button movieList = findViewById(R.id.btnMovieList);
final Bundle bundle = new Bundle();
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String name = editTextMovieName.getText().toString();
String genre = editTextGenre.getText().toString();
String year = editTextReleaseYear.getText().toString();
bundle.putString("MOVIE_NAME", name);
bundle.putString("GENRE", genre);
bundle.putString("YEAR", year);
}
});
movieList.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this, MovieListActivity.class);
intent.putExtras(bundle);
startActivity(intent);
}
});
}
private void setActionBarColour()
{
ActionBar actionBar;
actionBar = getSupportActionBar();
ColorDrawable colorDrawable = new ColorDrawable(Color.parseColor("#3498DB"));
assert actionBar != null;
actionBar.setBackgroundDrawable(colorDrawable);
}
}
This below code is only a function in the Second Activity to get the data
private void prepareMovieData()
{
Intent intent = getIntent();
Bundle bundle = intent.getExtras();
String movieName = bundle.getString("MOVIE_NAME");
String genre = bundle.getString("GENRE");
String year = bundle.getString("YEAR");
Movie movie = new Movie(movieName,genre,year);
movieList.add(movie);
}
If I edit the above code to
Movie movie = new Movie(movieName,genre,year);
movieList.add(movie);
Movie movie2 = new Movie(movieName,genre,year);
movieList.add(movie2);
I can add only 2 movies. If i want to put 3 movies then I would have to put a third statement like this
Movie movie3 = new Movie(movieName,genre,year);
movieList.add(movie3);
The more movies I want the more lines of code I have to write. So how do I put a large number of movies on click?
As per your question detailing we can conclude that
1) On Submit move to next Activity with movie details and add in adapter.
2) Press back
3) Repeat step 1 with new details.
So here revisiting next screen will not have previous data. For that you have to save data in local storage and display.
As i review your code when you call the second activity its clear your model data and make its easy use parcable data into model class which help you to pass the model class from one activity to another use onActivityresult for this and add this you model into list to add multiple data through intent. or you can save your data into local sql-lite and fetch data into next activity
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
I have a problem to receive a text from edittext in one activity intent to a listview on another intent.
This is what I have done so far:
Activity B:
Button btn = (Button) findViewById(R.id.button2);
final EditText edit = (EditText) findViewById(R.id.editText1);
btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent i = new Intent(addnote.this, MainActivity.class);
i.putExtra("text", edit.getText().toString());
startActivity(i);
Activity A: where the list view is I just don't know how to receive this text when I clicked the button 2
Basically all you want to do is call getStringExtra() to grab whatever you originally assigned during putExtra(). So for example: In Activity A's onCreate(), you'll want to do this:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_a);
mYourString = getIntent().getStringExtra("text");
}
Keep in mind, that Android recommends prefacing the names of the objects your storing with the application's package name. So instead of using "text" you should use "com.example.myproject.text".
thank you for that but I have problem receiving the data and placing it into my list view in my activity A i have done so far :
Intent i = getIntent();
String mdata = getIntent().getStringExtra("text");
ListView listv = (ListView) findViewById(R.id.notelist);
ArrayAdapter<String> Adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, mdata);
listv.setAdapter(Adapter);
I have a button in a TabActivitythat when clicked, opens anAlertDialogwith 2EditTextViews` for a name and number.
When I click the Ok Button to close the Dialog, I want to pass the name back into a ListView on the TabActivity. I can get the name to pass back to the EditText box mAlertDialog on the TabActivity. But something other than the name is being displayed in the ListView.
It looks like a reference to the object "widget" (Widget is an object of the class Device, which has getName, setName methods), com.mypackage.Device#419226e0.
I'll try to post the relevant code below (yes, I know I'm not using Fragments. I found it difficult to implement horizontal scrollable tabs with a ListView with Fragments):
#SuppressWarnings("deprecation")
public class MainActivity extends TabActivity implements OnClickListener {
public static ArrayList<Device> deviceList = new ArrayList<Device>();
public static ArrayAdapter<Device> deviceAdapter=null;
private static ListView deviceListView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTabHost= getTabHost();
TabHost.TabSpec spec;
Intent intent;
rButton = (Button)findViewById(R.id.button_register);
mAlertDialog = (EditText)findViewById(R.id.edittextresult_Name);
rButton.setOnClickListener(onRegister);
intent = new Intent (this, devices.class);
spec = mTabHost.newTabSpec("devices")
.setIndicator("Devices")
.setContent(R.id.devices);
mTabHost.addTab(spec);
deviceListView=(ListView)findViewById(R.id.rdevices);
//Attach array adapter to data array "deviceList"
deviceAdapter = new ArrayAdapter<Device>(this,android.R.layout.simple_list_item_1, deviceList);
//connect adapter "deviceAdapter" to listview widget so the activity listview is populated with data from the array
deviceListView.setAdapter(deviceAdapter);
}
private View.OnClickListener onRegister = new View.OnClickListener() {
public void onClick(View v) {
String title = "Register";
String buttonOk = "OK";
String buttonCancel = "Cancel";
String madd = "address";
String name = "widget name";
//get rdevice.xml view
LayoutInflater li = LayoutInflater.from(context);
View rView = li.inflate(R.layout.rdevice, null);
AlertDialog.Builder adRegister = new AlertDialog.Builder(context);
//set rdevice.xml to adRegister builder
adRegister.setView(rView);
//set title
adRegister.setTitle(title);
//Set EditText views to get user input
final EditText mField = (EditText)rView.findViewById(R.id.editText_Address);
final EditText nField = (EditText)rView.findViewById(R.id.editText_WidgetName);
//set dialog message
adRegister.setMessage("Message")
.setCancelable(false)
.setPositiveButton(buttonOk, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int BUTTON_POSITIVE) {
// TODO Auto-generated method stub
Device widget = new Device();
String madd = mField.getText().toString();
String name = nField.getText().toString();
widget.setName(name);
widget.setAddress(madd);
Log.d(TAG, "Address: " + madd);
Log.d(TAG, "Widget name: " + name);
//get user input and set it to result on main activity
mAlertDialog.setText(nField.getText());
deviceAdapter.add(widget);
deviceAdapter.notifyDataSetChanged();
}
})
.setNegativeButton(buttonCancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int BUTTON_NEGATIVE) {
}
});
//Create alert dialog
AlertDialog alertDialog = adRegister.create();
//show it
adRegister.show();
}
};
On debug, there are no errors in logcat.
However, when I watch the expression mAlertDialog it says
Unable to retrieve the correct enclosing instance of this
Even though the correct name is displayed in the app. When I let the program finish after debug, this reference is displayed in the ListView "com.mypackage.Device#419226e0" instead of the name I typed in the AlertDialog box.
Does this have something to do with scope or anonymous inner classes? Please help. I'm not that familiar with Java so I getting lost in the nuts and bolts here.
Ok I got it to work. This was very helpful: http://www.ezzylearning.com/tutorial.aspx?tid=6816874 , specifically this quote
You may be wondering how the ListView will display the Product object and which property of the Product object will be displayed. The answer is very simple, by default Android ListView control renders a simple TextView inside every ListView item and TextView control can only display simple text. Notice how the toString() function is overridden in the Product class we defined above. Whatever String you will return from the object toString() function will be displayed in the TextView rendered in the ListView items.
Basically, in my Device.java class, I had to override the toString method to specify which object member to pass, so I included this code
#Override
public String toString(){
return this.name;
}
I have two java classes, HelloAndroidActivity and GetTasks. I want to try to get the text from the Edit Text box from the first activity on clicking the button and get that value in the next activity GetTasks and display it in the text view. My code is as shown:
HelloAndroidActivity
Button save = (Button) findViewById(R.id.save);
save.setOnClickListener(new OnClickListener() {
public void onClick (View v) {
Intent i = new Intent(HelloAndroidActivity.this, GetTasks.class);
//i.setClass(HelloAndroidActivity.this, GetTasks.class);
EditText taskname = (EditText) findViewById(R.id.task_name);
String task_name = taskname.getEditableText().toString();
Log.d("Task Name", task_name + "");
i.putExtra("taskname", task_name);
startActivity(i);
}
});
GetTasks
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_page_layout);
CharSequence task_name = (CharSequence) findViewById(R.id.task_name);
Log.d("Here", task_name + "");
Intent i2 = getIntent();
taskname = i2.getStringExtra("taskname");
TextView text = (TextView) findViewById(R.id.gettaskname);
text.setText(taskname);
}
Can you tell me what am I doing wrong? My application force closes itself. Instead of passing a variable, if I pass a string variable, I am able to see that in the text view? Does it have to do with the manifest file? I have an intent for both the activities. Any help regarding this would appreciated.
I believe that the line
CharSequence task_name = (CharSequence) findViewById(R.id.task_name);
is the most likely culprit. CharSequence should replaced with whatever type of a view the task_name element is...
Instead of (CharSequence), use (EditText), that is the type of layout object your are retrieving the data from, as defined your layout XML file.
In your GetTasks.onCreate method, you need to bring in the values that you passed from the intent in the HelloAndroidActivity.
You do that like this:
Bundle extras = getIntent().getExtras();
if (extras ==null) { return;}
String taskname = extras.getString("taskname");
See the following link for a good tutorial on using intents