Ok. I'm working on a project, I have already created the listview, but I want to click on it and go to another page e.g like when you click a button it goes to another page, exactly like that, this is my code so far:
import android.app.ListActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class listV extends ListActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setListAdapter( new ArrayAdapter<String>(this, R.layout.listview,Food));
ListView list = getListView();
list.setTextFilterEnabled(true);
list.setOnItemClickListener(new OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), ((TextView) arg1).getText(), Toast.LENGTH_SHORT).show();
}
});
}
static final String[] Food = new String[]{
"Physical Activity" , "Healthy Diet", "Childhood Obesity"
};
}
Any help would be appreciated.
I'm just a beginner so please try to explain in detail.
Looks like you're 95% of the way there. In your onItemClick method of the listener, you just have to start the new activity like you normally would. You can use the 3rd argument of the onItemClick to give you the position of the listview item that was click and use that to differentiate the activity you call OR pass it into a single activity:
#Override
public void onItemClick(AdapterView<?> arg0, View position, int arg2, long arg3) {
Intent i;
if( position == 1 ){
i = new Intent(listV.this, MyFirstActivity.class);
} else if (position == 2){
i = new Intent(listV.this, MySecondActivity.class);
} else if (position == 3) {
i = new Intent(listV.this, MyThirdActivity.class);
} else {
return;
}
startActivity(i);
}
I am a fairly new programmer myself and I am attempting to create the same thing. A ListView where the user is able to click each individual item in the list and each item will start its own activity. Please check out my code based on the help you gave earlier.
package com.tylerbmc.test;
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class Main extends ListActivity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
setListAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,
getResources().getStringArray(R.array.abdominals)));
ListView list = getListView();
list.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
Intent i;
if (position == 1) {
i = new Intent(Main.this, Second.class);
startActivity(i);
}
else if (position == 2) {
i = new Intent(Main.this, Third.class);
startActivity(i);
}
}
});
}
}
Related
package at.thesis.ticmip;
import java.util.ArrayList;
import android.app.ListActivity;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
public class Mainadminvdictionary extends ListActivity {
private ArrayList<String> results = new ArrayList<String>();
private String ddct = Databaseadapter.dtbldctnry;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_admin_vdictionary);
SQLiteDatabase db= openOrCreateDatabase(Databaseadapter.DATABASE_NAME,MODE_PRIVATE, null);
try {
Cursor c= db.rawQuery("select * from Ddictionary", null);
//Looping through all rows
if (c != null ) {
if (c.moveToFirst()) {
do {
String dss = c.getString(c.getColumnIndex("disease"));
results.add(dss);
}while (c.moveToNext());
}
}
} catch (SQLiteException se ) {
Log.e(getClass().getSimpleName(), "Could not create or Open the database");
} finally {
db.close();
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, results);
setListAdapter(adapter);
getListView().setTextFilterEnabled(true);
}
}
i have my code here that will show the data and display in listview my problem now is how can i click an item by its id? I tried using protected void onListItemClick(ListView l, View v, int position, long id) {} but its not working
Try this :
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
}
});
this work for me
getListView().setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String item = (String) getListAdapter().getItem(position);
if (position == 0) {
Toast.makeText(Mainadminvdictionary.this, item + " selected", Toast.LENGTH_LONG).show();
Intent intent = new Intent(Mainadminvdictionary.this, Mainuserstop10.class); startActivity(intent);
}
}
});
There no error, but when i click a item of listview nothing happen. I have more than 10 items. and go to difference activities. Any idea? I'am beginner in eclipse also java.
Example:
1.Niat (ListView-OnItemClickListener) will go to NiatActivity.class
2.Lafaz (ListView-OnItemClickListener) will go to LafazActivity.class
Here my code. Thanks in advance.
import java.util.ArrayList;
import java.util.HashMap;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
public class MainTwoActivity extends Activity {
// List view
private ListView lv;
// Listview Adapter
ArrayAdapter<String> adapter;
// Search EditText
EditText inputSearch;
// ArrayList for Listview
ArrayList<HashMap<String, String>> productList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_two);
// Listview Data
final String products[] = { "Niat",
"Lafaz", "Solat" };
lv = (ListView) findViewById(R.id.list_view);
inputSearch = (EditText) findViewById(R.id.inputSearch);
// Adding items to listview
adapter = new ArrayAdapter<String>(this, R.layout.list_item,
R.id.product_name, products);
lv.setAdapter(adapter);
/**
* Enabling Search Filter
* */
inputSearch.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence cs, int arg1, int arg2,
int arg3) {
// When user changed the Text
MainTwoActivity.this.adapter.getFilter().filter(cs);
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1,
int arg2, int arg3) {
// TODO Auto-generated method stub
}
#Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
}
});
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// if(position == 1)
String openClass = adapter.getItem(position);
if (openClass.equals("Niat")) {
// code specific to first list item
Intent myIntent = new Intent(view.getContext(),
NiatActivity.class);
startActivity(myIntent);
}
else if (openClass.equals("Lafaz")) {
Intent myIntent1 = new Intent(view.getContext(),
LafazActivity.class);
startActivity(myIntent1);
}
}
});
}
}
Use Reflection is better but also u can use of Hashmap
Use OF HashMap
HashMap<String, Class>hashMap=new HashMap<String, Class>();
hashMap.put("Niat",NiatActivity.class);
hashMap.put("Lafaz",LafazActivity.class);
hashMap.put("Solat",SolatActivity.class);
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
String openClass = adapter.getItem(position);
Intent myIntent1 = new Intent(MainTwoActivity.this,
hashMap.get(openClass));
startActivity(myIntent1);
}
MaWhen starting a new activity you should use
Intent myIntent = new Intent(MainTwoActivity.this ,NiatActivity.class);
View getContext() doesnt carry the full context of your app. Read up here
I have an application that extends ActionBarActivity, but I'm using ListView and I need to implement OnItemClickListener and I'm not sure how to do this without extending ListActivity. Also I want to ask you: Moreover I have a button and I need to listen if the button is clicked or if an item in the list is clicked. I'm not pretty sure how to do this.
So I would really appreciate if you help me :)
Here is my code:
package com.src.vicnote;
import java.io.File;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.os.Build;
public class MainActivity extends ActionBarActivity {
Button newButton;
String path = Environment.getExternalStorageDirectory().toString()+"/VICNote";
String lastOfPath;
File f = new File(path);
File files[] = f.listFiles();
String[] theNamesOfFiles = new String[files.length + 1];
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
theNamesOfFiles[0] = "Create new note";
for(int i = 1; i < theNamesOfFiles.length; i++) {
lastOfPath = files[i-1].toString().split("/")[files[i-1].toString().split("/").length-1];
theNamesOfFiles[i] = lastOfPath.replace(".txt","");
Log.d("Files", "String: " + theNamesOfFiles[i]);
}
ListView lv = (ListView) findViewById(R.id.notesList);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,
theNamesOfFiles);
lv.setAdapter(adapter);
newButton = (Button) findViewById(R.id.buttonNew);
newButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent newNote = new Intent(MainActivity.this, NewNoteActivity.class);
startActivity(newNote);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
You can implement the OnItemClickListener interface and override onItemClick
lv.setAdapter(adapter);
lv.setOnItemClickListener( new OnItemClickListener()
{
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
Toast.makeText(MainActivity.this.this, "List View row Clicked at"+position,Toast.LENGTH_SHORT).show();
}
});
If the button belongs to activity_main.xml then what you have
newButton.setOnClickListener(new View.OnClickListener()
is right
You can set item click listener for ListView using this code.
lv.setAdapter(adapter);
lv.setOnItemClickListener(new OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> adapter, View v, int position,
long arg3)
{
// it is used to get the clicked string
String theNamesOfFile = adapter.getItem(position);
}
});
I guess it can help you.
Hello I'm new on android I have this trouble with my code
package com.example.spinner;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.Toast;
public class MainActivity extends Activity {
Spinner lista;
String[] datos = {"opcion1", "opcion2", "Ir a listView"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lista = (Spinner) findViewById(R.id.lista1);
ArrayAdapter<String> adaptador = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, datos);
lista.setAdapter(adaptador);
lista.setOnItemSelectedListener(new OnItemSelectedListener(){
#Override
public void onItemSelected(AdapterView<?> adapterView, View view,
int i, long l) {
// TODO Auto-generated method stub
switch (i){
case 1:
Toast to = Toast.makeText(getApplicationContext(), datos[i], Toast.LENGTH_SHORT);
to.show();
break;
case 2:
Intent int = new Intent(MainActivity.this, VentanaListView.class);
break;
}
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
}
}
In the switch case 2 is where a litte box appears saying :
Intent cannot be resolved to a variable
I have already import the Intent using import android.content.Intent; and It says
The import android.content.Intent is never used
Please do you know what should I do?
Change this
Intent int = new Intent(MainActivity.this, VentanaListView.class)
to
Intent intent = new Intent(MainActivity.this, VentanaListView.class)
int is a keyword in java
You probably want to call startActivity(intent) also
You can't name a variable int; that's a keyword. Choose a different variable name, such as intent.
Intent int = new Intent(MainActivity.this, VentanaListView.class);
int is a reseverd word in java (a Keyoword) ,and it can not be used a variable`s name
list_item.xml: http://pastebin.com/bn56L3NN
What happens after onCreate() and after creating the Comm-object is that I get a "Connection established" message which gets picked up in another thread and I get the message in receiveMessage, I then send "list" and get called back to receiveMessage again.
I've checked with Log.v and I do get back the message that I want to list, my problem is that I can't display it in the ListActivity when I get to these lines, maybe I should replace them with something else?:
setListAdapter(new ArrayAdapter<String>(this, R.layout.list_item, userRooms));
ListView lv = getListView();
lv.setTextFilterEnabled(true);
Full code:
package elf.app;
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import elf.app.comm.CommClient;
import elf.app.comm.CommListener;
import elf.app.entity.ELFList;
import elf.app.entity.Entry;
public class RoomListActivity extends ListActivity implements CommListener {
private ELFList eList;
private String[] userRooms;
private CommClient comm;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
eList = new ELFList();
comm = new CommClient( getIntent().getExtras().getString("ip"),
getIntent().getExtras().getInt("port") );
comm.setListener(this);
new Thread(comm).start();
}
public void receiveMessage(String IP, String message, int id) {
if(message.equals("Connection established")) {
comm.send("list");
}
if(message.charAt(0)=='#') {
String[] strArr = toStringarr(message);
eList.add(strArr);
listItems();
}
}
public String[] toStringarr(String str) {
String substr = str.substring(1);
return substr.split("#");
}
public void listItems() {
userRooms = eList.returnNames();
setListAdapter(new ArrayAdapter<String>(this, R.layout.list_item, userRooms));
ListView lv = getListView();
lv.setTextFilterEnabled(true);
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Entry e = eList.getEntry(position);
String roominfo = e.toString();
Intent intent = new Intent(RoomListActivity.this, RoomInfoActivity.class);
intent.putExtra("entry",roominfo);
intent.putExtra("ip", getIntent().getExtras().getString("ip"));
intent.putExtra("port", getIntent().getExtras().getInt("port"));
comm.disconnect();
RoomListActivity.this.startActivity(intent);
}
});
}
}
You forgot to set a content view for your Activity in onCreate() which contains the layout for the Activity. So there is no list to display which could display anything. Define a layout in a layout XML file and set it as content view using setContentView().