IF statement on list view - java

Could someone help me change my IF statement to take in the detail that is inside the list view rather than the position of the listview? The list view will display three details which can be seen in the image below.
listViewSaves.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
if (position == 0) {
Intent myIntent = new Intent(MainActivity.this, Game_500.class);
MainActivity.this.startActivity(myIntent);
}
if (position == 1) {
Intent myIntent = new Intent(MainActivity.this, Game_1000.class);
MainActivity.this.startActivity(myIntent);
}
if (position == 2) {
Toast.makeText(getApplicationContext(), "Your toast message3.",
Toast.LENGTH_SHORT).show();
}
}
});
Check below image for an example of the list view
Check the below image for how the list view is populated
I want the listview to open up their own activity. For example IF the list view shows (Gaming) and (Under 500) - open Game_500.class.
If the list view has (Gaming) and (Under 1000) -open Game_1000.class.
The list view is populated by asking the users to select from 2 choices. Type of system - Gaming or Personal Use and the price of the system - Under 500 or Under 1000.

Use this code for ListView setOnItemClickListener. Here you have to take RigSaves object from List with position and check if it meet your criteria.
listViewSaves.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
RigSaves rigSaves = savesList.get(position);
// Gaming option
if( rigSaves.getRigType().equals("Gaming") && rigSaves.getRigPrice().equals("Under 500") ){
Intent myIntent = new Intent(MainActivity.this, Game_500.class);
startActivity(myIntent);
}
if( rigSaves.getRigType().equals("Gaming") && rigSaves.getRigPrice().equals("Under 1000") ){
Intent myIntent = new Intent(MainActivity.this, Game_1000.class);
startActivity(myIntent);
}
// personal option
if( rigSaves.getRigType().equals("Personal Use") && rigSaves.getRigPrice().equals("Under 500") ){
// start activity you want to start
}
if( rigSaves.getRigType().equals("Personal Use") && rigSaves.getRigPrice().equals("Under 1000") ){
// start activity you want to start
}
}
});
Hope it helps you. And let me know if you faced any problem

Try this out :
When calling Intent, you should use the class's name as string with package name. So if your class is called Game_1000 and is in the package mypackage.tests, then you should use:
Intent myIntent = new Intent(MainActivity.this, Class.forName("mypackage.tests.Game_1000"));
MainActivity.this.startActivity(myIntent);

Related

How to edit the values in an Activity opened by a fragment from the same fragment after it has been opened

