Calling different activities from listview? - android

I'm trying to call different activities depending on the item the user clicks on my listview but for some reason only the first element is working.
here is the code for the listview:
options = (ListView) findViewById(R.id.lstOptions);
ArrayAdapter<String> OPTADAP= new ArrayAdapter<String>(this,R.layout.optionslayout,OPTIONS);
options.setAdapter(OPTADAP);
options.setOnItemClickListener(new OnItemClickListener(){
Intent i;
#Override
public void onItemClick(AdapterView<?> parent, final View view,int pos, long id) {
switch(pos){
case 0:
i = new Intent(view.getContext(),Posting.class);
i.putExtra("usrid", usrdata.get("id"));
i.putExtra("usrname", usrdata.get("name"));
try{
startActivity(i);
} catch(ActivityNotFoundException e) {
e.printStackTrace();
}
break;
case 1:
i = new Intent(view.getContext(),WallActivity.class);
try{
startActivity(i);
}catch(ActivityNotFoundException e){
e.printStackTrace();
}
break;
default:
Toast.makeText(view.getContext(), "default", 10).show();
}
}
}
for some reason the block of code in case 1 does not run, i tried putting the code from case 0 in case 1 and it worked, so it has to be something wrong with this block:
i = new Intent(view.getContext(),WallActivity.class);
try{
startActivity(i);
}catch(ActivityNotFoundException e){
e.printStackTrace();
}
the WallActivity is basically just a webview:
public class WallActivity extends Activity{
WebView wv;
private final String wurl = "URL HERE";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.wallactivity);
wv = (WebView) findViewById(R.id.webview);
wv.getSettings().setJavaScriptEnabled(true);
wv.loadUrl(wurl);
}
}
When i click on item 1 the code does not run, any ideas? all the help is greatly appreciated.

Why on earth are you catching the ActivityNotFoundException? If i had to hazard a guess, it woud be that you forgot to register WallActivity in your manifest and that exception is being thrown.
In any case, if you do catch an exception, in Android, if you want to see the stack trace you should write the exception to the Log instead of e.printStackTrace()
Log.e(getClass().getName(), "OMG ERROR ! :)", e);

Related

android remove view from alertdialog

