It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 9 years ago.
I have a confusing problem i have a list menu and i want to open a intent for each item as normal but i don't have single line strings I'm not sure how to set each item to its intent. ps i have most of the app made i just decided to change the menu and cant get it working.
package com.test.thenewboston;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import android.R.menu;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
public class Menu extends Activity {
String[] countries = new String[] {
"News / Blog",
"Calendar",
"Results",
"Standings",
"Photo",
"Videos",
"About us",
};
// Array of integers points to images stored in /res/drawable-ldpi/
int[] flags = new int[]{
R.drawable.rssreader,
R.drawable.calendar2,
R.drawable.results2,
R.drawable.standings2,
R.drawable.photo2,
R.drawable.video2,
R.drawable.about2,
};
// Array of strings to store currencies
String[] currency = new String[]{
" Check out the new blog by our team of f1 fans !",
" Race calendar with dates and times !",
" The latest results from this seasons 2013 Championship",
" The Current 2013 Standings",
" Latest Photos from us and our bloggers",
" This is still underdevolpment but if you have any videos contact us :)",
" All our contact information and extra info about out team.",
};
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Each row in the list stores country name, currency and flag
List<HashMap<String,String>> aList = new ArrayList<HashMap<String,String>>();
for(int i=0;i<7;i++){
HashMap<String, String> hm = new HashMap<String,String>();
hm.put("txt", " | " + countries[i] + " | ");
hm.put("cur","" + currency[i]);
hm.put("flag", Integer.toString(flags[i]) );
aList.add(hm);
}
// Keys used in Hashmap
String[] from = { "flag","txt","cur" };
// Ids of views in listview_layout
int[] to = { R.id.flag,R.id.txt,R.id.cur};
// Instantiating an adapter to store each items
// R.layout.listview_layout defines the layout of each item
SimpleAdapter adapter = new SimpleAdapter(getBaseContext(), aList, R.layout.listview_layout, from, to);
// Getting a reference to listview of main.xml layout file
ListView listView = ( ListView ) findViewById(R.id.listview);
// Setting the adapter to the listView
listView.setAdapter(adapter);
// Item Click Listener for the listview
listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// When clicked, show a toast with the TextView text
Intent countrys = new Intent(adapter.toString());
startActivityForResult(countrys, 0);
}
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.mainmenu, (android.view.Menu) menu);
return true;
} });
}
};
Thank you
Put this inside of setOnItemClickListener() method
listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
if (position==0) {
Intent news = new Intent(Menu.this ,RSSItem.class);
startActivity(news);
}else if (position==1) {
Intent calendar = new Intent(Menu.this ,calender.class);
startActivity(news);
}
// and so on
}
Because the of the fact that the order it maintain, then you have the possibility to go over the position to fire your desired intent
Inside
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
HashMap<String,String> aMap = (HashMap<String,String>)parent.getItemAtPosition(position);
}
see http://developer.android.com/reference/android/widget/AdapterView.html#getOnItemClickListener()
Maybe this helps?
Related
I am a beginner and I have a project to do for school. So the problem is, that whenever I try to open a new Activity on the Emulator by clicking on the listed entries I get to the activity, so far so good but the problem is because of the search bar, the positions of the entries changes. So as far as you can see in my code, Cyberpunk will always be the first entry and Dark Souls the second. But if I specificaly look for Dark Souls in the searchBar (it will only show up Dark Souls) I am getting Cyberpunk activity as a result since it is on position 1.
(I didn't finish all activities for the other entries yet, trying to fix this issure first)
I've already tried stuff like if, switch etc. but I just get the same result. I would really appreciate any help! :)
Regards
Here is my Code:
package at.fh.joanneum.smartplay;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.SearchView;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import java.util.ArrayList;
public class Searchlist extends AppCompatActivity {
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_searchlist);
final ArrayList<String> listGames = new ArrayList<>();
listGames.add("Cyberpunk");
listGames.add("Anno 1800");
listGames.add("Dark Souls 3");
listGames.add("Battlefield V");
listGames.add("Minecraft");
listGames.add("DayZ");
listGames.add("Counter Strike");
final ArrayList<Class> intents = new ArrayList<Class>();
intents.add(Cyberpunk.class);
intents.add(DarkSouls.class);
ListView myListView = (ListView) findViewById(R.id.listview_activity_Searchlist);
final ArrayAdapter<String> adapter = new ArrayAdapter<>(this,
android.R.layout.simple_list_item_1, listGames);
myListView.setAdapter(adapter);
SearchView mySearchView = (SearchView) findViewById(R.id.searchBar);
mySearchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String s) {
return false;
}
#Override
public boolean onQueryTextChange(String list) {
adapter.getFilter().filter(list);
return false;
}
});
myListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent listIntent = new Intent(getApplicationContext(),
intents.get(position));
startActivity(listIntent);
}
});
}
}
The top item is always the item at first index. Since you filter your adapter you change the order of items and therefore their positions, but you don't account for that when loading the Intent from your Intent List in the itemClick callback. You should either create a complex object that contains the display text and the Intent so when onClick is called, you can retrieve the clicked item and get the Intent from it. Or you can create a mapping of item-id and intent and then use the id-parameter of the click callback to retrieve the correct Intent. I would recommend the first solution.
Create a object like
class GameData{
private String text;
private Intent intent;
public GameData(String text, Intent intent){
this.text = text;
this.intent = intent;
}
public Intent getIntent(){
return intent;
}
public String toString(){
return text;
}
}
and fill your ArrayAdapter with those objects instead of Strings. Once the item is clicked, retrieve the item for the clicked position from the adapter and call its getIntent() method. This will deliver the desired Intent.
I'm trying to create an app that has different pages for topics and questions. I have created about two activites and am about to create more, like 40 activities. How can I do this without creating up to that number of activities?
Here is my MainActivity.java codes
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
private ListView mListView;
private Context context;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Declare the text view id
mListView = (ListView) findViewById(R.id.myList);
//Adding text to the array list
String booksArray[] = new String[]{"General Questions", "Mathematics",
"Physics",
"Chemistry",
"English"};
//Initialize the array list in the adapter
ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout
.simple_list_item_1, booksArray);
mListView.setAdapter(adapter);
//Set the listener for the list view item
mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
//if the position of item clicked is 1, it should open
//another activity
if(position == 1 ){
conditionOfIf();
}
else{
//A short message that notify user for an error
Toast.makeText(getApplicationContext(), "Please click on the first objcet",
Toast.LENGTH_LONG)
.show();}
}
});
}
//The real code that open another activity called Topics
private void conditionOfIf(){
Intent intent = new Intent(this, Topics.class);
startActivity(intent);
}
}
Fragments is your answer. your can create 40 fragments and have only one activity for managing that fragments.
And the best thing about fragments is that you can use the same UI for multiple purpose i.e reuse-ability which might come handy as you have large number of layouts.
i think this will be a great Fragment tutorial to start with,it is easy to understand yet powerful enough to teach you the fundamentals.
use fragments.
For learning fragments go to google or youtube videos.
There are many online sources available.
I am trying to create a list view in Java that allows each list item to open a web url address but I can not seem to get the code right. Please can some one show me where IO going wrong.
package com.sasquatchapps.hydraquip10.bestofmonsterquest;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
public class Season1Activity extends Activity{
private String episodes[] = {"America's Loch Ness Monster","Sasquatch Attack",
"Giant Squid Found","Birdzilla","Bigfoot","“Mutant K9","Lions in the Backyard","Gigantic Killer Fish","Swamp Beast","Russia's Killer Apemen","Unidentified Flying Creatures","The Real Hobbit",
"Giganto: The Real King Kong","American Werewolf"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ArrayAdapter<String> adapter = new
ArrayAdapter<>(this,
android.R.layout.simple_list_item_1, episodes);
setListAdapter(adapter);
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
Toast.makeText(this, "Item clicked;" + episodes[position], Toast.LENGTH_SHORT).show();
if (position == 0) {
Intent intent = new Intent(android.content.Intent.ACTION_VIEW, Uri.parse("https://www.youtube.com/watch?v=o7-RdxrCFAg"));
startActivity(intent);
}
}
}
You have some errors - Where is your listview? Modify your code
1) create listview -
ListView myList;
2) In your onCreate assign this list:
myList = (ListView) findViewById(R.id.my_list);
3) Set adapter to your list:
myList.setAdapter(adapter);
This is my first time creating android app. and what i want to create now is to make a list and when a user click a name in the list the detail of the click name will show. I am trying to create simple cursor adapter. But an error occur
The constructor SimpleCursorAdapter(QuestionsNew, int, Cursor, String[], int[]) is undefined.
What do you think is the possible reason for this. Below is some part of my code
package tk.wew.wew;
import info.androidhive.sqlite.model.LocalStorage;
import info.androidhive.sqlite.model.Message;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import static tk.askd.askd.CommonUtilities.*;
public class QuestionsNew extends Fragment {
Cursor cursor;
ListView nameList;
protected ListAdapter adapter;
// TextView tvCompany = (TextView)
// findViewById(R.id.tvContactListCompany);
private static final String TAG = "Question";
private ListView list;
private static List questions;
ArrayList<String> senders = new ArrayList<String>();
ArrayList<String> shortMsg = new ArrayList<String>();
ArrayList<Integer> imageId = new ArrayList<Integer>();
SimpleCursorAdapter myCursorAdapter;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view;
//CommonUtilities.sendAQuestion(getActivity(), "msg123Kjjj11", "richmund_10023", "lofrancs1231", "Apil ka?");
questions = CommonUtilities.getAllQuestions(getActivity(), "N", null);
if(questions.size() > 0){
view = inflater.inflate(R.layout.questions_main_layout, container, false);
AskdDatabaseHelper msg_db = new AskdDatabaseHelper(getActivity());
List<Message> messages = msg_db.getAllQuestions("N", "lofrancs1231");
Cursor cursor = msg_db.getAllQuestions3();
// Setup mapping from cursor to view fields:
String[] fromFieldNames = new String[] { "KEY_MSG_MESSAGE_ID","KEY_MSG_MESSAGE" };
int[] toViewIDs = new int[] { R.id.KEY_MSG_MESSAGE_ID, R.id.KEY_MSG_MESSAGE_ID };
/* SimpleCursorAdapter myCursorAdapter = new SimpleCursorAdapter(this, // Context
R.layout.message_list_item, // Row layout template
cursor, // cursor (set of DB records to map)
fromFieldNames, // DB Column names
toViewIDs // View IDs to put information in
);*/
myCursorAdapter = new SimpleCursorAdapter(QuestionsNew.this,
R.layout.message_list_item,
cursor,
fromFieldNames,
toViewIDs);
ListView contactList = (ListView) getView().findViewById(R.id.lvContacts);
contactList.setAdapter(myCursorAdapter);
for(int m=0; m<questions.size(); m++){
senders.add(messages.get(m).getFromUser());
shortMsg.add(messages.get(m).getMessage());
imageId.add(R.drawable.ic_launcher);
}
} else {
view = inflater.inflate(R.layout.fragments_question_new, container, false);
((TextView)view.findViewById(R.id.textView)).setText("No New Questions");
}
return view;
}
#Override
public void onStart(){
super.onStart();
Log.v(TAG, ": New onStart");
if(questions.size() > 0){
list = (ListView) getView().findViewById(R.id.list);
CustomLst adapter = new CustomLst(getActivity(), senders, imageId, shortMsg);
list.setAdapter(adapter);
list.setOnItemClickListener(new OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id){
// Cursor listCursor = (Cursor) parent.getItemAtPosition(position);
// Cursor listCursor = (Cursor) parent.getAdapter().getItem(position);
// Log.d("TAG", (String) parent.getItemAtPosition(id));
Toast.makeText(getActivity(),
"Position:"+ parent.getItemIdAtPosition((int) id), Toast.LENGTH_LONG)
.show();
// int message = listCursor.getInt(listCursor.getColumnIndex(AskdDatabaseHelper.KEY_MSG_MESSAGE_ID));
/*
Intent intent = new Intent(getActivity(), QuestionDetail.class);
intent.putExtra("Message_ID", listCursor.getString(listCursor.getColumnIndex(AskdDatabaseHelper.KEY_MSG_MESSAGE_ID)));
startActivity(intent);
// ListView clicked item index
int Position = position;
// ListView clicked item value
String itemValue = (String) list.getItemAtPosition(Position);
// show alert
// Toast.makeText(getActivity(),
// "Position:" + Position + " Listitem:" + itemValue, Toast.LENGTH_LONG)
// .show();
*/
}
});
} else {
Log.e(TAG, "No new question");
}
}
}
Change your constructor as below
myCursorAdapter = new SimpleCursorAdapter(getActivity(),
R.layout.message_list_item,
cursor,
fromFieldNames,
toViewIDs);
The first param is a Context. This QuestionsNew.this is not a valid context. Fragment does not extend Context.
Activity
java.lang.Object
↳ android.content.Context // check this
↳ android.content.ContextWrapper
↳ android.view.ContextThemeWrapper
↳ android.app.Activity // check this
Fragment
java.lang.Object
↳ android.app.Fragment // check this
So get context in fragment use getActivity()
public final Activity getActivity ()
Added in API level 11 Return the Activity this fragment is currently
associated with.
Also
SimpleCursorAdapter(Context context, int layout, Cursor c, String[]
from, int[] to) This constructor was deprecated in API level 11. This
option is discouraged, as it results in Cursor queries being performed
on the application's UI thread and thus can cause poor responsiveness
or even Application Not Responding errors. As an alternative, use
LoaderManager with a CursorLoader.
It is same when you use ArrayAdapter in Fragment class. The first param to the constructor of ArrayAdapter is a valid context. So even in that case you need to use getActivity() instead of FragmentName.this.
This question already has answers here:
How to Call Activity using ListView Array
(2 answers)
Closed 9 years ago.
Iam using Sherlock fragment to make a Action Bar. and I have ListView in action bar, but I will my listview can call activity .. Please help me Thanks.. :)
in this code have a listview using array list . and i want to mylist can call same activity.
So it can Like menu in action bar. and when we clik listview ..he can call activity
thank.. please help me !
Please correct my code ..how to call activity with each option in listview.. thanks..
AppleFragment.java
package iqbal.apps.visitkuningan;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.AdapterView.OnItemClickListener;
import com.actionbarsherlock.app.SherlockListFragment;
public class AppleFragment extends SherlockListFragment{
/** An array of items to display*/
String apple_versions[] = new String[]{
"Mountain Lion",
"Lion",
"Snow Leopard",
"Leopard",
"Tiger",
"Panther"
};
/** An array of images to display*/
int apple_images[] = new int[]{
R.drawable.mountainlion,
R.drawable.lion,
R.drawable.snowleopard,
R.drawable.leopard,
R.drawable.tiger,
R.drawable.panther
};
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
// Each row in the list stores country name, currency and flag
List<HashMap<String,String>> aList = new ArrayList<HashMap<String,String>>();
for(int i=0;i<5;i++){
HashMap<String, String> hm = new HashMap<String,String>();
hm.put("txt", apple_versions[i]);
hm.put("img", Integer.toString(apple_images[i] ) );
aList.add(hm);
}
// Keys used in Hashmap
String[] from = { "img","txt" };
// Ids of views in listview_layout
int[] to = { R.id.img,R.id.txt};
// Instantiating an adapter to store each items
// R.layout.listview_layout defines the layout of each item
SimpleAdapter adapter = new SimpleAdapter(getActivity().getBaseContext(), aList, R.layout.listview_layout, from, to);
// Getting a reference to listview of main.xml layout file
ListView listview = AppleFragment.this.getListView();
listview.setAdapter(adapter);
// Setting the adapter to the listView
listview.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent,
View view, int position,long id) {
// ?? please add code in here to call activity from each option in listview.. T_T or correct my code
}
});
return super.onCreateView(inflater, container, savedInstanceState);
}
}
Edit the setOnItemClickListener and insert a condition which checks for position of the item and starts and activity depending on the item clicked.
Should look something like this
listview.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0,View arg1, int position, long arg3) {
Intent n = null;
switch (position){
case 0:
n = new Intent(getActivity(), Class0.class);
break;
case 1:
n = new Intent(getActivity(), Class1.class);
break;
}
if(null!=n)
startActivity(n);
}
});