I'm trying to create a ListView where you click on a row and it takes you to a page with the name and other details. I've spent many days trying to make it work, but at the moment all I have is that clicking the row takes you to a blank page. I've searched many questions but none of them add a title to the new page! Here's my listview activity:
package com.example.cookbook;
import java.util.ArrayList;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.AdapterView.OnItemClickListener;
import android.view.View;
public class SecondScreenActivity extends Activity
{
ArrayList<String> RecipeList;
public void onCreate(Bundle saveInstanceState)
{
super.onCreate(saveInstanceState);
setContentView(R.layout.main);
// Get the reference of ListViewRecipes
ListView RecipeListView=(ListView)findViewById(R.id.mainListView);
RecipeList = new ArrayList<String>();
getRecipeNames();
// Create The Adapter with passing ArrayList as 3rd parameter
ArrayAdapter<String> arrayAdapter =
new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, RecipeList);
// Set The Adapter
RecipeListView.setAdapter(arrayAdapter);
// register onClickListener to handle click events on each item
RecipeListView.setOnItemClickListener(new OnItemClickListener()
{
// argument position gives the index of item which is clicked
public void onItemClick(AdapterView<?> arg0, View v,int position, long arg3)
{
Intent i=new Intent(SecondScreenActivity.this, ThirdScreenActivity.class);
i.putExtra("position", position);
startActivity(i);
}
});
}
void getRecipeNames()
{
RecipeList.add("Recipe1");
RecipeList.add("Recipe2");
RecipeList.add("Recipe3");
RecipeList.add("Recipe4");
RecipeList.add("Recipe5");
RecipeList.add("Recipe6");
RecipeList.add("Recipe7");
RecipeList.add("Recipe8");
RecipeList.add("Recipe9");
RecipeList.add("Recipe10");
}
}
Here's my new page activity:
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.TextView;
public class ThirdScreenActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.screen2);
TextView t = ((TextView)findViewById(R.id.textviewPosition));
Intent intent = getIntent();
String position = intent.getStringExtra("position");
t.setText(position);
}
}
and screen2 is:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#ffffff">
<TextView
android:id="#+id/textviewPosition"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textColor="#000000"
android:textAppearance="?android:attr/textAppearanceLarge" />
</LinearLayout>
I'm not getting any error messages in eclipse or logcat, it's just showing a blank page when I click!
Thanks for the help
edit: tried (String.valueOf(position)) instead of (position) and it now says null for every row. eg. on ThirdScreenActivity:
TextView t = ((TextView)findViewById(R.id.textviewPosition));
Intent intent = getIntent();
String position = intent.getStringExtra("position");
t.setText(String.valueOf(position));
the reason you are not getting anything is because you are passing an int. position is an int not a string extra so the getStringExtra wont work because the extra is an int.
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View itemClicked,
int position, long id) {
TextView textView = (TextView) itemClicked;
String strText = textView.getText().toString();
Intent i = new Intent(SecondScreenActivity.this, ThirdScreenActivity.class);
i.putExtra("position", strText);
startActivity(i);
}
});
First of all, why are you creating the same intent and starting it twice?
You just need this:
Intent i = new Intent(SecondScreenActivity.this, ThirdScreenActivity.class);
i.putExtra("position", position);
startActivity(i);
Edit:
Secondly, are you sure your screen2 contains visible elements? You should post your XML
The problem was that you were passing an int as a extra:
i.putExtra("position", position);
and receiving a string:
Intent intent = getIntent();
String position = intent.getStringExtra("position");
t.setText(position);
...So you have to change this two lines for the following lines...
Intent intent = getIntent();
int position = intent.getExtras().getInt("position");
t.setText(String.valueOf(position));
EDIT: If you wanna pass a string then do this...
i.putExtra("position", String.valueOf(position));
...So you have to receive the string on the other activity...
Intent intent = getIntent();
String position = intent.getExtras().getString("position");
t.setText(position);
Related
int countervalue = i.getIntExtra("Count", 10);
I have this line of code in a different activity when someone clicks a button they go to that activity. Without this line of code the app runs perfectly.
Here is the whole code for the activity:
package com.example.navjeevenmann.mytycoon;
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;
public class SecondActivity extends AppCompatActivity {
private ListView listView;
Intent i = getIntent();
int userchoice;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
int countervalue = i.getIntExtra("Count", 0);
String[] values = {"Apple($20)- Generates $40/sec",
"Second", "Third"};
listView = (ListView) findViewById(R.id.List);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_expandable_list_item_1, android.R.id.text1, values);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
}
});
}
}
initialize i = getIntent(); inside onCreate() method
right before int countervalue = i.getIntExtra("Count", 0);
you can use bundle such as
First Activity
Intent intent = new Intent(MainActivity.this,Main2Activity.class);
intent.putExtra("int",20);
startActivity(intent);
Now in Second Activity use this
Bundle i = getIntent().getExtras();
int value = i.getInt("int");
Vyacheslav's answer is correct, but here's a little more info.
When you write:
public class SecondActivity extends AppCompatActivity {
Intent i = getIntent();
}
Your Intent i will be intialized as soon as your SecondActivity instance is created, and it will be set to the results of the getIntent() method.
If you look at the source for this method, you see:
public Intent getIntent() {
return mIntent;
}
At the time your SecondActivity instance is created, mIntent is null. So your activity is behaving as though you had written this instead:
public class SecondActivity extends AppCompatActivity {
Intent i = null;
}
The solution, as Vyacheslav said, is to initialize the i variable later on. Anywhere inside onCreate() (after the super call) is a fine place to do so, but waiting until just before your i.getIntExtra("Count", 0) call will work as well.
I got problem when trying to get checked item from listView through predefined xml layout simple_list_item_single_choice and select item then set text of a TextView that is in another activity.
This is my showMyUI method that call from MainActivity on click of TextView
dateRange.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Toast.makeText(MainActivity.this, "Range clicked",Toast.LENGTH_SHORT).show();
DateRangeClass day=new DateRangeClass(MainActivity.this,dayRangeSelected);
day.showMyUI();
overridePendingTransition(R.anim.right_to_left, R.anim.left_to_right);
}
});
And my DateRangeClass is
package tutorial.projecttwofilter;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
public class DateRangeClass {
Context context;
LinearLayout backButton;
ListView rangeList;
TextView rangeText;
String[] dateRangeData= new String[]{"Next 7 Days", "Next 14 Days", "Next 30 Days"};
public DateRangeClass(Context context,TextView rangeText) {
this.context = context;
this.rangeText=rangeText;
}
public void showMyUI(){
((Activity)context).setContentView(R.layout.daterange);
backButton= (LinearLayout) ((Activity)context).findViewById(R.id.backButton);
backButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
((Activity) context).finish();
((Activity) context).overridePendingTransition(R.anim.left_to_right, R.anim.right_to_left);
}
});
rangeList= (ListView) ((Activity)context).findViewById(R.id.dateRangeList);
ArrayAdapter<String> adapter= new ArrayAdapter<>(context, android.R.layout.simple_list_item_single_choice, dateRangeData);
rangeList.setAdapter(adapter);
rangeList.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
rangeList.setItemChecked(position, true);
if(rangeList.isItemChecked(position))
Toast.makeText(context, "Checked item is"+rangeList.getCheckedItemPosition(), Toast.LENGTH_SHORT).show();
rangeText.setText("You new Change "+rangeList.getCheckedItemPosition());
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
Toast.makeText(context, "Nothing selected", Toast.LENGTH_SHORT).show();
}
});
}
}
Create DateRangeClass as an activity not as normal class and pass the information using bundle. As i can see you are passing textview instead of that you can pass text as string and can show in second activity.
To transfer data
String textToBesend = "Text from textview";
Intent i = new Intent(this, DateRangeActivity.class);
i.putExtra("text", textToBesend);
startActivity(i);
and to recieve data in DateRangeActivity write this in oncreate method.
Intent intent = getIntent();
String textPassedFromFirstActivity = intent.getExtras().getString("text");
You can refer below tutorial for your purpose hope it helps.
passing data to activity from listview
You have not started your activity.
Use startActivity and putIntent method on button click and in your second activity use getIntent method to display the text.
I made an Activity for searching people that also shows history of recent research.
If I long click on an item of the history it asks me if I want to delete it. If I press "Yes" it deletes the list item.
So, I write something and click to "Search" button. This brings me in another Activity with results. Here I click on result so it stores the person info and brings me in the person page.
When I come back I don't see the new person in the history.
So I overwritten onResume() but it still not work and now I cannot delete items from the history list.
Here the code:
package com.lpsmt.proffinder;
import java.util.List;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Resources;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
import com.lpsmt.R;
public class HomeActivity extends Activity
{
protected Db db = null;
protected List<ProfBean> historyProfs = null;
protected ProfListItemAdapter listAdapter = null;
protected ListView listView = null;
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
this.db = new Db(this);
this.setContentView(R.layout.prof_finder_home);
this.historyProfs = this.db.getHistory(-1); // -1 means with no limits
this.listAdapter = new ProfListItemAdapter(HomeActivity.this, R.id.prof_finder_history_list_view, this.historyProfs);
this.listView = (ListView) this.findViewById(R.id.prof_finder_history_list_view);
listView.setAdapter(this.listAdapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(HomeActivity.this, ProfPageActivity.class);
Bundle bundle = new Bundle();
bundle.putString("profId", HomeActivity.this.historyProfs.get(position).getProfId());
intent.putExtras(bundle);
HomeActivity.this.startActivity(intent);
}
});
listView.setOnItemLongClickListener(new OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view,
int position, long id)
{
Resources resources = HomeActivity.this.getResources();
String title = resources.getString(R.string.prof_finder_history_delete_title);
String message = resources.getString(R.string.prof_finder_history_delete_message);
AlertDialog.Builder adb=new AlertDialog.Builder(HomeActivity.this);
adb.setTitle(title);
adb.setMessage(message);
final int positionToRemove = position;
String positive = resources.getString(R.string.prof_finder_history_delete_positive);
String negative = resources.getString(R.string.prof_finder_history_delete_negative);
adb.setNegativeButton(negative, null);
adb.setPositiveButton(positive, new AlertDialog.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
ProfBean prof = HomeActivity.this.historyProfs.get(positionToRemove);
HomeActivity.this.db.deleteProf(prof.getProfId());
HomeActivity.this.historyProfs.remove(positionToRemove);
HomeActivity.this.runOnUiThread(new Runnable() {
public void run() {
HomeActivity.this.listAdapter.notifyDataSetChanged();
}
});
}});
adb.show();
return true;
}
});
}
public void searchProf(View view) throws Exception
{
EditText queryEditText = (EditText) this.findViewById(R.id.prof_finder_search_query);
String query = queryEditText.getText().toString().trim();
queryEditText.setText(query);
if (query.length() < 3) {
String message = this.getResources().getString(R.string.prof_finder_query_too_short);
Toast.makeText(this, message, Toast.LENGTH_LONG).show();
return;
}
Intent intent = new Intent(HomeActivity.this, SearchResultActivity.class);
Bundle bundle = new Bundle();
bundle.putString("query", query);
intent.putExtras(bundle);
this.startActivity(intent);
}
public void onResume()
{
super.onResume();
this.historyProfs = this.db.getHistory(-1);
this.listAdapter.notifyDataSetChanged();
}
}
You haven't set any new data to list view. Thats why your new contact isn't added to the list after notifyDataSetChanged(). You need to add some method into adapter like
setData(List<ProfBean> data)
{
this.currentAdaptersList= data;
}
and then call notifyDataSetChanged(). So the final onResume will be :
public void onResume()
{
super.onResume();
this.historyProfs = this.db.getHistory(-1);
this.listAdapter.setData(this.historyProfs);
this.listAdapter.notifyDataSetChanged();
}
Enjoy.
And using onResume() for this task is bad idea. Is better to use onActivityResult.
notifyDataSetChanged() didn't work for me either. I was able to solve this a little bit differently:
I use OnStart() (in a derived class from Fragment)
I use setNotifyOnChange() of the ArrayAdapter:
ListView listView = (ListView) findViewById(R.id.logListView);
listView.setAdapter(logAdapter);
logAdapter.setNotifyOnChange(true);
I create the adapter once:
logAdapter = new ArrayAdapter(activity, android.R.layout.simple_list_item_1, activity.logMessages);
in onViewCreated().
I am displaying a list view in android. When I click on each item that particular page should open. So for that I had written the following code.
package com.splash;
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;
public class Information extends Activity {
private String[] Countries;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.information);
Countries = getResources().getStringArray(R.array.countries);
ListView list = (ListView)findViewById(R.id.list);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.row, Countries);
list.setAdapter(adapter);
registerForContextMenu(list);
}
protected void onListItemClick(ListView l, View v, int position, long id) {
// Get the item that was clicked
Object o = this.getListAdapter().getItem(position);
String keyword = o.toString();
if((keyword.equals("test1"))){
Intent intent=new Intent(getApplicationContext(),lvereview.class);
startActivity(intent);
}
else if(keyword.equals("test2")){
Intent i = new Intent("android.intent.action.VIEW", Uri.parse("http://www.Facebook.com/canadaqbank"));
startActivity(i);
}
else if(keyword.equals("test3")){
Intent intent=new Intent(getApplicationContext(),recommendfriend.class);
startActivity(intent);
}
else if(keyword.equals("test3")){
Intent i = new Intent("android.intent.action.VIEW", Uri.parse("http://www.Facebook.com/canadaqbank"));
startActivity(i);
}
else if(keyword.equals("test4")){
Intent intent=new Intent(getApplicationContext(),ContactUs.class);
startActivity(intent);
}
else if(keyword.equals("test5")){
Intent intent=new Intent(getApplicationContext(),receiveemail.class);
startActivity(intent);
}
else
{
Intent intent=new Intent(getApplicationContext(),Otherapps.class);
startActivity(intent);
}
//tabView.setCurrentView(R.layout.rowlayout);
//setContentView(tabView.render(2));
}
}
Here I have created the list items in strings.xml file. When I m executing this code it is displaying "The method getListAdapter() is undefined for the type Information".What is the problem here...why cant I use that method? Any suggestion will be helpful....
Extend ListActivity, not Activity.
hey all.. i have been looking at other questions to get help and answers without luck..
my problem is that i want to open different class from my listView. according to the specific name in the listView. . the names are in lv_arr[] ..
If anybody can give a detailed answer i will be very thankfull and happy..
Im new in android and not the best in java :-(
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
public class StatusActivity extends Activity implements OnItemClickListener {
public ListView lv1;
public String lv_arr[]= {"John", "Andrew","alex","alice","bob","bla bla"};
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.tabview);
lv1=(ListView)findViewById(R.id.ListView01);
lv1.setAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1 , lv_arr));
lv1.setOnItemClickListener(this);
}
public boolean onCreateOptionsMenu(Menu menu) {
new MenuInflater(getApplication())
.inflate(R.menu.menu, menu);
return(super.onPrepareOptionsMenu(menu));
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.close:
super.finish();
break;
case R.id.icontext:
Intent i = new Intent(this, InfoActivity.class);
startActivity(i);
break;
}
return true;
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// TODO Auto-generated method stub
if(position == 0){
//Intent w = new Intent (this, Seekbar.class);
//startActivity(w);
Toast.makeText(this, "You pressed the first item in the list", Toast.LENGTH_SHORT).show();
}
else {
Toast.makeText(this, "You pressed all other items in the list", Toast.LENGTH_SHORT).show();
}
}
}
try this....if you have doubts add comment.
edited:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.tabview);
lv1=(ListView)findViewById(R.id.ListView01);
lv1.setAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1 , lv_arr));
lv1.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> a, View v, int position, long id) {
if(position==0){
Intent i = new Intent(this, InfoActivity.class);
startActivity(i);
} else if(position==1){
start another activity here...
}
}
});
}
hope it helps..
well i think you want to know basically the flow of how it is possible.
If all the classes which should be opened are more likely the same with just text and image changes and same layout then you dont need to create separate class file for each and every item clicked.
Just create one class file and one xml file and on item click pass on the bundle to the class file which will just changes the content on different item clicks and will workk as a charm as with this flow you will have only one class file and one xml file for all the list items you have
If you dont want to keep the same layout then you can obviously make the some views gone, visible or invisible at runtime
try something like this
public String lv_class_names[]= {Activity1.class.getName(), Activity2.class.getName(), Activity3.class.getName(), .....};
In the onItemClick method write
Intent i = new Intent(this, Class.forName(lv_class_name[position]));
startActivity(i);
for more details see this