Hi i have a MainActivity class where i have a listview populated by rss items. When i click on item list my app shows me an alertdialog where i can see in message box the item details. My problem is that after i show alertdialog when i close it and open a new item my app crashes giving me this error:
FATAL EXCEPTION: main.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.
Here my java class:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listview = (ListView) findViewById(R.id.listView);
wv = new WebView(this);
try {
url = new URL("http://www.unikore.it/index.php/ingegneria-informatica-home?format=feed");
} catch (MalformedURLException e) {
e.printStackTrace();
}
new ReadRssTask().execute(url);
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,long id) {
OptionDialog = new AlertDialog.Builder(MainActivity.this).create();
OptionDialog.setTitle(listview.getItemAtPosition(position).toString());
s = rssItems.get(position).getDescription();
if(s.contains("href=")){
s.substring(0,s.indexOf("</div>"));
wv.loadData(s, "text/html", "UTF-8");
wv.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
});
OptionDialog.setView(wv);
}else {
OptionDialog.setMessage(s.replaceAll("<[^>]*>", ""));
}
OptionDialog.show();
}
});
}
i tried using OptionDialog.dismiss() method but app crashes anyway.
Thanks
move the instantiation of the WebView just before accessing the object.
s = rssItems.get(position).getDescription();
if(s.contains("href=")){
wv = new WebView(this);
wv.loadData(s, "text/html", "UTF-8");
// other code

ShowCase View with fragments

I'm trying to do a intro tutorial for my android aplication that uses View Pager with Fragments Pager Adapter and the things don't work with fragments.
I'm using this library: https://github.com/amlcurran/ShowcaseView
t1 = new ViewTarget(R.id.btnGenerate, getActivity());
t2 = new ViewTarget(R.id.cbFavorito, getActivity());
t3 = new ViewTarget(R.id.txtResult, getActivity());
view.post(new Runnable() {
#Override
public void run() {
if(isAdded()) {
showcaseView = new ShowcaseView.Builder(getActivity())
.setTarget(Target.NONE)
.setContentTitle("Tutorial")
.setContentText("Aprenda como usar o aplicativo")
.build();
showcaseView.setButtonText("Next");
showcaseView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
switch (contador) {
case 0:
showcaseView.setShowcase(t1, true);
showcaseView.setContentTitle("Teste");
showcaseView.setContentText("Teste");
break;
case 1:
showcaseView.setShowcase(t2, true);
showcaseView.setContentTitle("Gerar um nome");
showcaseView.setContentText("Teste");
break;
case 2:
showcaseView.setShowcase(t3, true);
showcaseView.setContentTitle("Adicionar aos Favoritos");
showcaseView.setContentText("teste");
showcaseView.setButtonText("Fechar");
break;
case 3:
showcaseView.hide();
break;
}
contador++;
}
});
}
}
});
In the code above I'm trying to focus different buttons when I click in button Next of ShowCase View, but, when is clicked the tutorial just closes, nothing happens, no erros, just closes.
You dont have take the event Listner from Button, try this:
public void run() {
try {
showCase();
} catch (Exception e) {
e.printStackTrace();
}
and ShowCase:
showcaseView = new ShowcaseView.Builder(getActivity())
.setTarget(new ViewTarget(R.id.tool_bar, getActivity()))
.setContentTitle(getString(R.string.title_list_os))
.setContentText(getString(R.string.dica_atualizar_os))
.setOnClickListener(this)
.setStyle(R.style.CustomShowcaseTheme)
.build();
your activity needs Implements View.OnclickListener
Sorry my english.

load content dynamically from listview to another activity

Android newbie here.
The scenario
I am using my website's api to populate data for Android ListView
for the first screen it is called GameFragment. Game fragment loads the games from my website url
I was able to successfully list all games. So my next step would be to show all articles related to the game when user clicks on the game. Using my websites api http://www.gamerzwiki.com/api/news.json?game_id=qwert133 (whatever the id of the item is)
Loading Contents from url
try {
JSONArray games = gp.loadGamesFromApi();
ArrayList<Games> listData = new ArrayList<Games>();
if(games != null){
for(int x = 0 ; x<games.length() ; x++){
JSONObject game = games.getJSONObject(x);
try {
Games game1 = new Games();
game1.title=game.getString("title");
game1.id = game.getInt("id");
listData.add(game1);
//free game 1
game1 = null;
} catch (JSONException e) {
e.printStackTrace();
}
}
}
ArrayAdapter<Games> adapter = new ArrayAdapter<Games>(getActivity(),android.R.layout.simple_list_item_1, listData);
setListAdapter(adapter);
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
so I have a listener
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
Object item = l.getSelectedItem();
Toast.makeText((Context)getActivity(),item.title.toString() , Toast.LENGTH_LONG).show();
Intent intent = new Intent(v.getContext(), NewsActivity.class);
startActivity(intent);
}
but it seems I can't get the attribute of the item
but I don't know how I can do that on my ListView. So I would like to ask your expert advise
what you can do is implement onClick listener on your listview which has all the games:-
listview.setOnItemClickListener(new OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?>adapter,View v, int position){
Games game = adapter.getItem(position);
Intent intent = new Intent(Activity.this,destinationActivity.class);
intent.putExtra("id",game.id);
startActivity(intent);
}
});
in your other activity retrieve this as:-
String id=getIntent.getStringExtra("id");
and now you can use this id to make webservice call in your activity,here ItemClicked is your model class which your are using to populate your listview with your all games
You can pass data between activities by using putExtra in the intent
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
Games item = adapter.getItem(position);
Intent intent = new Intent(v.getContext(), NewsActivity.class);
intent.putExtra("id", item.id);
startActivity(intent);
}
In your receiving activity do this
String id = getIntent().getStringExtra("id");
You can pass basic datatypes through putExtra. If you want to pass custom objects you'll have to implement Parcelable http://developer.android.com/reference/android/os/Parcelable.html

adapter.notifyDataSetChanged(); and listview.invalidateViews not refreshing listview

