Fairly new to android programming and having trouble changing the string value "channel" when a button is clicked. Having issues trying to close the onCreate but it only seems to let me close it at the end of the activity. I get an error of 'token "}". please delete' if i try to close it elsewhere. I'm having a hard time trying to wrap my head around this even though it's probably very simple.
public class MainActivity extends Activity {
String channel = "bbc1";
// This method creates main application view
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Set view
setContentView(R.layout.main);
final ViewSwitcher switcher = (ViewSwitcher)findViewById(R.id.ViewSwitcher1);
Button bbcButton = (Button) findViewById(R.id.bbcButton);
Button bbc2Button = (Button) findViewById(R.id.bbc2Button);
bbcButton.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
channel = "bbc1";
switcher.showNext();
}
});
bbc2Button.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
channel = "bbc2";
switcher.showNext();
}
});
try{
// This line creates RSS reader
RssReader rssReader = new RssReader("http://bleb.org/tv/data/rss.php?ch="+channel+"&day=0");
// This line gets a ListView from main view
ListView tvItems = (ListView) findViewById(R.id.listMainView);
// This line creates a list adapter
ArrayAdapter<RssItem> adapter = new ArrayAdapter<RssItem>(this,android.R.layout.simple_list_item_1, rssReader.getItems());
// This line sets list adapter for the ListView
tvItems.setAdapter(adapter);
} catch (Exception e) {
Log.e("Tv RSS Reader", e.getMessage());
}
}
}
I'm guessing that you want to change the RSS feed when you press the button. But since you are fetching the RSS info in the onCreate, you won't update the data, even though you are pressing the buttons. But you are changing the value of the string channel.
onCreate is only called once when you create the activity!
Try moving the try-statement into a seperate method and call this method in your two onClickListeners.
bbc2Button.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
channel = "bbc2";
updateRSS();
switcher.showNext();
}
});
public void updateRSS(){
try{
// This line creates RSS reader
RssReader rssReader = new RssReader("http://bleb.org/tv/data/rss.php?ch="+channel+"&day=0");
// This line gets a ListView from main view
ListView tvItems = (ListView) findViewById(R.id.listMainView);
// This line creates a list adapter
ArrayAdapter<RssItem> adapter = new ArrayAdapter<RssItem>(this,android.R.layout.simple_list_item_1, rssReader.getItems());
// This line sets list adapter for the ListView
tvItems.setAdapter(adapter);
} catch (Exception e) {
Log.e("Tv RSS Reader", e.getMessage());
}
Related
i want to add listview item dynamically. i had done this but when i restart the app listview item disappear. How can i save this item permanently to listview. please suggest
public class ChatWithAttorney extends Activity {
ImageView btnBack;
ListView chatList;
EditText etMsg;
Button btnSend;
String msg_to_send;
ArrayAdapter<String> adapter;
ArrayList<String> listMsg;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.chatwithattorny);
btnBack = (ImageView) findViewById(R.id.btnback);
chatList = (ListView) findViewById(R.id.chatList);
etMsg = (EditText) findViewById(R.id.etMsg);
btnSend = (Button) findViewById(R.id.btnSend);
listMsg = new ArrayList<String>();
adapter = new ArrayAdapter<String>(this, R.layout.chat_list_text, R.id.tvSentMsg,listMsg);
chatList.setAdapter(adapter);
btnSend.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
try {
msg_to_send = URLEncoder.encode(etMsg.getText().toString(),
"utf-8");
listMsg.add(msg_to_send);
adapter.notifyDataSetChanged();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
});
}
Put those ArrayList items in a database or SharedPreference and read those items when resuming your activity.
You can use Local database , SharedPreference or Static arraylist for storing the messages
AT the Time of Destroy Serialize the List data.
And Deserilize when Application Starts Again.
I am using a ListFragment for displaying a list from a database in my activity. I have included a search function. Unfortunately the "old" ListFragments seem to remain in the background and the ListFragments containing the result of the query are displayed on top of it. How can I avoid, that the old ListFragments are displayed?
My FragmentActivity:
private Button buttonSearch;
private TextView searchString;
public static String search = null;
static IShoppinglist shoppinglistManager;
static IAktionen aktionenManager;
private AktionenListListFragment listFragment;
#Override
public void onCreate(Bundle savedInstanceState) {
Log.d(TAG, "ListFragmentActivity created");
super.onCreate(savedInstanceState);
setContentView(R.layout.articlelist);
shoppinglistManager = new Shoppinglist(this);
aktionenManager = new Aktionen(this);
buttonSearch = (Button) findViewById(R.id.search_Button);
buttonSearch.setOnClickListener(searchListAktionen);
//show all entries on start
listFragment = new AktionenListListFragment();
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_articlelist, listFragment).commit();
}
OnClickListener searchListAktionen = new OnClickListener() {
public void onClick(View v) {
try{
searchString = (TextView) findViewById(R.id.input_search_bezeichnung);
search = searchString.getText().toString().trim();
Log.d(TAG, "search Button clicked "+search);
if(search.trim().length()==0){
search=null;
}
//show all entries on start
listFragment = new AktionenListListFragment();
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_articlelist, listFragment).commit();
}catch(Exception ex){
ex.printStackTrace();
}
}
};
Thanks in advance,
update:
thank you for your answers. I tried to implement them, but the main problem seems to be nowthat the onCreate and onActivityCreated method in the ListFragment are called twice (as I can see in my log messages).
my new code:
#Override
public void onCreate(Bundle savedInstanceState) {
Log.d(TAG, "ListFragmentActivity created");
super.onCreate(savedInstanceState);
//force commit
getSupportFragmentManager().executePendingTransactions();
if(getSupportFragmentManager().findFragmentByTag(tag) == null) {
setContentView(R.layout.articlelist);
shoppinglistManager = new Shoppinglist(this);
aktionenManager = new Aktionen(this);
buttonSearch = (Button) findViewById(R.id.search_Button);
buttonSearch.setOnClickListener(searchListAktionen);
listFragment = new AktionenListListFragment();
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_articlelist, listFragment,tag).commit();
}else{
Log.d(TAG, "ListFragment already exists");
}
}
I tried to set a unique tag for my ListFragment but this solution does not work.
I guess that one of the ListFragments is displayed in the background and the other is updated.
So first you need to stop making new ListFragments everytime your list is refreshed and just have a public method in your ListFragment that the Activity can call to restart the loader with the proper parameters. Then:
In your onLoadFinished(),
you should make a new adapter with the list you want to replace it with
myAdapter = new AktionenListCustomCursorAdapter(getActivity(), myCursor);
and call:
this.getListView().setAdapter(myAdapter);
So:
public void onLoadFinished(Loader<Cursor> mAdapter, Cursor myCursor) {
if(myCursor!=null){
//getting the data from the database
Log.d(TAG, "search String "+AktionenListFragmentActivity.search);
if(AktionenListFragmentActivity.search==null){
myCursor = AktionenListFragmentActivity.aktionenManager.fetchAllArticles();
}else{
myCursor = AktionenListFragmentActivity.aktionenManager.fetchItemsByBezeichnung(AktionenListFragmentActivity.search);
}
myAdapter = new AktionenListCustomCursorAdapter(getActivity(), myCursor);
this.getListView().setAdapter(myAdapter);
}
}
Hopefully this solved your question as I understood it. If you have any questions please leave it in the comment below and I will expand my answer. If it worked for you please accept answer. :D
I have created a class of type BaseAdapter that is populated with buttons - when you click on a button I want to load a new intent. This has proven difficult on two levels:
You cannot associate the event with the button (one that creates a new intent) inside the Adapter. This is why I send the Buttons as an array to my Adapter (this solution works, but it is messy)
Even though my buttons are created inside the same Activity - they cannot create a new intent from that Activity. The exeption is so great that I have not even gotten a try...catch statement to work.
I have tried reflection, creating the buttons inside the activity and passing them through, passing the context (to call context.startIntent(...))
My question: can someone show me how to create a ButtonAdapter where each button creates a new Intent - even of the same type as the original Activity?
UPDATE: Here is the code because I am getting answers from people who think I am struggling with onClickListeners:
public class ButtonAdapter extends BaseAdapter
{
private Context _context;
private Button[] _button;
public ButtonAdapter(Context c, Button[] buttons)
{
_context = c;
_button = buttons;
}
// Total number of things contained within the adapter
public int getCount()
{
return _button.length;
}
// Require for structure, not really used in my code.
public Object getItem(int position)
{
return _button[position];
}
// Require for structure, not really used in my code. Can
// be used to get the id of an item in the adapter for
// manual control.
public long getItemId(int position)
{
return position;
}
public View getView(int position, View convertView, ViewGroup parent)
{
_button[position].setId(position);
return _button[position];
}
}
---------------
The Activity:
public class MainActivity extends Activity
{
private GridView _gv;
private TextView _heading;
private ButtonAdapter _adapter;
public void LoadActivity(String heading)
{
try
{
Itent intent = new Intent(getApplicationContext(), MainActivity.class);
intent.putExtra("Level", "NextPage");
intent.putExtra("Heading", heading);
startActivity(intent);
}
catch (Exception ex)
{
Toast.makeText(getApplicationContext(), String.format("Error LoadActivity: %s", ex.getMessage()), Toast.LENGTH_SHORT).show();
}
}
private void createButtonsAdapter(Button _button[])
{
_buttonadapter = new ButtonAdapter(getApplicationContext(), _button);
_gv.setAdapter(_adapter);
}
private void setupButtons()
{
Button[] _buttons = new Button[2];
String names[] = new String[]{"Button1","Button2"};
for (int i = 0; i < 2; i++)
{
_buttons[i] = new Button(this);
_buttons[i].setText(names[i]);
_buttons[i].setTag(names[i]);
_buttons[i].setOnClickListener(new View.OnClickListener()
{
public void onClick(View arg0)
{
try
{
LoadActivity(((Button)arg0).getTag().toString());
}
catch(Exception ex)
{
Toast.makeText(getApplicationContext(), String.format("Error button.onClick: %s", ex.getMessage()), Toast.LENGTH_SHORT).show();
}
}
});
}
createButtonsAdapter(_buttons);
}
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
_gv = (GridView)findViewById(R.id.gridview);
_heading = (TextView)findViewById(R.id.tv_heading);
Bundle params = getIntent().getExtras();
if (params == null)
{
setupButtons();
}
else if (params.containsKey("Level"))
{
_heading.setText(params.getString("Heading"));
if (params.getString("Level").equals("NextPage"))
{
//code not here yet
}
else if (params.getString("Level").equals("Chapters"))
{
//future code
}
}
}
}
Excuse the bold and caps but I have had enough silly answers to warrent this:
I HAVE TRIED PUTTING THE ONCLICKLISTENER INSIDE THE GRIDVIEW AND IT DOES NOT WORK EITHER
You cannout load an activity from a class outside that activity, even if you pass the context as a parameter. That is why I have resorted to this method, which completely bombs android, even though I have try catch statements.
Please try give me a solution in the form of a correction to my code, other code, or a tutorial that achieves what I want here. I know how to do a button adapter properly, it is the act of loading an Intent that has forced me to implement it this way.
I suggest the following,
Using a common onClick listner for all the buttons in your grid view
Set tag for all the butons in the getView func. of adapter.
Use the tag Object to decide on the intent to fire from the onClick listener.
I hope it helps..
I guess you can easily manipulate your buttons created in your class extending Base adapter. In the getView method .... if you have button b.. then do it as follows
b.setOnClickListener(new OnClickListener()
{
public void onClick()
{
// Do your stuff here ...
}
});
and if you want to start another activity on Click of this button then you need to pass the calling context to this adapter.
Once again I am answering my own question:
http://bottlecapnet.blogspot.com/2012/01/android-buttons-have-no-place-inside.html
I will just have to style TextViews as I want to see them.
I have a listview that contains values from webservice.Each page contains only 10 listitems and the next 10 in page 2 etc.Each listitem is clickable and it contains a button which is mainly for voting.So when i click the button in list item 1 ,a value is added to webservice.
The button click codes are placed in a custom base adapter class.So that i can easily add the vote.But the problem is,When i submit the vote,i want to refresh my listview also.Suppose if iam in page no 5,refresh that listview page.
How can i refresh this listview instantly after submitting the value to webservice?
sample code for main.java
private class ProgressThreadNextPageLoading extends
AsyncTask<String, Void, String> {
// private String Content;
#Override
protected void onPreExecute() {
progressDialog = new ProgressDialog(KidsCrackMeUp.this);
progressDialog.setMessage("Loading..Please Wait..");
progressDialog.setIcon(R.drawable.icon);
progressDialog.show();
}
#Override
protected String doInBackground(String... urls) {
String response = "";
// call ur webservice here
try {
// pagenum = 1;
posts= web
.getAllposts(pagenum);
response = "Yes";
} catch (Exception e) {
e.printStackTrace();
response = "Failure";
}
return response;
}
#Override
protected void onPostExecute(String result) {
// below line code is to dismiss the progress bar
progressDialog.dismiss();
if (posts != null) {
adapter = new DynamicListAdapter(
main.this, posts
lstPosts.setAdapter(adapter);
adapter.notifyDataSetChanged();
//btnState.setPressed(true);
}
----------------------------------custom adapter class
viewHolder.btnVoting.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
final Dialog d = new Dialog(activity);
d.requestWindowFeature(Window.FEATURE_NO_TITLE);
d.setContentView(R.layout.voteselectornew);
Button btnCategoryCancel = (Button) d
.findViewById(R.id.btnCategoryCancel);
Button twcVote = (Button) d
.findViewById(R.id.btnTwcVote);
twcVote.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
String confirm = web
.addTwcVote(UserSessionKey, Userlist.get(position).contentid);
if (confirm.contains("Successfully")) {
d.dismiss();
}
You have to notify your ListView adapter that the data has changed.
listViewAdapater.notifyDataSetChanged();
you can just reasing your adapter via the constructor with the updated array.
call your listview adapter's method to update the change as:
adapter.notifyDataSetChanged();
I have a simple linearlayout with a textbox a button and a listview, I'm doing some URL data getting when something is entered in the textbox and the button is pressed I want to parse the results and display in the listview.
What I can't work out is how to instatiate the listview from within my extende activity class and add it to the layout? I think I'm barking up the wrong tree !
public class HelloAndroid extends Activity{
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
MyList L;
L = new MyList();
//setContentView(L.getListView());
EditText edittext = (EditText)findViewById(R.id.editText1);
edittext.setText("");
Button button = (Button)findViewById(R.id.button1);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
try {
EditText edittext = (EditText)findViewById(R.id.editText1);
executeHttpGet(edittext.getText().toString());
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
public void executeHttpGet(String vrm) throws Exception {
BufferedReader in = null;
try {
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet();
request.setURI(new URI("http://xxx/vrmtest.asp?vrm="+vrm));
HttpResponse response = client.execute(request);
in = new BufferedReader
(new InputStreamReader(response.getEntity().getContent()));
StringBuffer sb = new StringBuffer("");
String line = "";
String NL = System.getProperty("line.separator");
while ((line = in.readLine()) != null) {
sb.append(line + NL);
}
in.close();
String page = sb.toString();
System.out.println(page);
Context context = getApplicationContext();
CharSequence text = page;
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public class MyList extends ListActivity {
/** Called when the activity is first created. */
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
// Create an array of Strings, that will be put to our ListActivity
String[] names = new String[] { "Linux", "Windows7", "Eclipse", "Suse",
"Ubuntu", "Solaris", "Android", "iPhone"};
// Create an ArrayAdapter, that will actually make the Strings above
// appear in the ListView
this.setListAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, names));
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
// Get the item that was clicked
Object o = this.getListAdapter().getItem(position);
String keyword = o.toString();
Toast.makeText(this, "You selected: " + keyword, Toast.LENGTH_LONG)
.show();
}
}
}
An explanation would suffice rather than code but an example would be nice.
As long as your main.xml layout file has a ListView in it, you're on the right path. Set its #+id to something arbitrary and reference it in your code with:
ListView lv = (ListView) findViewById(R.id.arbitrary_id);
You don't necessarily need a ListActivity to use a ListView. Simply parse the data that you receive back from the server, put it in an array, and use lv.setAdapter(your_array_adapter) to fill the ListView with your data.
You can go further and specify your ItemClickListener by:
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> a, View v, int position, long id) {
}
};
Alternatively, you can create the ListView programmatically using
ListView lv = new ListView(this);
and adding it to a view in your layout with
some_container_view_in_main.addView(lv);
Then you would set the ArrayAdapter and OnItemClickListener the same as above.
You shouldn't create an Activity object yourself. Android will do it for you. Read this article, it will help you: http://developer.android.com/guide/topics/intents/intents-filters.html
If you want to add a ListView to your layout, just add it in the layout xml file. You can't add one activity to another until parent activity extends ActivityGroup. But that's not your case.
If what you want is to add the list to your layout, then use ListView instead of ListActivity.
you can then add the list as this.addView (myList);
Please follow the example here: http://developer.android.com/resources/tutorials/views/hello-listview.html