I'm building my first app but I'm having troubles with 1 piece of the code.
When a value is added (in this case a recipe) it saving the name and the the recipe itself.
The name is listed in a listview which is working.
But when I click the value I want to show/edit/delete, it also shows the name in the recipe field.
Can somebody help me / point me in the right direction?
The code is still messy:
My Recipe Listview
public class Recipes extends AppCompatActivity {
private static final String TAG = "Recipes";
DatabaseRecipes mDatabaseRecipes;
ArrayList<RecipeHelper> recipeList;
ListView mListView;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_recipes);
recipeList = new ArrayList<>();
mListView = (ListView) findViewById(R.id.listView);
mDatabaseRecipes = new DatabaseRecipes(this);
Cursor data = mDatabaseRecipes.getData();
populateListView();
Button button_add = (Button) findViewById(R.id.button_add);
button_add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.d(TAG, "onClick: Continue to adding Recipes");
toastMessage("Continue to adding Recipes");
Intent intent = new Intent(Recipes.this, AddRecipe.class);
startActivity(intent);
}
});
}
private void populateListView() {
Log.d(TAG, "populateListView: Displaying data in the ListView.");
//get the data and append to a list
Cursor data = mDatabaseRecipes.getData();
ArrayList<String> listData = new ArrayList<>();
while(data.moveToNext()){
//get the value from the database in column 1
//then add it to the ArrayList
listData.add(data.getString(1));
}
//create the list adapter and set the adapter
ListAdapter adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, listData);
mListView.setAdapter(adapter);
//set an onItemClickListener to the ListView
mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
String name = adapterView.getItemAtPosition(i).toString();
String recipe = adapterView.getItemAtPosition(i).toString();
Log.d(TAG, "onItemClick: You Clicked on " + name);
Cursor data = mDatabaseRecipes.getData(); //get the id associated with that name
int itemID = -1;
while(data.moveToNext()){
itemID = data.getInt(0);
}
if(itemID > -1){
Log.d(TAG, "onItemClick: The ID is: " + itemID);
Intent editScreenIntent = new Intent(Recipes.this, EditRecipe.class);
editScreenIntent.putExtra("id",itemID);
editScreenIntent.putExtra("name",name);
editScreenIntent.putExtra("recipe",recipe);
startActivity(editScreenIntent);
}
else{
toastMessage("No ID associated with that ingredient");
}
}
});
}
/**
* customizable toast
* #param message
*/
private void toastMessage(String message){
Toast.makeText(this,message, Toast.LENGTH_SHORT).show();
}
}
My edit recipe:
public class EditRecipe extends AppCompatActivity {
private static final String TAG = "EditRecipe";
private Button button_edit,button_delete,button_back;
public EditText editRecipe, editRecipeName;
DatabaseRecipes mDatabaseRecipe;
private String selectedName, selectedRecipe;
private int selectedID;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit_recipe);
button_edit = (Button) findViewById(R.id.button_edit);
button_delete = (Button) findViewById(R.id.button_delete);
button_back = (Button) findViewById(R.id.button_back);
editRecipeName = (EditText) findViewById(R.id.editRecipeName);
editRecipe = (EditText) findViewById(R.id.editRecipe);
mDatabaseRecipe = new DatabaseRecipes(this);
//get the intent extra from the ListDataActivity
Intent receivedIntent = getIntent();
//now get the itemID we passed as an extra
selectedID = receivedIntent.getIntExtra("id",-1); //NOTE: -1 is just the default value
//now get the name we passed as an extra
selectedName = receivedIntent.getStringExtra("name");
//now get the name we passed as an extra
selectedRecipe = receivedIntent.getStringExtra("recipe");
//set the text to show the current selected name
editRecipeName.setText(selectedName);
//set the text to show the current selected name
editRecipe.setText(selectedRecipe);
button_edit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String item = editRecipeName.getText().toString();
String item2 = editRecipe.getText().toString();
if(!item.equals("") && !item2.equals("")){
mDatabaseRecipe.updateName(item,selectedID,selectedName);
mDatabaseRecipe.updateRecipe(item2,selectedID,selectedRecipe);
Intent int1 = new Intent(EditRecipe.this, Recipes.class);
startActivity(int1);
}else{
toastMessage("You must enter a name");
}
}
});
button_delete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mDatabaseRecipe.deleteName(selectedID,selectedName);
editRecipeName.setText("");
toastMessage("removed from database");
Intent int1 = new Intent(EditRecipe.this, Recipes.class);
startActivity(int1);
}
});
button_back.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent int1 = new Intent(EditRecipe.this, Recipes.class);
startActivity(int1);
}
});
}
/**
* customizable toast
* #param message
*/
private void toastMessage(String message){
Toast.makeText(this,message, Toast.LENGTH_SHORT).show();
}
}
My editrecipe.xml
<TextView
android:id="#+id/textView2"
android:layout_width="0dp"
android:layout_height="0dp"
android:background="#drawable/background"
android:textAllCaps="false"
android:textSize="36sp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="1.0" />
<EditText
android:id="#+id/editIngredient"
android:layout_width="wrap_content"
android:layout_height="43dp"
android:layout_marginBottom="284dp"
android:layout_marginEnd="68dp"
android:layout_marginRight="68dp"
android:layout_marginTop="256dp"
android:background="#color/black_overlay"
android:ems="10"
android:inputType="text|textPersonName"
android:text="#string/ingredient"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.96"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/button-recipes" />
<Button
android:id="#+id/button_edit"
android:layout_width="182dp"
android:layout_height="92dp"
android:layout_marginBottom="192dp"
android:background="#android:drawable/alert_dark_frame"
android:text="#string/edit_the_ingredient"
android:textColor="#ffffff"
android:textSize="18sp"
android:visibility="visible"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent" />
<Button
android:id="#+id/button_delete"
android:layout_width="182dp"
android:layout_height="92dp"
android:layout_marginBottom="192dp"
android:background="#android:drawable/alert_dark_frame"
android:text="#string/delete_the_ingredient"
android:textColor="#ffffff"
android:textSize="18sp"
android:visibility="visible"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="1.0"
app:layout_constraintStart_toStartOf="parent" />
<Button
android:id="#+id/button_back"
android:layout_width="182dp"
android:layout_height="92dp"
android:background="#android:drawable/alert_dark_frame"
android:text="#string/Back"
android:textColor="#ffffff"
android:textSize="18sp"
android:visibility="visible"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent" />
</android.support.constraint.ConstraintLayout>
In your onItemCLickListener, you are doing:
String name = adapterView.getItemAtPosition(i).toString();
String recipe = adapterView.getItemAtPosition(i).toString();
Exact same function for the two variables, so likely you are getting twice the same information
I don't know how your Recipe class looks, but maybe you want something more like
String name = recipesList.get(i).getName();
String recipe = recipesList.get(i).getRecipe();
Edit:
After reading more carefully I realize you are not creating your listview using the recipesList but the listData list. You are populating it with the results of your cursor but only the fist column each time, so I assume it's always the name. You are not storing your recipe anywhere, you will have to if you want to be able to retrieve it when clicking on an item.
Assuming your Recipe class contains name and recipe, and your database has one column for name and one for recipe, you can do something like this:
Cursor data = mDatabaseRecipes.getData();
ArrayList<String> listData = new ArrayList<>();
while(data.moveToNext()){
//get the value from the database in column 1
//then add it to the ArrayList
listData.add(data.getString(1));
recipesList.add(new Recipe(data.get(NAME_COLUMN), data.get(RECIPE_COLUMN));
}
Then it should work without making too much changes to your code. But ideally you should use only one list if possible.
Related
Main_activity.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="16dp"
android:paddingLeft="16dp"
android:paddingRight="16dp"
android:paddingTop="16dp"
android:id="#+id/activity_main"
tools:context="com.example.syafiq.mychatapp.MainActivity">
<android.support.design.widget.FloatingActionButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:clickable="true"
android:src="#drawable/ic_send"
android:id="#+id/fab"
android:tint="#android:color/white"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
app:fabSize="mini"
/>
<android.support.design.widget.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_toLeftOf="#+id/fab"
android:layout_alignParentBottom="true"
android:layout_alignParentEnd="true"
>
<EditText
android:id="#+id/messageinput"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/fab"
android:layout_centerHorizontal="true"
android:hint="Message..." />
</android.support.design.widget.TextInputLayout>
<ListView
android:id="#+id/list_of_message"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true"
android:layout_above="#+id/fab"
android:dividerHeight="16dp"
android:divider="#android:color/transparent"
android:layout_marginBottom="16dp"
android:layout_width="match_parent"
android:layout_height="match_parent">
</ListView>
Maincode
private static int SIGN_IN_REQUEST_CODE =1;
//private List<ChatMessage> list = new ArrayList<ChatMessage>();
FirebaseListAdapter<ChatMessage> adapter;
RelativeLayout activity_main;
FloatingActionButton fab;
FirebaseDatabase db = FirebaseDatabase.getInstance();
DatabaseReference myRef = db.getReference("message");
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
if (item.getItemId() == R.id.menu_signout)
{
AuthUI
.getInstance()
.signOut(this)
.addOnCompleteListener(
new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task)
{
Snackbar
.make(
activity_main,
"You have been signed out.",
Snackbar.LENGTH_SHORT
).show()
;
finish();
}
}
)
;
}
return true;
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
if (resultCode==SIGN_IN_REQUEST_CODE)
{
if (resultCode==RESULT_OK)
{
Snackbar
.make(
activity_main,
"Successfully signed in!",
Snackbar.LENGTH_SHORT
).show()
;
displayChatMessage();
}
else
{
Snackbar
.make(
activity_main,
"We couldn't sign you in. Please try again lter!",
Snackbar.LENGTH_SHORT
).show()
;
finish();
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
getMenuInflater().inflate(R.menu.main_menu,menu);
return true;
}
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
activity_main = (RelativeLayout) findViewById(R.id.activity_main);
fab = (FloatingActionButton) findViewById(R.id.fab);
fab
.setOnClickListener(
new View.OnClickListener()
{
#Override
public void onClick(View v)
{
EditText input = (EditText) findViewById(R.id.messageinput);
FirebaseDatabase
.getInstance()
.getReference()
.push()
.setValue(
new ChatMessage(
input.getText().toString(),
FirebaseAuth.getInstance().getCurrentUser().getEmail()
)
)
;
input.setText("");
displayChatMessage();
}
}
)
;
if (FirebaseAuth.getInstance().getCurrentUser()== null)
{
startActivityForResult(
AuthUI
.getInstance()
.createSignInIntentBuilder()
.build(),
SIGN_IN_REQUEST_CODE
);
}
else
{
Snackbar
.make(
activity_main,
"Welcome " + FirebaseAuth
.getInstance()
.getCurrentUser()
.getEmail(),
Snackbar.LENGTH_SHORT
).show()
;
//displayChatMessage();
}
}
DisplaychatMessage() function to display my chat message
private void displayChatMessage() {
Query query = FirebaseDatabase.getInstance().getReference().child("Chats");
ListView listofmsgs = (ListView) findViewById(R.id.list_of_message);
FirebaseListOptions<ChatMessage> options = new FirebaseListOptions
.Builder<ChatMessage>()
.setQuery(query, ChatMessage.class)
.setLayout(R.layout.list_item)
.build()
;
//adapter.startListening();
Log.d("ErrorCheck", "1");
adapter = new FirebaseListAdapter<ChatMessage>(options) {
#Override protected void populateView(View v, ChatMessage model, int position) {
//ChatMessage cm = (ChatMessage) model;
TextView messageText, messageUser, messageTime;
messageText = (TextView) v.findViewById(R.id.messageinput);
messageUser = (TextView) v.findViewById(R.id.message_user);
messageTime = (TextView) v.findViewById(R.id.message_time);
messageText.setText(model.getMessageText().toString());
messageUser.setText(model.getMessageUser());
messageTime
.setText(
android.text.format.DateFormat.format(
"dd-mm-yyyy (HH:mm:ss)",
model.getMessageTime()
)
)
;
Log.d("ErrorCheck", "2");
}
};
listofmsgs.setAdapter(adapter);
adapter.startListening();
}
Hi guys, i did this but it doesn't seem like anything appear on my APP. But the then, when i press send, in my database, my chat appears there but again it doesn't appear on my Chat app. I did a debug log. Errorcheck 1, and 2 to see where the code ends. When i checked, looks like the debug log only display up till ErrorCheck 1 and does not display display 2. How do i solve this?
You've put ErrorCheck 2 in something called an anonymous class. That's why calling your displayChatMessage() will only log ErrorCheck 1. The code in the anonymous FirebaseListAdapter class you defined will only run when it's populateView() method is called. You don't call that method. You call adapter.startListening(); Something, somewhere, needs to call adapter.populateView() before you'll see ErrorCheck 2 logged.
You likely don't want to call it here. You can call it here just for a test but you should track down what is supposed to be calling it.
According to the docs about FirebaseListAdapter
This class is a generic way of backing an Android ListView with a Firebase location. It handles all of the child events at the given Firebase location. It marshals received data into the given class type. Extend this class and provide an implementation of populateView, which will be given an instance of your list item mLayout and an instance your class that holds your data. Simply populate the view however you like and this class will handle updating the list as the data changes.
So trying changing the data and see if that makes you log ErrorCheck 2
I have the following piece of codes.I am calling a second activity from main activity.Whenever the send button is pressed i want a toast to show button is pressed and start the activity.But due to some context problems only toast is appearing.Please correct the context for intent and give some clear explaination about these contexts.
MainActivity.java
public class MainActivity extends AppCompatActivity {
public final static String EXTRA_MESSAGE="com.example.iamka.androiddevelop.MESSAGE";
public void Toast1(String s){
Toast.makeText(this,s+" is called",Toast.LENGTH_SHORT).show();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d("My app","onCreate is called");
Toast1("onCreate");
Button btn=(Button)findViewById(R.id.button);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d("My app","Button is pressed");
Toast.makeText(MainActivity.this,"Button pressed",Toast.LENGTH_SHORT).show();
}
});
}
public void sendMessage(View view) {
// Do something in response to button
Intent intent = new Intent(MainActivity.this, DisplayMessageActivity.class);
EditText editText = (EditText) findViewById(R.id.editText);
String message = editText.getText().toString();
intent.putExtra(EXTRA_MESSAGE, message);
Log.i("intent","intent is started");
startActivity(intent);
}
}
DisplayMessageActivity.java
public class DisplayMessageActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_message);
// Get the Intent that started this activity and extract the string
Intent intent = getIntent();
String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);
// Capture the layout's TextView and set the string as its text
TextView textView =(TextView) findViewById(R.id.textView);
Log.i("intent","displaymessage");
textView.setText(message);
}
}
activity_main.xml
<EditText
android:id="#+id/editText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:ems="10"
android:hint="#string/edit_message"
android:inputType="textPersonName"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintRight_toLeftOf="#+id/button"
app:layout_constraintHorizontal_chainStyle="spread" />
<Button
android:id="#+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="16dp"
android:onClick="sendMessage"
android:text="#string/button_send"
app:layout_constraintBaseline_toBaselineOf="#+id/editText"
app:layout_constraintLeft_toRightOf="#+id/editText"
app:layout_constraintRight_toRightOf="parent" />
activity_display_message.xml
<TextView
android:id="#+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:text="TextView"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
When i remove the onClickListener() method then the intent is working.
Since you are setting your own View.OnClickListener, you are removing the one from the XML definition. Button only support one View.OnClickListener. First, the XML will create one from the android:onclick attribute like :
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
sendMessage(v);
}
});
Then you are setting yours with the Toast. The button will only keep the last one, so the Intent is never send.
Solutions :
call the sendMessage method in your listener
Like:
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d("My app","Button is pressed");
Toast.makeText(MainActivity.this,"Button pressed",Toast.LENGTH_SHORT).show();
sendMessage(v); //Or anywhere in that method, your call.
}
});
remove the listener to keep the one create by the android:onclick.
FYI:
Usually, a set### methods means this is not supporting multiple values, add### methods do.
Also, you can check at android- multi onClick listener in one button to implement your own multi listener button if you like. But I didn't check if there were some more up to date...
Just remove android:onClick="sendMessage" for button and try. Either you have to set click listener in xml or in class file. Both it won't work
<Button
android:id="#+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="16dp"
android:text="#string/button_send"
app:layout_constraintBaseline_toBaselineOf="#+id/editText"
app:layout_constraintLeft_toRightOf="#+id/editText"
app:layout_constraintRight_toRightOf="parent" />
Change this in your Activity :
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d("My app","Button is pressed");
Toast.makeText(MainActivity.this,"Button pressed",Toast.LENGTH_SHORT).show();
sendMessage();
}
});
private void sendMessage() {
// Do something in response to button
Intent intent = new Intent(MainActivity.this, DisplayMessageActivity.class);
EditText editText = (EditText) findViewById(R.id.editText);
String message = editText.getText().toString();
intent.putExtra(EXTRA_MESSAGE, message);
Log.i("intent","intent is started");
startActivity(intent);
}
Just copy paste the following MainActivity code and it will do the work. The xmls are loaded first and then on runtime you are setting the onclick listener to the button again. so the xmls onclick has been replaced by your onclick listener in java code. Hence you get toast but the sendMessage() is never called
public class MainActivity extends AppCompatActivity {
public final static String EXTRA_MESSAGE="com.example.iamka.androiddevelop.MESSAGE";
public void Toast1(String s){
Toast.makeText(this,s+" is called",Toast.LENGTH_SHORT).show();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d("My app","onCreate is called");
Toast1("onCreate");
Button btn=(Button)findViewById(R.id.button);
}
public void sendMessage(View view) {
// Do something in response to button
Intent intent = new Intent(MainActivity.this, DisplayMessageActivity.class);
EditText editText = (EditText) findViewById(R.id.editText);
String message = editText.getText().toString();
intent.putExtra(EXTRA_MESSAGE, message);
Log.i("intent","intent is started");
startActivity(intent);
}
}
So I wrote a custom ArrayAdapter to have a ListView populate with custom row data, and also to set the OnClickListener to each row. I'm facing two major problems here:
the specified Activity (InvoiceActivity) does not start up on click.
The reaction time on clicks when I only output the logmessage (and comment the intent and startActivity part) is really slow.
For now there are only 3 rows of dummy data in the ListView.
I would be grateful for any help here, thanks!
public class InvoiceListAdapter extends ArrayAdapter<InvoiceShort> {
public InvoiceListAdapter(Context context, ArrayList<InvoiceShort> invoices) {
super(context, R.layout.list_elem, invoices);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final InvoiceShort invoice = getItem(position);
if (convertView == null) {
convertView = LayoutInflater.from(getContext()).inflate(R.layout.list_elem, parent, false);
convertView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(final View parent) {
Log.d("item click", "invoice id: " + invoice.getId());
Intent intent = new Intent(getContext(), InvoiceActivity.class);
intent.putExtra("id", invoice.getId());
getContext().startActivity(intent);
}
});
}
// Lookup view for data population
TextView date = (TextView) convertView.findViewById(R.id.textDate);
TextView total = (TextView) convertView.findViewById(R.id.textTotal);
CheckBox paid = (CheckBox) convertView.findViewById(R.id.checkBoxPaid);
// populate data
DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
date.setText(formatter.format(invoice.getDate()));
total.setText("€ " + new Long(invoice.getTotal()).toString());
paid.setChecked(invoice.isPaid());
return convertView;
}
}
EDIT: Here is the xml for one row
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="50dp"
android:layout_centerHorizontal="false"
android:orientation="horizontal">
<CheckBox
android:id="#+id/checkBoxPaid"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:checked="true"
android:elevation="0dp"
android:inputType="none" />
<EditText
android:id="#+id/textDate"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="5"
android:background="#null"
android:ems="10"
android:focusable="false"
android:inputType="none"
android:text="2017-12-30" />
<EditText
android:id="#+id/textTotal"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="2"
android:background="#null"
android:ems="10"
android:focusable="false"
android:inputType="none"
android:text="10€"
android:textAlignment="viewStart" />
</LinearLayout>
I have found the solution, problem here is you have edittext in your xml but your fetching it as Textview, you can change textview to edittext in list_elem layout your click listener will work . Otherwise you can change textview to edittext in your customAdapter and set two click listener for edittext as below to make it work
date.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
View parent = (View) v.getParent();
parent.performClick();
}
});
total.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
View parent = (View) v.getParent();
parent.performClick();
}
});
Start activity using view context
Intent intent = new Intent(convertView.getContext(), InvoiceActivity.class);
intent.putExtra("id", invoice.getId());
convertView.getContext().startActivity(intent);
Implement OnClickListener in your Activity class in which you are setting the Adapter and showing the ListView.
Try to modify your constructor like this:-
Context mContext;
public InvoiceListAdapter(Context context, ArrayList<InvoiceShort>
invoices) {
super(context, R.layout.list_elem, invoices);
mContext = context;
}
and use mContext instead of getContext();
this part:-
#Override
public void onClick(View parent) {
Log.d("item click", "invoice id: " + invoice.getId());
Intent intent = new Intent(getContext(), InvoiceActivity.class);
intent.putExtra("id", invoice.getId());
getContext().startActivity(intent);
}
try by writing the onclick listner outside the
if else
convertView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View parent) {
Log.d("item click", "invoice id: " + invoice.getId());
Intent intent = new Intent(getContext(), InvoiceActivity.class);
intent.putExtra("id", invoice.getId());
getContext().startActivity(intent);
}
});`
So I finally found the solution, in short it is setting this listener to all the views inside one row of the ListView:
/** A definition of a listener that does nothing but to let the click be handled by the parent **/
View.OnClickListener listener = new View.OnClickListener() {
#Override
public void onClick(View v) {
((ListView) parent).performItemClick(v, position, 0);
}
};
date.setOnClickListener(listener);
total.setOnClickListener(listener);
paid.setOnClickListener(listener);
And also to implement the OnItemClickedListener for the ListView inside the MainActivity
I made an android app in which the user click the favorite menu item button and the page name saves in the favorite.class activity. But when I click on any item in the favorite list it opens only one specific class and not others which I want. Here is my code please look at the code and tell me what should I do to make it first in ListView form and then to click the item which opens the correct activity from it.
favorite.xml layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
android:layout_marginLeft="17dp">
<TextView
android:id="#+id/empty_textview"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/no_bookmark"
android:textSize="16sp"
android:textColor="#000000"
android:
android:textStyle="bold"/>
<TextView
android:id="#+id/bookmark_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="10dp"
android:textSize="16sp"
android:textColor="#000000"
android:textStyle="bold"/>
<!-- ScrollView is needed when adding views, or only the last view will show up -->
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent" >
<LinearLayout
android:id="#+id/bookmark_insert_point"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
</LinearLayout>
</ScrollView>
</LinearLayout>
Favorite.Class activity:
public class Favorite extends Activity {
private TextView mEmptyText;
private LinearLayout mBookmarkLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.favorite);
// this code is used for the action bar color change//
ActionBar bar = getActionBar();
bar.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#6B8E23")));
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);
mEmptyText = (TextView) findViewById(R.id.empty_textview);
mBookmarkLayout = (LinearLayout) findViewById(R.id.bookmark_insert_point);
getAllKeys();
}
private void getAllKeys()
{
SharedPreferences sp = this.getSharedPreferences("bookmarks", MODE_PRIVATE);
Map<String,?> keys = sp.getAll();
int count = 0;
for(Map.Entry<String,?> entry : keys.entrySet())
{
String value = entry.getValue().toString();
System.out.println("!!!!!!!!!!!!!!!!!value = "+value);
String delimiter = ",";
String[] values_array = value.split(delimiter);
addBookmark(values_array);
count++; //keep track of the number of bookmarks
}
//if there are no bookmarks, display a text view saying so. Otherwise, make the text view go away
if (count == 0)
{
mEmptyText.setVisibility(View.VISIBLE);
mEmptyText.setText(getString(R.string.no_bookmark));
}
else
mEmptyText.setVisibility(View.GONE);
}
#SuppressWarnings("deprecation")
private void addBookmark(final String[] values_array)
{
LayoutInflater vi = (LayoutInflater) getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View v = vi.inflate(R.layout.favorite, null);
final TextView text = (TextView) v.findViewById(R.id.bookmark_text);
text.setText(values_array[1]);
// insert into main view
mBookmarkLayout.addView(v, 0, new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.FILL_PARENT));
System.out.println("!!!!!!!!!!!!!!!!!!!!Just added a view");
text.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(text.equals("Atherosclerosis"));
Intent i=new Intent(Favorite.this,Atherosclerosis.class);
startActivity(i);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.favorite, menu);
return true;
}
}
and finally the activity from where user click for add to favorite:
public boolean onOptionsItemSelected(MenuItem item) {
// Take appropriate action for each action item click
switch (item.getItemId()) {
case R.id.id_search:
Intent newActivity0 = new Intent(this,Search.class);
startActivity(newActivity0);
return true;
case R.id.id_favorit:
SharedPreferences sp = this.getSharedPreferences("bookmarks", MODE_PRIVATE);
Editor editor = sp.edit();
editor.putString("atherosclerosis", "com.kmcpesh.shortreviewofcardiology.Favorite,Atherosclerosis");
editor.commit();
Toast.makeText(getApplicationContext(), "Item Added to Favorite List!", Toast.LENGTH_SHORT).show();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
well i guess what you have to do is setOnItemClickListener in everyone of the list items...
an example is
private void registerCallClickBack() {
// TODO Auto-generated method stub
ListView list = (ListView)findViewById(R.id.listView1);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View viewClicked, int position,
long id) {
// TODO Auto-generated method stub
//String message = "You have chosen the " + id + "item";
//Toast.makeText(MainActivity.this, message, Toast.LENGTH_SHORT).show();
Intent intent = new Intent("package.Activity name");
startActivity(intent);
}
});
}
this will either display a toast message of every listview item clicked or start a new intent..
I have two EditText fields i.e name and marks and one Add button.
I have to display EditText values each and every time whenever Add button is clicked.
However,I am only able to display only one single value on listview.
When i clicked again on Add button,its previous value get erased and newer value gets displayed in listview.
I wanna populate whole list in listview.
public class MainActivity extends Activity {
EditText name1;
EditText marks1;
private ListView lv;
ArrayAdapter<String> aa;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_main);
TextView markshee = (TextView)findViewById(R.id.textView3);
markshee.setText("");
Button btnAdd = (Button) findViewById(R.id.button1);
btnAdd.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
try{
name1 = (EditText)findViewById(R.id.editText1);
String name = name1.getText().toString();
marks1 = (EditText)findViewById(R.id.editText2);
String marks = marks1.getText().toString();
if(name.equals("") || marks.equals("")){
String str="Don't Leave any field blank !";
Toast toast = Toast.makeText(MainActivity.this, str, Toast.LENGTH_SHORT);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
}
else {
TextView marksheet = (TextView)findViewById(R.id.textView3);
marksheet.setText("Marks Sheet");
marksheet.setTextColor(Color.BLUE);
TextView nam = (TextView)findViewById(R.id.textView4);
nam.setText("Name");
nam.setTextColor(Color.RED);
TextView mar = (TextView)findViewById(R.id.textView5);
mar.setText("Marks");
mar.setTextColor(Color.RED);
name1.setText("");
marks1.setText("");
lv = (ListView) findViewById(R.id.listView1);
lv.setItemsCanFocus(true);
ArrayList<String> data = new ArrayList<String>();
data.add(" "+name+" "+marks);
aa =
new ArrayAdapter<String>(MainActivity.this,android.R.layout.simple_list_item_1, data);
lv.setAdapter(aa);
}
}catch(Exception ex)
{
System.out.println(ex.getStackTrace());
}
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
Try this:
you declare ArrayList is public otherwise it will create each and every time clicking and sotre last items only
public class MainActivity extends Activity {
EditText name1;
EditText marks1;
private ListView lv;
ArrayAdapter<String> aa;
ArrayList<String> data = new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_main);
TextView markshee = (TextView)findViewById(R.id.textView3);
markshee.setText("");
Button btnAdd = (Button) findViewById(R.id.button1);
btnAdd.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
try{
name1 = (EditText)findViewById(R.id.editText1);
String name = name1.getText().toString();
marks1 = (EditText)findViewById(R.id.editText2);
String marks = marks1.getText().toString();
if(name.equals("") || marks.equals("")){
String str="Don't Leave any field blank !";
Toast toast = Toast.makeText(MainActivity.this, str, Toast.LENGTH_SHORT);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
}
else {
TextView marksheet = (TextView)findViewById(R.id.textView3);
marksheet.setText("Marks Sheet");
marksheet.setTextColor(Color.BLUE);
TextView nam = (TextView)findViewById(R.id.textView4);
nam.setText("Name");
nam.setTextColor(Color.RED);
TextView mar = (TextView)findViewById(R.id.textView5);
mar.setText("Marks");
mar.setTextColor(Color.RED);
name1.setText("");
marks1.setText("");
lv = (ListView) findViewById(R.id.listView1);
lv.setItemsCanFocus(true);
data.add(" "+name+" "+marks);
aa =
new ArrayAdapter<String>(MainActivity.this,android.R.layout.simple_list_item_1, data);
lv.setAdapter(aa);
}
}catch(Exception ex)
{
System.out.println(ex.getStackTrace());
}
}
});
}
Instead of creating and initializing your data inside onClick, try initializing it in the onCreate method and inside onClick just add the new entry to it:
ArrayList<String> data = new ArrayList<String>();
Button btnAdd = (Button) findViewById(R.id.button1);
btnAdd.setOnClickListener(new Button.OnClickListener(){
public void onClick(View v) {
.....
.....
.....
data.add(" "+name+" "+marks);
....
}
}
With your existing code, when your onClick method is called, you are creating a new list data every time and adding just a single entry to it, hence it displays only a single value.
UPDATE:
Lets see an example :
Lets say have a class from which I need to get incremental value on calling a method getIncrementValue that should return current value +1 every time I call it.
This is the code for it:
public class MyClass{
public int getIncrementValue(){
int a = 0;
a = a+1;
return a;
}
}
Now if I call this method like:
MyClass m = new MyClass();
System.out.println(m.getIncrementValue()); //prints 1
System.out.println(m.getIncrementValue()); //prints 1 should print 2 right
System.out.println(m.getIncrementValue()); //prints 1 should print 3 right
You see this, every time it prints only one value instead of incremented value.
This is beacuse every time I call getIncrementValue(), I am declaring and initializing a new variable a = 0 and incrementing it and returning it, hence every time it increments it to 1 and return 1 (instead of 2 and three and so on)
For this I need to change slighlty my class, declare variable a outside that method make it a class variable (in your case declare ArrayList<String> data = new ArrayList<String>(); just after the line ArrayAdapter<String> aa;)
public class MyClass{
int a = 0;
public int getIncrementValue(){
a = a+1;
return a;
}
}
Now if I call this method like:
MyClass m = new MyClass();
System.out.println(m.getIncrementValue()); //prints 1
System.out.println(m.getIncrementValue()); //prints 2 should print 2 right
System.out.println(m.getIncrementValue()); //prints 3 should print 3 right
Now you can uderstand why that happens with your code.
So try tweaking your code a little bit and it will be fine.
according to your question i have done something for you.. i have created two Edit text as name and marks and created two lists name as list and list2...and one add button... for run this code your min sdk version should be 11.. otherwise it will not work....when you enter value on edit text box and click on add button these value will be show on two different list and never erased the previous value..... follow my code...
MainActivity.java
package com.example.textview;
import java.util.ArrayList;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
public class MainActivity extends Activity {
EditText Name, Marks;
Button Add;
ListView lv, lv2;
ArrayList<String> list = new ArrayList<String>();
ArrayAdapter<String> adapter;
ArrayList<String> list2 = new ArrayList<String>();
ArrayAdapter<String> adapter2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Name=(EditText)findViewById(R.id.name);
Marks=(EditText)findViewById(R.id.marks);
Add=(Button)findViewById(R.id.add);
lv=(ListView)findViewById(R.id.list);
lv2=(ListView)findViewById(R.id.list2);
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, list);
lv.setAdapter(adapter);
adapter2 = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_activated_1, list2);
lv2.setAdapter(adapter2);
Add.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
String name = Name.getText().toString();
String marks = Marks.getText().toString();
if(name.length() > 0 && marks.length() > 0)
{
list.add(name);
adapter.notifyDataSetChanged();
list2.add(marks);
adapter2.notifyDataSetChanged();
}
}
});
}
#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;
}
}
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<ListView
android:id="#+id/list"
android:layout_width="match_parent"
android:layout_height="200dp"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_toLeftOf="#+id/textView2" >
</ListView>
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/list"
android:layout_marginTop="36dp"
android:text="Enter name"
android:textAppearance="?android:attr/textAppearanceMedium" />
<EditText
android:id="#+id/name"
android:layout_width="80dp"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/list"
android:layout_alignRight="#+id/textView1"
android:layout_below="#+id/textView1"
android:layout_marginTop="15dp"
android:ems="10"
android:inputType="textPersonName" >
<requestFocus />
</EditText>
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/textView1"
android:layout_alignBottom="#+id/textView1"
android:layout_marginLeft="28dp"
android:layout_toRightOf="#+id/textView1"
android:text="Enter marks"
android:textAppearance="?android:attr/textAppearanceMedium" />
<ListView
android:id="#+id/list2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_above="#+id/textView1"
android:layout_alignLeft="#+id/textView2"
android:layout_alignParentTop="true"
android:layout_alignRight="#+id/textView2" >
</ListView>
<EditText
android:id="#+id/marks"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/name"
android:layout_alignLeft="#+id/textView2"
android:layout_alignRight="#+id/textView2"
android:ems="10" />
<Button
android:id="#+id/add"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/name"
android:layout_marginTop="33dp"
android:layout_toRightOf="#+id/name"
android:text="ADD" />
</RelativeLayout>
and your min sdk version should be 11