I open the IndividualCouponsActivity from the fragment foodCouponsFragment within the parent CouponsActivity. I open the IndividualCouponsActivity with an Intent. After opening it, I want to edit the textViews and ImageViews of the IndividualCouponActivity. It should be noted that the IndividualCouponActivity is not a parent of the fragment.
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
Coupon coupon = foodCoupons.get(position);
Intent foodCouponsIntent = new Intent(getActivity(), IndividualCouponActivity.class);
startActivity(foodCouponsIntent);
IndividualCouponActivity activity = new IndividualCouponActivity();
activity.setValue(coupon.getCouponValue());
activity.setCompany(coupon.getCompanyName());
activity.setInfo(coupon.getDescription());
activity.setPts(coupon.getPts());
activity.setQr(coupon.getPicImageResourceId());
}
});
However, when I run the app, clicking on the listView makes the app shut down. This is what the log says at that time:
FATAL EXCEPTION: main
java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.Window$Callback android.view.Window.getCallback()' on a null object reference at android.support.v7.app.AppCompatDelegateImplBase.
I suspect that this is rooting from my use of the new IndividualCouponActivity activity to access the class methods. Thanks!
Don't create your activity with new...
Pass the Coupon object to your activity like this:
Intent intent = new Intent();
Bundle bundle = new Bundle();
bundle.putParcelable("coupon", coupon); // or putSerializable()
intent.putExtras(bundle);
intent.setClass(context, IndividualCouponActivity.class);
context.startActivity(intent);
In your activity in onCreate() you can get the passed coupon with:
getIntent().getExtras().getParcelable("coupon"); // or putSerializable()
Then set the values to your views.
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
Coupon coupon = (Coupon) adapterView.getItemAtPosition(position);
Intent foodCouponsIntent = new Intent(getActivity(), IndividualCouponActivity.class);
Bundle extras = new Bundle();
extras.put("value", coupon.getCouponValue());
extras.put("companyName", coupon.getCompanyName());
extras.put("description",coupon.getDescription());
extras.put("pts", coupon.getPts());
extras.put("picImageResourceId", coupon.picImageResourceId());
foodCouponsIntent.putExtras(extras);
startActivity(foodCouponsIntent);
}
});
and then in your IndividualCouponActivity's onCreate:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//get reference to views...
textViewValue = (TextView) findViewById(R.id.textViewValue);
//do this for all views....
//if all objects are String values, if not you know what you have to do...
//here you get values from extras
Bundle data = getIntent().getExtras();
String value = data.getStringExtra("value");
String companyName = data.getStringExtra("companyName");
String description = data.getStringExtra("description");
String pts = data.getStringExtra("pts");
String picImageResourceId = data.getStringExtra("picImageResourceId");
//here update UI views
//example
textViewValue.setText(value);
//do this for all views....
}
maybe there is some typo mistake, but this is the solution...
You can pass data between both activities using "putExtra"
Intent intent = new Intent(getBaseContext(), IndividualCouponActivity.class);
intent.putExtra("COUPON_COMPANY_NAME", coupon.getCompanyName());
startActivity(intent);

Cannot make a static reference to the non-static method in onitemclicklistener on custom listview adapter fetching data from sqlite database

Application Structure first:
//This class has a listview which will be populated from custom adapter
public class Transactions_show extends Activity implements OnItemClickListener
//This class is custom adapter which returns custom view for each row to be populated in above listview using sqlite database
public class CustomAdapter extends BaseAdapter
//Here all is working fine
//Now
//setting onitemclicklistener on each item of listview
public class Transactions_show extends ListActivity implements
OnItemClickListener {
List<Transactions> all_transactions;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.all_transactions);
DatabaseHandler db = new DatabaseHandler(getApplicationContext());
all_transactions = db.get_all_transactions();
size_of_transaction = all_transactions.size();
ListView all_transactions_list = (ListView) findViewById(R.id.all_transaction_show_list);
CustomAdapter adapter = new CustomAdapter(this, all_transactions);
all_transactions_list.setAdapter(adapter);
try {
all_transactions_list.setOnItemClickListener(this);
} catch (NullPointerException e) {
Log.e("null pointer exception at item click", e.getMessage());
}
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
Transactions single_transaction = new Transactions();
single_transaction = all_transactions.get(position);
Intent intent = new Intent(this, transacee_summary.class);
int p_n = single_transaction.get_phone_number();
Intent.putExtra("phone_number", p_n);
startActivity(intent);
/*
* Toast toast = Toast.makeText(getApplicationContext(), "Item " +
* (position + 1) + ": " +single_transaction.get_phone_number() ,
* Toast.LENGTH_SHORT); toast.setGravity(Gravity.BOTTOM |
* Gravity.CENTER_HORIZONTAL, 0, 0); toast.show();
*/
}
}
error is occuring here
Intent.putExtra("phone_number", p_n);
Which is : Cannot make a static reference to the non-static method putExtra(String, int) from the type Intent
Finding and trying on stack overflow for days and following google developers , decided to make a bundle as given in Passing a Bundle on startActivity()?
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,long id) {
Transactions single_transaction = new Transactions();
single_transaction = all_transactions.get(position);
Intent intent = new Intent(this, transacee_summary.class);
int p_n = single_transaction.get_phone_number();
Bundle extras = intent.getExtras();
try {
extras.putInt("phone_number", p_n);
} catch (NullPointerException e) {
Log.e("Null exception at putint", e.getMessage());
}
Intent.putExtra("phone_number", p_n);
startActivity(intent);
}
Error removed but when application runs but crashes at extras.puInt ,although next activity starts well if don't pass this bundle.
So thought about taking complete custom view row and extract field of phone number
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
Intent intent = new Intent(this, transacee_summary.class);
TextView textv = (TextView) findViewById(R.id.phone_number_show);
int p_n = Integer.parseInt( textv.getText().toString());
Intent.putExtra("phone_number", p_n);
startActivity(intent);
}
now error comes again same.
What goes around comes around!
It should probably be:
intent.putExtra("phone_number", p_n);
intent (the instance), not Intent (the class), since putExtra is indeed an instance method.
Problem is with this piece of code:
Intent intent = new Intent(this, transacee_summary.class);
int p_n = single_transaction.get_phone_number();
Intent.putExtra("phone_number", p_n);
You need to replace Class Intent refrence with Object Intent refrence as putExtra is not a static method it is an instance method
Intent intent = new Intent(this, transacee_summary.class);
int p_n = single_transaction.get_phone_number();
intent.putExtra("phone_number", p_n); // see starts with small i
Hope this helps.