I have an application where the user will click on an item in the listview and either save, cancel, or delete the entry(this is done on a new activity that is started on the item click). so in the activity that is started on item click , after i click either button i call finish() to return to my previous activity and in this case the activity with the listview. However, if I do any change to the item in the list, the list is not changed at all. I tried using both .notifyDataSetChanged() and invalidateViews but neither of the two worked. Here is my code.
public class Flashcards_List extends ListActivity{
String[] All_Cards = null;
ArrayAdapter<String> adapter;
ListView listview;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.flashcards_list);
Flashcards Cards = new Flashcards(this);
Cards.open();
All_Cards = Cards.getAllFronts();
listview = (ListView) findViewById(android.R.id.list);
listview.invalidateViews();
adapter = new ArrayAdapter<String>(Flashcards_List.this, android.R.layout.simple_list_item_1, All_Cards);
// Assign adapter to ListView
listview.setAdapter(adapter);
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
// TODO Auto-generated method stub
super.onListItemClick(l, v, position, id);
String Specific_Card = All_Cards[position];
/* Class to assist us in loading the activity */
Class editClass = null;
try {
editClass = Class.forName("com.example.flashcards.Edit_Flashcard");
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Bundle specificCard = new Bundle();
specificCard.putString("card", Specific_Card);
Intent ourIntent = new Intent(Flashcards_List.this, editClass);
ourIntent.putExtras(specificCard);//passing the bundle to the activity
startActivity(ourIntent);
adapter.notifyDataSetChanged();
}
}
This class edits the DB entry
public class Edit_Flashcard extends Activity implements OnClickListener{
String front_of_card = null;
Bundle bundle_received;
Button cancel, delete, save;
EditText front, back;
String[] card;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.edit_flashcard);
bundle_received = getIntent().getExtras();
front_of_card = bundle_received.getString("card");//current card is the card that was clicked on
Flashcards info = new Flashcards(this);
info.open();
card = info.getCard(front_of_card);
info.close();
initialize();
}
public void initialize(){
front = (EditText) findViewById(R.id.front);
back = (EditText) findViewById(R.id.back);
front.setText(card[1]);
back.setText(card[2]);
cancel = (Button) findViewById(R.id.cancel);
save = (Button) findViewById(R.id.save);
delete = (Button) findViewById(R.id.delete);
cancel.setOnClickListener(this);
save.setOnClickListener(this);
delete.setOnClickListener(this);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch(v.getId()) {
case R.id.cancel:
super.finish();//finishes the activity, and returns to previous Activity
break;
case R.id.save:
try{
Flashcards update_entry = new Flashcards(this);
update_entry.open();
update_entry.updateEntry(card[0], front.getText().toString(), back.getText().toString());
update_entry.close();
}catch(Exception e){
String save_text = "The Flashcard could not be saved. Please try again.";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(Edit_Flashcard.this, save_text, duration);
toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
toast.show();
}
super.finish();
break;
case R.id.delete:
try{
Flashcards delete_entry = new Flashcards(this);
delete_entry.open();
delete_entry.deleteEntry(card[0]);
delete_entry.close();
}catch(Exception e){
/* set the value to NOT INSERTED */
String delete_text = "The Flashcard could not be deleted. Please try again.";
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(Edit_Flashcard.this, delete_text, duration);
toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
toast.show();
}
super.finish();
break;
}/* end Switch */
}/* end onClick */
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/background"
android:orientation="vertical" >
<ListView
android:id="#android:id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
</LinearLayout>
Launch EditClass activity by startActivityForResult method. Implement onActivityResult method in the calling activity and in that method call adapter.notifyDatasetChanged.
Intent ourIntent = new Intent(Flashcards_List.this, editClass);
ourIntent.putExtras(specificCard);//passing the bundle to the activity
startActivity(ourIntent);
adapter.notifyDataSetChanged();
notifyDataSetChanged is executed IMMEDIATELY after you call startActivity(), it doesn't block. Instead, you should load your data in onResume(), that way the latest data will always be shown when the activity comes back. Basically leave only the setContentView() in your onCreate.

Android ListActivity different title and activity name

I'd like to show the user a list of different available activities in my app, but I want the names to be explicit such as "Accelerometer Control", or "Line Follower". Right now the activities are stored in a String array, these activity names are what are shown AND called. I'd like to show "Line Follower" and call the "LineFollower" activity (without space). I haven't found any examples doing that.
Here's ListActivity that should show the available activities:
public class ActivityList extends ListActivity {
// here I'd like to have "Accelerometer Control", "Touch Control"...
String[] activities = new String[] {"AccelerometerControl", "TouchControl", "ArrowControl", "LineFollower", "Piano", "SendData", "LEDEqualizer", "Program"};
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setListAdapter(new ArrayAdapter<String>(ActivityList.this, android.R.layout.simple_list_item_1, activities));
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
String activity = activities[position];
try
{
Class<?> activityClass = Class.forName("com.bluetooth." + activity);
Intent intent = new Intent(ActivityList.this, activityClass);
startActivity(intent);
}
catch(ClassNotFoundException e)
{
e.printStackTrace();
}
}
}
Keep the activities like you would normally want to appear in the list and when it's time to start them simply remove the empty spaces between the names:
String[] activities = new String[] {"Accelerometer Control", "Touch Control", "Arrow Control", "Line Follower", "Piano", "Send Data", "LED Equalizer", "Program"};
// ...
String activity = activities[position];
activity = activity.replace(" ", "");
try {
Class<?> activityClass = Class.forName("com.bluetooth." + activity);
Intent intent = new Intent(ActivityList.this, activityClass);
startActivity(intent);
} catch(ClassNotFoundException e) {
e.printStackTrace();
}
Try setTitle by itself, like this in those activites where u want:
requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
setContentView(R.layout.main);
this.setTitle("myclass2");

Categories

Resources