I have tried many methods but still not working.
almost used all methods from stackoverflow's answers. but not working.
MainActivity.java
mProductList = new ArrayList<>();
//add sample data to list
mProductList.add(new Product(1, "iPhone4", 200, "Apple1"));
mProductList.add(new Product(2, "iPhone5", 2100, "Apple2"));
mProductList.add(new Product(3, "iPhone6", 2020, "Apple3"));
mProductList.add(new Product(4, "iPhone7", 2400, "Apple4"));
mProductList.add(new Product(5, "iPhone8", 2050, "Apple5"));
mProductList.add(new Product(6, "iPhone9", 7200, "Apple6"));
//init adapter
adapter = new ProductListAdapter(getApplicationContext(), mProductList);
lvProduct.setAdapter(adapter);
lvProduct.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(getApplicationContext(), "Clicked product id =" + view.getTag(), Toast.LENGTH_SHORT).show();
Product item = (Product)lvProduct.getAdapter().getItem(position);
Log.d("abc",item.getName());
Intent launchActivity1= new Intent(MainActivity.this,Show.class);
launchActivity1.putExtra("item", item.getName());
startActivity(launchActivity1);
}
});
and Show.java
public class Show extends Activity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.show);
}
Intent launchActivity1 = getIntent();
String item = launchActivity1.getStringExtra("item"); // this is line 17
}
when i click on one item it shows item name in Log with "getName()" function.
but at the same time app crashes and show error in Show.java on line 17
please help me to solve this code.
this error is showing in Log
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.io.Serializable android.content.Intent.getSerializableExtra(java.lang.String)' on a null object reference
at com.example.sohaib.mydesign.Show.<init>(Show.java:17)
Your code is outside onCreate method!
Intent launchActivity1 = getIntent();
String item = launchActivity1.getStringExtra("item");
Put this inside onCreate. Also onCreate doesn't have override annotation.
Copy paste this instead in your Show.java
public class Show extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.show);
Intent launchActivity1 = getIntent();
String item = launchActivity1.getStringExtra("item"); // this is line 17
}
}
add it in oncreate block...
public class Show extends Activity {
protected void onCreate(Bundle savedInstanceState) {
................
................
Intent launchActivity1 = getIntent();
String item = launchActivity1.getStringExtra("item"); // this is line 17
}
}
Or it happens when you pass object instead of string. So use
launchActivity1.putExtra("item", ""+item.getName());
thanks..
and in onclick should be..
Product item = (Product)parent.getAdapter().getItem(position);
I have Solved the issue on my own. thank you all of you for your quick response... solution is...
MainActivity.java
lvProduct.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(getApplicationContext(), "Clicked product id =" + view.getTag(), Toast.LENGTH_SHORT).show();
Product item = (Product)lvProduct.getAdapter().getItem(position);
Intent launchActivity1= new Intent(MainActivity.this,Show.class);
launchActivity1.putExtra("item", item.getName());
startActivity(launchActivity1);
}
});
Show.java
public class Show extends Activity {
String passedVar = null;
private TextView passedView= null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.show);
passedVar = getIntent().getStringExtra("item");
passedView = (TextView) findViewById(R.id.pass);
passedView.setText("You= " + passedVar);
}
}
Related
I having some trouble with how to use a Button to access another activity with data from firebase. I'm just getting an error "Can't pass null for argument 'pathString' in child()". But when I try in another activity with OnItemClick on a listview item it works. Why is that?
What I'm trying to do is: I have a activity with a listview that stores and get data from firebase. What I want is, if I click on one of the items in that listview I want a new activity with buttons, and these buttons will get me to another activity with a listview that are related to the first activity (related data). So the activity with the buttons are the same activity for every listview items i click on, like just a "dummy" activity. Is this possible?
Here is the code:
lvjobbinfo works fine, but add doesn't. I want lvjobbinfo and add to do the same.
public class MainActivity extends AppCompatActivity {
EditText etinfonavn;
ListView lvjobbinfo;
TextView tvjobbnavn;
Button add;
DatabaseReference databaseJOBBINFO;
List<Main> jobbinfo;
public static final String infonavn = "infonavn";
public static final String infoid = "infoid";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
databaseJOBBINFO = FirebaseDatabase.getInstance().getReference().child("Jobbinfo");
lvjobbinfo = (ListView)findViewById(R.id.lvjobbinfo);
lvjobbinfo.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> adapterView, View view, int i, long l) {
Main main = jobbinfo.get(i);
Intent intent = new Intent(getApplicationContext(), Notater.class);
intent.putExtra(infoid, main.getInfoId());
intent.putExtra(infonavn, main.getInfonavn());
startActivity(intent);
return true;
}
});
tvjobbnavn = (TextView)findViewById(R.id.tvjobbnavn);
etinfonavn = (EditText) findViewById(R.id.etinfonavn) ;
add = (Button)findViewById(R.id.add);
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent add = new Intent(MainActivity.this, Notater.class);
startActivity(add);
}
});
Intent intent = getIntent();
jobbinfo = new ArrayList<>();
String id = intent.getStringExtra(Jobbliste.jobbId);
String navn = intent.getStringExtra(Jobbliste.jobbnavn);
tvjobbnavn.setText(navn);
databaseJOBBINFO = FirebaseDatabase.getInstance().getReference("Jobbinfo").child(id);
}
#Override
protected void onStart() {
super.onStart();
databaseJOBBINFO.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
jobbinfo.clear();
for (DataSnapshot infosnapshot : dataSnapshot.getChildren()) {
final Main main = infosnapshot.getValue(Main.class);
jobbinfo.add(main);
final listMain infolistadapter = new listMain(MainActivity.this, jobbinfo);
lvjobbinfo.setAdapter(infolistadapter);
infolistadapter.notifyDataSetChanged();
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
I have a listview which consist of items with prices. My listview also has a Delete button. I also have a textview at the bottom part of the layout which is not part of the listview and it shows the total amount. I can successfully remove the item from my listview. What I want is that when the item is removed, the total amount will also change.
Here is a part of my adapter where i must do some actions
holder.del.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
remove(getItem(position));
}
});
and here is my Activity where my textview of amount is found.
public class Cart extends MainActivity {
TextView amount_total;
ListView cartList;
CartCustomAdapter cartCustomAdapter;
String name, price;
static ArrayList<Order> cartArray = new ArrayList<Order>();
static Double total_amount = 0.00d;
static Double temp = 0.00d;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cart);
amount_total = (TextView) findViewById(R.id.total_tv);
Bundle bundle = getIntent().getExtras();
Button checkout = (Button) findViewById(R.id.check_out);
Button add_item = (Button) findViewById(R.id.add_item);
name = bundle.getString("i_name");
price = bundle.getString("i_price");
temp = Double.parseDouble(price);
total_amount = (total_amount + temp);
amount_total.setText("Php" + total_amount.toString());
add_item.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Cart.this,MainActivity.class);
startActivity(intent);
}
});
cartList = (ListView) findViewById(R.id.cart_list);
cartCustomAdapter = new CartCustomAdapter(Cart.this,R.layout.list_cart,cartArray);
cartList.setItemsCanFocus(false);
cartList.setAdapter(cartCustomAdapter);
cartArray.add(new Order(name,price,"1"));
cartCustomAdapter.notifyDataSetChanged();
}
}
Define an interface with method like below to update text view in your activity :
updateDeletedItemCount();
and in this method take integer and increase its count like
deletedCount++;
and then update it on text view like this
tvDeletedCount.setText("Deleted Item Count : "+ deletedCount);
This is the easiest way to do that:
//Add a method to your Cart
public void changeTotal(int totalPrice){
if(textView != null) // set total price
}
// Call after remove an item in your listener:
if(getContext() instanceOf Cart){
((Cart)getContext()).changeTotal(newTotalPrice);
}
This is not the best way, but I think it's ok for now :)
I have a Mainactivity that contains the list of Trainings. And on each list is clicked it starts the session of the same training in whole application.
I managed to use Singleton and access that into my main activity. But onItemClick it takes to dialog box and on button click inside dialog it should take to another activity. Now I a getting error like java NullPointerException. Here is the code below;
Remember: I want same training session in second activity also.
MainActivity class;
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
currentTraining = (Training)arg0.getAdapter().getItem(arg2);
Log.i("DEBUG", currentTraining.getTitle());
CurrentTraining.getInstance().setTraining(currentTraining);
Toast.makeText(
getApplicationContext(),
"You clicked on position : " + arg2 + " and ID : "
+ currentTraining.getId(), Toast.LENGTH_LONG).show();
dialog = new Dialog(MainActivity.this);
dialog.setContentView(R.layout.dialog);
dialog.setTitle(currentTraining.getTitle());
TextView description = (TextView) dialog.findViewById(R.id.textView1);
description.setText("Description: " + currentTraining.getDescription());
TextView location = (TextView) dialog.findViewById(R.id.textView2);
location.setText("Location: " + currentTraining.getLocation());
TextView date = (TextView) dialog.findViewById(R.id.textView3);
date.setText("Date: " + currentTraining.getDate());
Button back_btn = (Button) dialog.findViewById(R.id.button1);
back_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
dialog.dismiss();
}
});
Button start_btn = (Button) dialog.findViewById(R.id.button2);
start_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent intent = new Intent(MainActivity.this,
TraineeActivity.class);
//intent.putExtra("trainingId", currentTraining.getId());
//intent.putExtra("title", currentTraining.getTitle().toString());
MainActivity.this.startActivity(intent);
}
});
dialog.show();
}
And in second Activity Class;
Training currentTraining;
private ListView personNamesListView;
// Adapter to made the connection between ListView UI component and SQLite data set.
private ListAdapter traineeListAdapter;
private TextView TitleView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.trainees);
currentTraining = CurrentTraining.getInstance().setTraining(currentTraining);
Log.i("DEBUG", ""+currentTraining.getTitle());
TitleView = (TextView)findViewById(R.id.training_title);
TitleView.setText(currentTraining.getTitle());
Button addnew = (Button) findViewById(R.id.add_btn);
addnew.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
Intent intent = new Intent(TraineeActivity.this,
FormActivity.class);
TraineeActivity.this.startActivity(intent);
}
});
personNamesListView = (ListView) findViewById(R.id.traineeslist);
// Create a list that contains only full name of the trainee
traineeListAdapter = new ArrayAdapter<Trainee>(this,
android.R.layout.simple_list_item_1, currentTraining.getTraineeArrayList());
personNamesListView.setAdapter(traineeListAdapter);
}
protected void onResume(){
super.onResume();
traineeListAdapter = new ArrayAdapter<Trainee>(this, android.R.layout.simple_list_item_1, currentTraining.getTraineeArrayList());
personNamesListView.setAdapter(traineeListAdapter);
}
My Singleton Class:
public class CurrentTraining {
private Training training ; //Training is my model class
private static CurrentTraining instance;
private CurrentTraining() {
}
public static CurrentTraining getInstance() {
if (instance == null)
instance = new CurrentTraining();
return instance;
}
public Training getTraining() {
return training;
}
public Training setTraining(Training training) {
return this.training = training;
}
}
In onCreate() of your second activity, you do this:
currentTraining = CurrentTraining.getInstance().setTraining(currentTraining);
Since currentTraining is null, this will just set the singleton variable training to null and return null.
Where are you actually setting the value of the one that the user picked?
I am trying to pass a value on my ListView to my second activity using Intents. I am not sure how to pass the text value to the second activity my Intent leads to. Right now my Intent is able to connect to the second activity on tap but it doesn't pass the string of the tapped value.
I feel that I need to pass something into my launchEditItem() but I am not sure what. These are the two functions I am dealing with right now.
private void launchEditItem() {
Intent i = new Intent(this, EditItemActivity.class);
i.putExtra("itemOnList", ); // list item into edit text
startActivity(i);
}
private void setupEditItemListener() { // on click, run this function to display edit page
lvItems.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> adapter, View item, int pos, long id) {
launchEditItem();
}
});
}
I'm not sure what value to place into the i.putExtra(), but I think I need to pass an argument into the launchEditItem().
This is what is currently in my second Activity:
public class EditItemActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit_item);
Intent i = getIntent();
String ItemToEdit = i.getStringExtra("itemOnList");
// place into EditText using ItemToEdit
}
I'm also not sure how to place this String value (ItemToEdit) into an EditText box. I'm new to android dev so I'm learning as much as I can thank you!
* EDIT *
I guess I'm a bit too vague in my question. Here is the entire code of the small app I am working on
public class ToDoActivity extends Activity {
private ArrayList<String> todoItems;
private ArrayAdapter<String> todoAdapter; // declare array adapter which will translate the piece of data to teh view
private ListView lvItems; // attach to list view
private EditText etNewItem;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_to_do);
etNewItem = (EditText) findViewById(R.id.etNewItem);
lvItems = (ListView) findViewById(R.id.lvItems); // now we have access to ListView
//populateArrayItems(); // call function
readItems(); // read items from file
todoAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, todoItems); //create adapter
lvItems.setAdapter(todoAdapter); // populate listview using the adapter
//todoAdapter.add("item 4");
setupListViewListener();
setupEditItemListener();
}
private void launchEditItem() {
Intent i = new Intent(this, EditItemActivity.class);
i.putExtra("itemOnList", ); // list item into edit text
startActivity(i);
}
private void setupEditItemListener() { // on click, run this function to display edit page
lvItems.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> adapter, View item, int pos, long id) {
launchEditItem();
}
});
}
private void setupListViewListener() {
lvItems.setOnItemLongClickListener(new OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> adapter, View item, int pos, long id) {
todoItems.remove(pos);
todoAdapter.notifyDataSetChanged(); // has adapter look back at the array list and refresh it's data and repopulate the view
writeItems();
return true;
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.to_do, menu);
return true;
}
public void onAddedItem(View v) {
String itemText = etNewItem.getText().toString();
todoAdapter.add(itemText); // add to adapter
etNewItem.setText(""); //clear edit text
writeItems(); //each time to add item, you want to write to file to memorize
}
private void readItems() {
File filesDir = getFilesDir(); //return path where files can be created for android
File todoFile = new File(filesDir, "todo.txt");
try {
todoItems = new ArrayList<String>(FileUtils.readLines(todoFile)); //populate with read
}catch (IOException e) { // if files doesn't exist
todoItems = new ArrayList<String>();
}
}
private void writeItems() {
File filesDir = getFilesDir(); //return path where files can be created for android
File todoFile = new File(filesDir, "todo.txt");
try {
FileUtils.writeLines(todoFile, todoItems); // pass todoItems to todoFile
} catch (IOException e) {
e.printStackTrace();
}
}
}
String[] link_list;
int currenttrack=0;
link_list=new String[]{
"W-TE_Ys4iwM",//1
"oozgmH3ZP14",//2
"o_v9MY_FMcw",//3
"36mCEZzzQ3o",//4
}
First activity
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
currenttrack=arg2;
Intent videoIntent=new Intent(MainActivity.this,VideoView.class);
videoIntent.putExtra("filename", link_list[currenttrack]);
startActivity(videoIntent);
}
});
In your Second Activity
// getting intent data
// get intent data
Intent i = getIntent();
Bundle extras = i.getExtras();
filename = extras.getString("filename");
Log.e("File Name", filename);
and your done :)
In your current Activity, create a new Intent:
Intent i = new Intent(getApplicationContext(), NewActivity.class);
i.putExtra("new_variable_name","value");
startActivity(i);
Then in the new Activity, retrieve those values:
Bundle extras = getIntent().getExtras();
if (extras != null) {
String value = extras.getString("new_variable_name");
}
I am not sure if i understood where is the value. Well if the value is in EditText do something like:
private void launchEditItem(String text) {
Intent i = new Intent(this, EditItemActivity.class);
i.putExtra("itemOnList", text); // list item into edit text
startActivity(i);
}
private void setupEditItemListener() { // on click, run this function to display edit page
lvItems.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> adapter, View item, int pos, long id) {
EditText editView = (EditText) item.findById(R.id.ItemToEdit);
String text = editView != null ? editView.getText().toString() : "";
launchEditItem(text);
}
});
}
1 - I have some doubt with:
i.putExtra("itemOnList", );
You'd better pass a value:
i.putExtra("itemOnList", "something");
2 - To valorize a control, you must obtain a reference to it first. Something like:
EditText edt =
(EditText) findViewById(R.id.activity_edit_item_my_EditText); // or whatever id you assigned to it (it MUST HAVE AN ID)
Do it AFTER setContentView().
Then you can set it's text like:
edt.setText(ItemToEdit); // Now it should contain "something"
Just as simple as that
[EDIT]
If you aren't sure what to pass so is to pass in the "tapped" value in the ListView into the putExtra, modify your listview click handler code:
list.setOnItemClickListener
(
new OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3)
{
// TODO Auto-generated method stub
Intent videoIntent = new Intent(MainActivity.this, VideoView.class);
videoIntent.putExtra("filename", (((TextView) v).getText().toString());
startActivity(videoIntent);
}
}
);
It should work immediately.
01: Current Activity
String pass_value ="value";
Intent intent = new Intent(getApplicationContext(),NewActivity.class);
intent.putExtra("var_name",pass_value);
startActivity(intent);
02: New Activity
String value = getIntent().getExtras().getString("var_name");
I have implemented a ListView that starts a new Activity when a list item is clicked. When I test it manually, it works perfectly. But when I try to do an automated test with ActivityUnitTestCase, I get a NullPointerException as though the ListView was empty.
MainActivity (partial):
public class MainActivity extends ListActivity {
#Override
protected void onResume() {
super.onResume();
String[] items = new String[] {"item 1", "item 2"};
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, items);
setListAdapter(adapter);
getListView().setOnItemClickListener(new OnItemClickListener () {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
TextView clickedItem = (TextView) view;
CharSequence clickedItemText = clickedItem.getText(); // throws a NullPointerException when running testWithPerformItemClick()!
Intent intent = new Intent(MainActivity.this, ItemDisplayActivity.class);
intent.putExtra("parameter", clickedItemText);
startActivity(intent);
}
});
}
}
The test code that fails:
public class MainActivityTest extends ActivityUnitTestCase<MainActivity> {
ListView listView;
View child0;
public MainActivityTest() {
super(MainActivity.class);
}
private void setUpTest() {
MainActivity activity = startActivity(new Intent(), null, null);
getInstrumentation().callActivityOnStart(activity);
getInstrumentation().callActivityOnResume(activity);
listView = (ListView) activity.findViewById(android.R.id.list);
child0 = listView.getChildAt(0); // returns null!
}
public void testWithPerformClick() {
setUpTest();
child0.performClick(); // throws a NullPointerException!
Intent startedIntent = getStartedActivityIntent();
assertEquals("item 1", startedIntent.getStringExtra("parameter"));
}
public void testWithPerformItemClick() {
setUpTest();
long itemId = listView.getAdapter().getItemId(0);
listView.performItemClick(child0, 0, itemId); // throws a NullPointerException!
Intent startedIntent = getStartedActivityIntent();
assertEquals("item 1", startedIntent.getStringExtra("parameter"));
}
Both test methods fail because listView.getChildAt(0) returns null. Why is the ListView empty? How can I force it to update itself with the right children?
According to the documentation, If you prefer a functional test you should use ActivityInstrumentationTestCase2. To perform a click it works better. The #fewe answer is right, you have to wait the list to be drawn, to wait the fragment to be loaded you can use getInstrumentation().waitForIdleSync();
Try something like this.
public class ActivityTests extends
ActivityInstrumentationTestCase2<Activity>
final ListView list = (ListView) mActivity.findViewById(R.id.listId);
assertNotNull("The list was not loaded", list);
getInstrumentation().runOnMainSync(new Runnable() {
#Override
public void run() {
list.performItemClick(list.getAdapter().getView(position, null, null),
position, list.getAdapter().getItemId(position));
}
});
getInstrumentation().waitForIdleSync();
Then you cant test, for example, if a fragment was loaded.
mFragment frag = mActivity.getFragment();
assertNotNull("Fragment was not loaded", frag);
This is because the listview isn't drawn yet. You should wait for it to be drawn before trying to access its cells