Linking ListView objects to layouts android

Ive searched for this all over the internet and there seems to be no simple explanation or tutorial on how to do this.
Basically, I want a layout that has a ListView where the user can click on an object and it will take them to the next layout.
In other words, using the listview as links to other layouts.
Everything Ive found on the internet has the end result of using a Toast... However I dont want a toast, i want to link to the next page.
Your question is slightly confusing so I'm going to make an assumption.
Is [LinearLayout1 LinearLayout2 Breadcrumb] suppose to be navigation or tabs that when selected insert their corresponding content into the Main Content?
If so I would suggest using fragments for each piece of content. Then when you click the navigation/tab, perform an animation of the fragment which slides the content in and out.
See the google docs for how to use fragments: http://developer.android.com/guide/components/fragments.html
See another stackoverflow answer for how to do the slide animation: Android Fragments and animation
or
http://android-developers.blogspot.com/2011/08/horizontal-view-swiping-with-viewpager.html
Here is some code that outlines how to invoke an activity following a click on a list row. Hopefully you can adapt the Toast example you mention to make this work for you.
The basic idea is that you launch a new Activity with a new Intent. You can pass any data you need from the listView row as an extra in the Intent.
final static String[] months = new String[] {"Jan","Feb","Mar"};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_layout);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
R.layout.row_layout, R.id.text1, months);
setListAdapter(adapter);
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
int intItem = (int)id;
Intent intent= new Intent(this, SecondaryActivity.class);
intent.putExtra("MONTH", intItem);
startActivity(intent);
}
Why using ListView for it?
Each row must lead to different layout?
Its main benefits is in displaying dynamically changing data, but in your case data is constant, right?
Use vertical LinearLayout, fill it programmatically with "list elements", and add
leListComponent.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(YourActivity.this, TargetActivity.class));
}
});
to each.
If i didn't get it, and you feel good of using some adapter, it can be like this:
public class LeWrapper {
private String caption;
private Class<? extends Activity> target;
...POJO here...
}
v.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
//get leWrapper object from adapter
startActivity(new Intent(MenuActivity.this, leWrapper.getTarget()));
}
});
but its kinda overkill
Thanks for all the help guys. Sorry ive took my time replying. My solution is below :)
public class FP_WL1_ListView extends Activity {
private ListView lv1;
private String lv_arr[]={"Exercise Bike", "Treadmill", "Cross Trainer", "Squats", "Lunges"};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.fitnessprograms_wlday_one);
lv1=(ListView)findViewById(R.id.list);
lv1.setAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1 , lv_arr));
lv1.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
final TextView mTextView = (TextView)view;
switch (position) {
case 0:
Intent newActivity0 = new Intent(FP_WL1_ListView.this,FitnessPrograms_Wlone_sp.class);
startActivity(newActivity0);
break;
case 1:
Intent newActivity1 = new Intent(FP_WL1_ListView.this,FitnessPrograms_Wlone_Treadmill.class);
startActivity(newActivity1);
break;
case 2:
Intent newActivity2 = new Intent(FP_WL1_ListView.this,FitnessPrograms_Wlone_Crosstrainer.class);
startActivity(newActivity2);
break;
case 3:
Intent newActivity3 = new Intent(FP_WL1_ListView.this,FitnessPrograms_Wlone_Squats.class);
startActivity(newActivity3);
break;
case 4:
Intent newActivity4 = new Intent(FP_WL1_ListView.this,FitnessPrograms_Wlone_Lunges.class);
startActivity(newActivity4);
break;
}
}
});
} }

