I new in the Android Programming and I want built a digital Schoolplan. For this I use a few Activities. I want create a plan and list them in a ListView that the User can click in the ListView on this Control and see all Homeworks and so.
Here is my Idea:
I build a Activity for the CreateMain:
public void createPlan(View view)
{
String PlanName;
Intent intent = new Intent(this,ListenActivity.class);
EditText planName = (EditText)findViewById(R.id.editText1);
PlanName = planName.getText().toString();
intent.putExtra(ListViewMessage, PlanName);
startActivity(intent);
}
And a Activity for show the create data in a ListView
import android.os.Bundle;
import android.view.Menu;
import java.util.List;
import android.app.ListActivity;
import android.widget.ArrayAdapter;
public class ListenActivity extends ListActivity {
private CommentsDataSource datasource;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_open);
datasource = new CommentsDataSource(this);
datasource.open();
List<Comment> values = datasource.getAllComments();
// Use the SimpleCursorAdapter to show the
// elements in a ListView
ArrayAdapter<Comment> adapter = new ArrayAdapter<Comment>(this,
android.R.layout.simple_list_item_1, values);
setListAdapter(adapter);
Comment comment = null;
String[] comments = new String[] { "t1", "t2", "t3" };
comment = datasource.createComment(comments[1]);
adapter.add(comment);
adapter.notifyDataSetChanged();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_list, menu);
return true;
}
}
But I don't know how I can use the data from the activity before for this activity in my ListView. I want to use a SQLite database but it don't work :(
There are few ways to pass data through Activities. Since you stored your information in a Bundle I will answer following that same logic.
If you didn't notice, you stored your information in the Intent's Extra Bundle in your createPlan method. After that, you started that Intent.
According to the official documentation:
"...extras -- This is a Bundle of any additional information. This can be used to provide extended information to the component. For example, if we have a action to send an e-mail message, we could also include extra pieces of data here to supply a subject, body, etc..."
So, to get that information you might use getIntent().getExtras() inside your ListenActivity to take back your Bundle and then you pass the key you used to store the plan's name using getIntent().getExtras().getString(your_key).
For example:
public class ListenActivity extends ListActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
//...your stuff
String planName = getIntent().getExtras().getString(ListViewMessage);
//...your stuff
}
}
I don't recommend the use of SQLite to store small amount of data. If you really want to use it, there are very nice examples here.
Related
I have a listview of items in my ShoppingListActivity.
Items are added from another activity thought an intent. I want to make sure that all items are kept in the list when going between both activities; however, right now my list only has the last item added from the previous activity.
My ShoppingListActivity.class
public class ShoppingListActivity extends Activity {
private ListView mainListView ;
private ArrayAdapter<String> listAdapter ;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_shopping_list);
// Find the ListView resource.
mainListView = (ListView) findViewById( R.id.mainListView );
ArrayList<String> shoppingList = new ArrayList<String>();
shoppingList.add(itemLookup());
// Create ArrayAdapter using the shopping list.
listAdapter = new ArrayAdapter<String>(this, R.layout.simplerow, shoppingList);
// Set the ArrayAdapter as the ListView's adapter.
mainListView.setAdapter( listAdapter );
}
//Lookup item by ID
public String itemLookup() {
String itemName = "";
Intent intent = getIntent();
Bundle extras = intent.getExtras();
if (intent != null) {
String itemId = extras.getString("BARCODE_ID");
try {
itemName = ItemLookup.lookupById(itemId);
} catch (IOException e) {
e.printStackTrace();
}
}
return itemName;
}
#Override
public void onBackPressed() {
startActivity(new Intent(ShoppingListActivity.this, MainActivity.class));
}
}
I have a feeling I should be putting my add somewhere else. I'm pretty sure I should be passing the list back and forth in a putExtra, but if that's how I have to do it, it's fine.
How can I make sure that the list is maintained between activities?
One way around your problem is Singleton Pattern.
In your case you can implement something like this:
public class ShoppingListManager {
private static ShoppingListManager instance = new ShoppingListManager();
private List<String> shoppingList;
public static ShoppingListManager getInstance() {
return instance;
}
public List<String> getShoppingList() {
return shoppingList;
}
// Make the constructor private so that this class cannot be instantiated
private ShoppingListManager(){
shoppingList = new ArrayList<String>();
}
}
Then access it anywhere in your code.
ShoppingListManager.getInstance().getShoppingList();
One point to remember never store context in singleton classes as it will lead to memory leaks.
Keeping your data structures in an Activity makes your app prone to data loss because Activities can be destroyed at various times and for a variety of reasons, including rotating the device between portrait and landscape.
You should use a separate class to store and track which items are in the shopping list. The Activity with the ListView should only get the list of items stored and display them. Anything that causes an item to be added should simply trigger a reload of the list (if the Activity is running in the foreground), otherwise the Activity should see that new item anyway the next time it starts.
If you also need your data to be persistent after your process is terminated, you should look into the possible data storage options available.
I am trying to write some easy application for android. I have Listview, whitch is filled by data from database (BACKENDLESS). I would like to do this: When I tap on one list item, new page is opened and correct data are displayed.
this is code for onListItemClick:
#Override
protected void onListItemClick( ListView l, View v, int position, long id )
{
Intent showLocationsIntent = new Intent( this, Detail_page.class );
showLocationsIntent.putExtra("restaurants", totalRestaurants.get( position ) );
startActivity( showLocationsIntent );
}
and this is new activity class:
import android.app.ListActivity;
import android.os.Bundle;
import android.widget.ImageView;
public class Detail_page extends ListActivity{
private Restaurants restaurant;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.detail_page);
restaurant = (Restaurants) getIntent().getSerializableExtra( "restaurants" );
ImageView image = (ImageView)findViewById(R.id.imageView);
new DownloadImage((ImageView) findViewById(R.id.imageView)).execute(restaurant.getPicture());
String title = restaurant.getName();
}
}
But I have problem with this line showLocationsIntent.putExtra("restaurants", totalRestaurants.get( position ) );
Error is: no suitable method found for putExtra(String,Restaurant)
Restaurant is my class
Restaurant implements Serializable (or Parcelable)
Since you are passing an object. Your Restaurants class should implement Parcelable interface.
Read this.
The solution for me was to add:
implements Serializable
to the object class that is being passed into the intent.
With your code it looks like you are incorrectly using the intent.
I'm using The Complete Idiots Guide to Android App Development to get me started. I've been struggling through the book and I've come accross a problem that I don't understand. I'm creating a search class to add a search function to the app. I'm getting multiple errors in eclipse and the one I don't understand the most is
"Syntax error, insert "}" to complete ClassBody". I understand that Eclipse is telling me to close the class body, but it is closed. Just not where it's telling me to close it. Below where it's telling me to close it I have another method to enter.
Here is the code for the whole class.
package com.recipesapp;
import java.util.ArrayList;
import android.app.ListActivity;
import android.app.SearchManager;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.widget.ListView;
public class RecipeSearch extends ListActivity{
#Override
public void onCreate(Bundle savedInstanceState){
//super.onCreate(savedInstanceState);
setContentView(R.layout.recipe_list);
Intent intent = getIntent();
if(Intent.ACTION_VIEW.equals(intent.getAction())){
//A search suggestion was clicked
Intent recipeIntent = new Intent(this, RecipeEntry.class);
recipeIntent.setData( intent.getData() );
startActivity(recipeIntent);
finish();
}
else if(Intent.ACTION_SEARCH.equals(intent.getAction())){
//The search was executed
String query = intent.getStringExtra(SearchManager.QUERY);
showRecipes(query);
}
}
private static final ArrayList<String> _RecipeSearchResults = new ArrayList<String>();
private ListView resultsView;
private void showRecipes(query){
SharedPreferences recipeNames = getSharedPreferences(MainMenu.RecipeNamesPref, RecipeEntry.MODE_WORLD_READABLE);
String[] recipeList= recipeNames.getString(MainMenu.RecipeNamesPref, null).split(",");
for(String recipe: recipeList){
if(recipe.contains(query))
ReicpeSearchResults.add(recipe);
resultsView=(ListView) findViewById(android.R.id.list);
resultsView.setAdapter(new ListViewAdapter(this));
resultsView.setTextFilterEnabled(true);
resultsView.setOnItemClickListener(this);
}
}
}
I know there are other errors, but I can't figure this one out. I've gone through and seen that I have all the curly brackets, open and closed. I don't understand why it wants to put in line 35, which is:
private ListView resultsView;
Also, it wants me to also delete the very last curly bracket. I would appreciate any help.
This is not the problem with curly brace. You missed a type for your method parameter
A method parameter should have type
Change this
showRecipes(query)
to
this
showRecipes(String query)
Your method private void showRecipes(query) does not contain a data type, that's why it is showing an error.
if you change it to something like this private void showRecipes(String query) it will stop showing } error.
Just move following line before onCreate function
private ListView resultsView;
private static final ArrayList<String> _RecipeSearchResults = new ArrayList<String>();
private ListView resultsView;
Both these two lines mentioned above are actually supposed to come before OnCreate
Where you are actually writing them. at that place every line is supposed to be inside some method.
#Override
public void onCreate(Bundle savedInstanceState){
//super.onCreate(savedInstanceState);
setContentView(R.layout.recipe_list);
Intent intent = getIntent();
if(Intent.ACTION_VIEW.equals(intent.getAction())){
//A search suggestion was clicked
Intent recipeIntent = new Intent(this, RecipeEntry.class);
recipeIntent.setData( intent.getData() );
startActivity(recipeIntent);
finish();
}
else if(Intent.ACTION_SEARCH.equals(intent.getAction())){
//The search was executed
String query = intent.getStringExtra(SearchManager.QUERY);
showRecipes(query);
}
More Over you are supposed to define tthe Data Type of the "query" parameter say String here in this case
private void showRecipes(String query){
SharedPreferences recipeNames = getSharedPreferences(MainMenu.RecipeNamesPref, RecipeEntry.MODE_WORLD_READABLE);
String[] recipeList= recipeNames.getString(MainMenu.RecipeNamesPref, null).split(",");
for(String recipe: recipeList){
if(recipe.contains(query))
ReicpeSearchResults.add(recipe);
resultsView=(ListView) findViewById(android.R.id.list);
resultsView.setAdapter(new ListViewAdapter(this));
resultsView.setTextFilterEnabled(true);
resultsView.setOnItemClickListener(this);
}
}
I am creating a chat application & for that purpose i have used TabHost.
In that first tab contains List of Buddies, and as soon as user clicks on any of the buddy
from buddy it should create another tab for that buddy in order to chat.
I am completed up to this but my problem is I am using a single Activity to perform Chat
but It always shows the same activity for each buddy.
Any Help will be highly appreciated. Here is my code,
public void onItemClick(AdapterView<?> arg0, View arg1, int position,
long arg3) {
RosterEntry entry = List.get(position);
String userName = entry.getName();
Intent intent = new Intent().setClass(RosterScreen.this,
com.spotonsoft.chatspot.ui.ChatScreen.class);
TabSpec tabSpec = Home.tabHost.newTabSpec("chat")
.setIndicator(userName).setContent(intent);
Home.tabHost.addTab(tabSpec);
}
Best Regards,
~Anup
in onCreate of ChatScreen you only setup basic stuff like getting View and store it in private fields
onResume you "recreate" ChatScreen with buddy-specific data ... how to do this (pls, read comments in code)?
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.*;
public class ChatScreen extends Activity {
TextView textview = null;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
textview = new TextView(this);
setContentView(textview);
}
#Override
public void onResume(){
super.onResume();
Intent intent = getIntent();
if(intent!=null){
//we read buddy-specific data here
textview.setText(intent.getStringExtra("chatwith"));
//we only setting textview with user name
//in real app you should store conversation somewere (fx in db)
//and load it here
}
}
}
and your code
Intent intent = new Intent().setClass(RosterScreen.this, com.spotonsoft.chatspot.ui.ChatScreen.class);
// you shoud add this line and provide some information fx useName or userID to ChatScreen Activity
intent.putExtra("chatwith", userName);
TabSpec tabSpec = Home.tabHost.newTabSpec("chat").setIndicator(userName).setContent(intent);
Home.tabHost.addTab(tabSpec);
You can add data to your intent before starting it, for example
intent.putExtra("user", userName);
In the onCreate of your activity you can read this data and use it to setup your activity.
Also, make sure that you have set the proper launchmode for your activity.
I have an activity group and it starts 2 activities. When the user presses a button on one of the activities, the activity group populates an ArrayList.
I am wondering if there is a way to allow both of my activities to access this ArrayList.
Here's what I have at the moment:
public class ExampleGroup extends ActivityGroup {
public static ExampleGroup group;
ArrayList<String> strs = new ArrayList<String>();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
group = this;
View exampleView = getLocalActivityManager().startActivity(
"Example",
new Intent(this, Example.class).addFlags(
Intent.FLAG_ACTIVITY_CLEAR_TOP))
.getDecorView();
setContentView(exampleView);
}
public void populateArrayList(){
//code to do it
}
}
public class Example extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
ExampleGroup.group.populateArrayList();
ArrayList<String> strs2 = ExampleGroup.group.strs;
Log.i("ArrayList contents", strs2);
}
}
The arraylist returns null. Is there something I am missing, or is there a better way to do it?
Yes essentially you're wanting to share a model object between two activities, and this has much to do with the structure of your program. See this post for more details on how that can be done:
Where should I put global methods and variables in an Android app?