How to get more than two values in android listview selection

I want to open an activity depends on the value user select on a ListView. If user select a list item that have type1 value it should open acitvity1 (activity1.class), if the list item belongs to type2 it should open acitvity2 (activity2.class). I still wants to get the id value.
Can some one please help me to get more than one values in a list. (not just the id value) or a work around for this.
following is my code;
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
//TODO:need to assign the value here
String mEdit = .......;
if (mEdit.equals("type1")){
Intent i = new Intent(this, activity1.class);
i.putExtra(DbAdapter.KEY_ROWID, id );
startActivityForResult(i, ACTIVITY_EDIT);
}else if (mEdit.equals("type2")){
Intent i = new Intent(this, activity2.class);
i.putExtra(KEY_ROWIDA, id );
startActivityForResult(i, ACTIVITY_EDIT);
};
}
Thanks in advance
You can call getListView().getItemAtPosition(int) on your ListActivity and give it the index of the list item. You can then cast it to whatever the backing object is and perform any operations on that Object. Example from one of my own apps:
ForumDescriptor selected = (ForumDescriptor) getListView().getItemAtPosition(position);
ForumDescriptor has some information about an individual subforum (it's a forums viewer for a website). Each one is an item in my list.
This could work on the situation,
...
//TODO:need to assign the value here
TextView tv = (TextView)v.findViewById(R.id.itemname);
String category = tv.getText().toString();
...
The 'R.id.itemname' is the id attribute of list item defined in layout xml.
Here is the working code;
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
//TODO:need to assign the value here
Cursor mycursor = (Cursor) getListView().getItemAtPosition(position);
//1 is the field position
String mEdit = mycursor.getString(1);
if (mEdit.equals("type1")){
Intent i = new Intent(this, activity1.class);
i.putExtra(DbAdapter.KEY_ROWID, id );
startActivityForResult(i, ACTIVITY_EDIT);
}else if (mEdit.equals("type2")){
Intent i = new Intent(this, activity2.class);
i.putExtra(KEY_ROWIDA, id );
startActivityForResult(i, ACTIVITY_EDIT);
};
}

Passing parameters between activities not working

Passing parameters works with 2 normal activities, but when I try to pass this from the gridview to another activity, the value returns null
First Activity
gridview.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
//This takes the position id of the image and change
//it to match category id
position = position + 1;
String positionId = String.valueOf(position);
System.out.println(positionId);
Toast.makeText(MenuActivity.this, "position =" + positionId + "\nid =" + id, Toast.LENGTH_SHORT).show();
Intent myIntent = new Intent(v.getContext(), MenuItemActivity.class);
myIntent.putExtra("hello", "hello");
startActivityForResult(myIntent, 0);
}
});
My secondary activity (MenuItemActivity.java)
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.menuitem);
try{
Bundle extras = getIntent().getExtras();
String category = null;
extras.getString("Category "+extras.getString("hello"));
System.out.println("Category = "+category);
} catch(Exception e){
System.out.println("Error "+e.getMessage());
}
from here it looks like a master >> detail page. if so why are you calling
startActivityForResult(myIntent, 0);
instead of a simple
startActivity(myIntent);
can you try this and tell me if this works.
getIntent().getStringExtra("hello");
In your second activity, you need to call setResult to actually pass data back to the first activity.

Categories

Resources