Cannot set text to EditText from custom dialog - java

I had some problem with setting text to EditText. There are no error occur and I can get text from customDialog, but when I set text to edittext nothing happen.
This is a pact of xml file that use to set up edittext.
<LinearLayout
android:id="#+id/setting_layout_fname"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:weightSum="100"
android:clickable="true">
<TextView
android:layout_height="wrap_content"
android:layout_weight="25"
android:clickable="false"
android:text="Firstname"
android:textStyle="bold"
android:layout_width="wrap_content" />
<android.support.design.widget.TextInputLayout
android:id="#+id/setting_textLayout_fname"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="right"
android:layout_weight="75"
android:clickable="false">
<android.support.design.widget.TextInputEditText
android:id="#+id/setting_edittext_fname"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:clickable="false"/>
</android.support.design.widget.TextInputLayout>
</LinearLayout>
And this is code to handle my alertdialog.
package com.example.yggdrasil.realapplication;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.TextInputEditText;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
public class setting extends AppCompatActivity implements View.OnClickListener{
private android.support.v7.widget.Toolbar toolbar;
private LinearLayout linear_fname, linear_lname, linear_birthdate, linear_gender, linear_tel,
linear_carefname, linear_carelname, linear_careemail, linear_caretel, linear_range,
linear_min, linear_max;
private TextInputEditText input_fname;
private List<LinearLayout> layout_list;
private AlertDialog.Builder alertdialog;
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_setting);
alertdialog = new AlertDialog.Builder(this);
layout_list = new ArrayList<LinearLayout>();
toolbar = (android.support.v7.widget.Toolbar) findViewById(R.id.activity_setting_toolbar);
toolbar.setCollapsible(true);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("Setting");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDefaultDisplayHomeAsUpEnabled(true);
input_fname = (TextInputEditText) findViewById(R.id.setting_edittext_fname);
input_fname.setText("test");
layout_list.add(linear_fname = (LinearLayout) findViewById(R.id.setting_layout_fname));
/*layout_list.add(linear_lname = (LinearLayout) findViewById(R.id.setting_layout_lname));
layout_list.add(linear_birthdate = (LinearLayout) findViewById(R.id.setting_layout_birthdate));
layout_list.add(linear_gender = (LinearLayout) findViewById(R.id.setting_layout_gender));
layout_list.add(linear_tel = (LinearLayout) findViewById(R.id.setting_layout_tel));
layout_list.add(linear_carefname = (LinearLayout) findViewById(R.id.setting_layout_caretaker_fname));
layout_list.add(linear_carelname = (LinearLayout) findViewById(R.id.setting_layout_caretaker_lname));
layout_list.add(linear_careemail = (LinearLayout) findViewById(R.id.setting_layout_caretaker_email));
layout_list.add(linear_caretel = (LinearLayout) findViewById(R.id.setting_layout_caretaker_tel));
layout_list.add(linear_range = (LinearLayout) findViewById(R.id.setting_layout_glucose_range));
layout_list.add(linear_min = (LinearLayout) findViewById(R.id.setting_textLayout_minglucose));
layout_list.add(linear_max = (LinearLayout) findViewById(R.id.setting_textLayout_maxglucose));*/
for(LinearLayout linearLayout : layout_list){
linearLayout.setOnClickListener(this);
}
}
public void onClick(View v){
if(v.getId() == R.id.setting_layout_fname){
final EditText edittext = new EditText(getApplicationContext());
alertdialog.setTitle("First Name");
alertdialog.setMessage("Enter your firstname: ");
alertdialog.setView(edittext);
alertdialog.setPositiveButton("Yes", new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog, int whichButton) {
final String fname = edittext.getText().toString();
Toast.makeText(setting.this, fname, Toast.LENGTH_SHORT).show();
setting.this.input_fname.setText( fname, TextView.BufferType.EDITABLE);
}
});
alertdialog.setNegativeButton("No", new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog, int whichButton) {
}
});
alertdialog.create().show();
}
}
don't know what happen with my code, Toast always show same value as I put it but it not show in edittext of mainActivity.

code have 2 edittext, the 1st is editText in alertdialog that created programmatically, and the 2nd is editText that create in xml file.
All I want to do is setText to editText in xml with value from editText in alertdialog. I can got the value from edittext in alertdialog but cannot setText to editText in xml file.
package com.example.yggdrasil.realapplication;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.TextInputEditText;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
public class setting extends AppCompatActivity implements View.OnClickListener{
private android.support.v7.widget.Toolbar toolbar;
private LinearLayout linear_fname, linear_lname, linear_birthdate, linear_gender, linear_tel,
linear_carefname, linear_carelname, linear_careemail, linear_caretel, linear_range,
linear_min, linear_max;
private TextInputEditText input_fname;
private List<LinearLayout> layout_list;
private AlertDialog.Builder alertdialog;
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_setting);
alertdialog = new AlertDialog.Builder(this);
layout_list = new ArrayList<LinearLayout>();
toolbar = (android.support.v7.widget.Toolbar) findViewById(R.id.activity_setting_toolbar);
toolbar.setCollapsible(true);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("Setting");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDefaultDisplayHomeAsUpEnabled(true);
input_fname = (TextInputEditText) findViewById(R.id.setting_edittext_fname);
input_fname.setText("test");
layout_list.add(linear_fname = (LinearLayout) findViewById(R.id.setting_layout_fname));
for(LinearLayout linearLayout : layout_list){
linearLayout.setOnClickListener(this);
}
}
public void onClick(View v){
if(v.getId() == R.id.setting_layout_fname){
final EditText edittext = new EditText(getApplicationContext());
alertdialog.setTitle("First Name");
alertdialog.setMessage("Enter your firstname: ");
alertdialog.setView(edittext);
alertdialog.setPositiveButton("Yes", new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog, int whichButton) {
final String fname = edittext.getText().toString();
Toast.makeText(setting.this, fname, Toast.LENGTH_SHORT).show();
setting.this.input_fname.setText( fname, TextView.BufferType.EDITABLE);
}
});
alertdialog.setNegativeButton("No", new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog, int whichButton) {
}
});
alertdialog.create().show();
}
}
layout code
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<android.support.v7.widget.Toolbar
android:id="#+id/activity_setting_toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content">
</android.support.v7.widget.Toolbar>
</android.support.design.widget.AppBarLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:divider="?android:dividerHorizontal"
android:showDividers="middle"
android:padding="10dp">
<LinearLayout
android:id="#+id/setting_layout_fname"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:weightSum="100"
android:clickable="true">
<TextView
android:layout_height="wrap_content"
android:layout_weight="25"
android:clickable="false"
android:text="Firstname"
android:textStyle="bold"
android:layout_width="wrap_content" />
<android.support.design.widget.TextInputLayout
android:id="#+id/setting_textLayout_fname"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_gravity="right"
android:layout_weight="75"
android:clickable="false">
<android.support.design.widget.TextInputEditText
android:id="#+id/setting_edittext_fname"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:clickable="false"/>
</android.support.design.widget.TextInputLayout>
</LinearLayout>
</LinearLayout>
</ScrollView>

Hmmm... I figure something. When I create new xml class withly slight same element with the old one, It perfectly work either with editText or textView. So I think I did some mistake and overlook it. So I guess that I should answer my own question.

Related

Android Studio RecyclerView wont show my data when i add toolbar at my `layout.xml` file

I created a page where it will show the firebase data in a RecyclerView. It work but I decided to put a toolbar at the top of the page to have a back function. After I put the toolbar in my layout file, the RecyclerView is not showing any data anymore. I think that my layout XML file is wrong. Thanks in advance for anyone helping.
Actity file
package com.example.attendanceappvqyfyp;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.Toolbar;
import com.example.attendanceappvqyfyp.Interface.itemClickListener;
import com.example.attendanceappvqyfyp.Common.Common;
import com.example.attendanceappvqyfyp.Model.LecturerClass;
import com.example.attendanceappvqyfyp.Model.News;
import com.example.attendanceappvqyfyp.Model.Timetable;
import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.example.attendanceappvqyfyp.Common.Common;
public class LecturerClassList extends AppCompatActivity {
RecyclerView recyclerView;
RecyclerView.LayoutManager layoutManager;
FirebaseDatabase database;
DatabaseReference lecturerclass;
DatabaseReference news;
FirebaseRecyclerAdapter<LecturerClass,LecturerClassViewHolder> adapter;
TextView newscourse, newsclass;
EditText newsdescription;
Toolbar toolbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_lecturer_class_list);
//Firebase
database = FirebaseDatabase.getInstance();
lecturerclass = database.getReference("Class");
news = database.getReference("News");
recyclerView = (RecyclerView)findViewById(R.id.recycler_lecturerclass);
recyclerView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(layoutManager);
//Toolbar code
toolbar = findViewById(R.id.toolbar);
toolbar.setTitle("Class List");
toolbar.setNavigationIcon(R.drawable.ic_arrow_back_black_24dp);
loadLecturerClass(Common.currentLecturer.getName());
}
private void loadLecturerClass(String Lecturer) {
adapter = new FirebaseRecyclerAdapter<LecturerClass, LecturerClassViewHolder>(LecturerClass.class, R.layout.lecturerclass_item, LecturerClassViewHolder.class, lecturerclass.orderByChild("lecturer").equalTo(Lecturer)) {
#Override
protected void populateViewHolder(LecturerClassViewHolder lecturerClassViewHolder, LecturerClass lecturerClass, int i) {
lecturerClassViewHolder.lclasstitle.setText("Class :" + adapter.getRef(i).getKey());
lecturerClassViewHolder.ldate.setText("Day :" + lecturerClass.getDay());
lecturerClassViewHolder.ltime.setText("Time :" + lecturerClass.getTime());
lecturerClassViewHolder.lclassroom.setText("Classroom :" + lecturerClass.getClassroom());
lecturerClassViewHolder.lcourse.setText(lecturerClass.getCourse());
lecturerClassViewHolder.setItemClickListener(new itemClickListener() {
#Override
public void onClick(View view, int position, boolean isLongClick) {
//code later
}
});
}
};
recyclerView.setAdapter(adapter);
}
#Override
public boolean onContextItemSelected(MenuItem item) {
if(item.getTitle().equals(Common.News))
{
showNewsDialog(adapter.getRef(item.getOrder()).getKey(),adapter.getItem(item.getOrder()));
}
return super.onContextItemSelected(item);
}
private void showNewsDialog(final String course, final LecturerClass item) {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(LecturerClassList.this);
alertDialog.setTitle("Make Announcement");
alertDialog.setMessage("Make announcement about this class.");
LayoutInflater inflater = this.getLayoutInflater();
View lecturer_make_news = inflater.inflate(R.layout.activity_lecturer_make_news, null);
newscourse = lecturer_make_news.findViewById(R.id.NewsCourse);
newsclass = lecturer_make_news.findViewById(R.id.NewsClass);
newsdescription = lecturer_make_news.findViewById(R.id.NewsDescription);
newscourse.setText("Course: "+item.getCourse());
newsclass.setText("Subject: " + course);
alertDialog.setView(lecturer_make_news);
alertDialog.setPositiveButton("Post", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int i) {
if(newsdescription.getText().toString().isEmpty()){
Toast.makeText(LecturerClassList.this, "Post cancel, description cannot be empty.", Toast.LENGTH_SHORT).show();
}
else {
News lnews = new News(
item.getCourse(),
course,
newsdescription.getText().toString()
);
news.child(String.valueOf(System.currentTimeMillis())).setValue(lnews);
Toast.makeText(LecturerClassList.this, "Announcement post successfully.", Toast.LENGTH_SHORT).show();
finish();
}
}
});
alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();;
}
});
alertDialog.show();
}
}
Activity file for viewholder
package com.example.attendanceappvqyfyp;
import android.view.ContextMenu;
import android.view.View;
import android.widget.TextView;
import com.example.attendanceappvqyfyp.Common.Common;
import androidx.recyclerview.widget.RecyclerView;
import com.example.attendanceappvqyfyp.Interface.itemClickListener;
public class LecturerClassViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener,View.OnCreateContextMenuListener {
public TextView lclasstitle, ldate, ltime, lclassroom, lcourse;
private itemClickListener itemClickListener;
public LecturerClassViewHolder(View itemView) {
super(itemView);
lclasstitle = (TextView)itemView.findViewById(R.id.lclasstitle);
ldate = (TextView)itemView.findViewById(R.id.ldate);
ltime = (TextView)itemView.findViewById(R.id.ltime);
lclassroom = (TextView)itemView.findViewById(R.id.lclassroom);
lcourse = (TextView)itemView.findViewById(R.id.lcourse);
itemView.setOnCreateContextMenuListener(this);
itemView.setOnClickListener(this);
}
public void setItemClickListener(itemClickListener itemClickListener) {
this.itemClickListener = itemClickListener;
}
#Override
public void onClick(View view) {
itemClickListener.onClick(view, getAdapterPosition(), false);
}
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
menu.setHeaderTitle("Select");
menu.add(0,0,getAdapterPosition(), Common.News);
}
}
Layout file for recyclerview
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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"
tools:context=".LecturerClassList">
<android.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="?attr/colorPrimary"
android:minHeight="?attr/actionBarSize"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:theme="#style/ThemeOverlay.AppCompat.Dark" />
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/recycler_lecturerclass"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:scrollbars="vertical"
app:layout_constraintTop_toBottomOf="#+id/toolbar" />
</androidx.constraintlayout.widget.ConstraintLayout>
Layout file for itemview
<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="160dp"
app:cardElevation="4dp"
android:layout_marginBottom="8dp"
>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="#+id/lclasstitle"
android:layout_width="match_parent"
android:layout_height="40dp"
android:gravity="center"
android:text=""
android:textColor="#android:color/black"
android:textSize="20sp" />
<TextView
android:id="#+id/ldate"
android:layout_width="match_parent"
android:layout_height="40dp"
android:layout_alignBottom="#id/lclasstitle"
android:layout_marginBottom="-40dp"
android:gravity="center"
android:text=""
android:textColor="#android:color/black"
android:textSize="20sp" />
<TextView
android:id="#+id/ltime"
android:layout_width="match_parent"
android:layout_height="40dp"
android:layout_alignBottom="#id/ldate"
android:layout_marginBottom="-40dp"
android:gravity="center"
android:text=""
android:textColor="#android:color/black"
android:textSize="20sp" />
<TextView
android:id="#+id/lclassroom"
android:layout_width="match_parent"
android:layout_height="40dp"
android:layout_alignParentBottom="true"
android:gravity="center"
android:text=""
android:textColor="#android:color/black"
android:textSize="20sp" />
<TextView
android:id="#+id/lcourse"
android:layout_width="match_parent"
android:layout_height="40dp"
android:layout_alignParentBottom="true"
android:gravity="center"
android:text=""
android:visibility="invisible"
android:textColor="#android:color/black"
android:textSize="20sp" />
</RelativeLayout>
</androidx.cardview.widget.CardView>
Thanks to ZeePee for giving this link Display Back Arrow on Toolbar, although the toolbar didnt work for me, i change it back to actionbar and use the code from the link and it work.
Try adding horizontal constraints for Toolbar and Recycler View. After that you need to specify where do you want your single item widgets in Relative layout

How to add strings from editText to a listView

I have a MainActivity with a ListView and an add Button. When the user clicks the add Button it takes you to another activity the CreateActivity for you to enter in data or strings into the editText boxes. After that you click the create Button and it adds the strings to the ListView it shows up, but every time I try to add another item to the ListView it just overrides the first item and doesn't add on to the ListView.
MainActivity.java with listView and add button
package com.example.brian.inventoryapp;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import static android.R.layout.simple_list_item_1;
public class MainActivity extends AppCompatActivity {
Button addButton;
ListView itemListView;
public static ArrayList<String> arrayList;
public static ArrayAdapter arrayAdapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Bundle editTextData = getIntent().getExtras();
if(editTextData != null){
itemListView = (ListView)findViewById(R.id.itemListView);
String data = editTextData.getString("data");
arrayList = new ArrayList<String>();
arrayList.add(data);
arrayAdapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1, arrayList);
itemListView.setAdapter(arrayAdapter);
if(data != ""){
arrayAdapter.notifyDataSetChanged();
}
}
addButton = (Button) findViewById(R.id.addButton);
addButton.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, CreateActivity.class);
startActivity(intent);
}
});
}
}
activity_main xml with listView and add button
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_main"
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="com.example.brian.inventoryapp.MainActivity"
android:weightSum="1">
<Button
android:text="Add"
android:layout_width="wrap_content"
android:layout_height="58dp"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:id="#+id/addButton" />
<ListView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="#+id/itemListView"
/>
</RelativeLayout>
CreateActivity.java with four editText boxes and create button
package com.example.brian.inventoryapp;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import static com.example.brian.inventoryapp.R.id.editTextItem;
public class CreateActivity extends AppCompatActivity {
EditText editTextItem;
EditText editTextModel;
EditText editTextSerial;
EditText editTextID;
Button createButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create);
getIntent();
editTextItem = (EditText)findViewById(R.id.editTextItem);
editTextModel = (EditText)findViewById(R.id.editTextModel);
editTextSerial = (EditText)findViewById(R.id.editTextSerial);
editTextID = (EditText)findViewById(R.id.editTextID);
createButton = (Button) findViewById(R.id.createButton);
createButton.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
String item = "";
item = editTextItem.getText().toString().trim() +
editTextModel.getText().toString().trim() +
editTextSerial.getText().toString().trim() +
editTextID.getText().toString().trim();
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
intent.putExtra("data", item);
startActivity(intent);
}
});
}
}
activity_create xml with the four editText boxes and the create button
<?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:id="#+id/activity_create"
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="com.example.brian.inventoryapp.CreateActivity">
<TextView
android:text="Item Name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:id="#+id/textView" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="textPersonName"
android:ems="10"
android:layout_below="#+id/textView"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:id="#+id/editTextItem" />
<TextView
android:text="Model Number"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="18dp"
android:id="#+id/textView2"
android:layout_below="#+id/editTextItem"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="textPersonName"
android:ems="10"
android:layout_below="#+id/textView2"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:id="#+id/editTextModel" />
<TextView
android:text="Serial Number"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/editTextModel"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="18dp"
android:id="#+id/textView3" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="textPersonName"
android:ems="10"
android:layout_below="#+id/textView3"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:id="#+id/editTextSerial" />
<ImageButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:srcCompat="#mipmap/ic_launcher"
android:layout_below="#+id/editTextID"
android:layout_centerHorizontal="true"
android:layout_marginTop="64dp"
android:id="#+id/imageButton" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:inputType="textPersonName"
android:ems="10"
android:id="#+id/editTextID"
android:layout_below="#+id/editTextSerial"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginTop="18dp" />
<TextView
android:text="ID Number"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/textView4"
android:layout_below="#+id/editTextSerial"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<Button
android:text="Create"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/createButton"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true" />
</RelativeLayout>
every time you restart the MainActivity, it is be created, the onCreate method was executed .one method you can use the comment method:use startactivityforResult;
you can read this question how to manage startactivityforResult.the second method is to set MainActivity model to SingleInstance.
You are starting MainActivity over and over again, clearing all data previously loaded.
Try this solution
Main activity:
package com.example.brian.inventoryapp;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import static android.R.layout.simple_list_item_1;
public class MainActivity extends AppCompatActivity {
public static final int CREATE_REQUEST = 1;
private Button addButton;
private ListView itemListView;
private ArrayList<String> arrayList;
private ArrayAdapter<String> arrayAdapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
itemListView = (ListView) findViewById(R.id.itemListView);
addButton = (Button) findViewById(R.id.addButton);
arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, arrayList);
itemListView.setAdapter(arrayAdapter);
addButton = (Button) findViewById(R.id.addButton);
addButton.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, CreateActivity.class);
startActivityForResult(intent, CREATE_REQUEST);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CREATE_REQUEST) {
if (resultCode == RESULT_OK) {
String item = data.getStringExtra("data");
arrayList.add(item);
arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, arrayList);
itemListView.setAdapter(arrayAdapter);
}
}
}
}
In your CreateActivity change createButton listener to this one:
createButton.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v) {
String item = "";
item = editTextItem.getText().toString().trim() +
editTextModel.getText().toString().trim() +
editTextSerial.getText().toString().trim() +
editTextID.getText().toString().trim();
Intent intent = new Intent();
intent.putExtra("data", item);
setResult(RESULT_OK, intent);
finish();
}
});
Yes it will assume as if the MainActivity is started for the first time so you should use startActivityForResult() method instead of startActivity().This will continue your MainActivity and do not override your list View.

How to use viewHolder to make listView user input not go back to default when scrolling off screen

I have a listView where a user can enter input to change the textView on each listView row. When you scroll the row off the screen the edited text goes away and the default text reappears. I know this is fixed with the viewHolder but I can't get it to work in my custom adapter class.
MainActivity.java
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.app.Activity;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ViewSwitcher;
import java.util.ArrayList;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final ArrayList<String> Chores = new ArrayList<>();
//Chores.add("");
final ListAdapter MyAdapter = new CustomAdapter(this, Chores);
ListView listViewObject = (ListView)findViewById(R.id.customListView_ID);
listViewObject.setAdapter(MyAdapter);
listViewObject.setOnItemClickListener(
new AdapterView.OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id){
String ChoreString = String.valueOf(parent.getItemAtPosition(position));
}
}
);
final Button button = (Button) findViewById(R.id.button_ID);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Chores.add("");
((ArrayAdapter)MyAdapter).notifyDataSetChanged();
}
});
}
}
CustomAdapter.java
import android.content.Context;
import android.content.DialogInterface;
import android.support.annotation.NonNull;
import android.support.v7.app.AlertDialog;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import java.util.ArrayList;
import static com.example.emilythacker.chorelist.R.id.textView_ID;
class CustomAdapter extends ArrayAdapter{
ArrayList<String> choreText;
public CustomAdapter(Context context, ArrayList choreText) {
super(context, R.layout.custon_listview_row, choreText);
this.choreText = choreText;
}
#NonNull
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
//final TextView textView = (TextView) customView.findViewById(textView_ID);
if (convertView == null) {
LayoutInflater layoutInflater = LayoutInflater.from(getContext());
convertView = layoutInflater.inflate(R.layout.custon_listview_row, null);
holder = new ViewHolder();
holder.imageButton = (ImageButton) convertView.findViewById(R.id.imageButton_ID);
holder.textView = (TextView) convertView.findViewById(textView_ID);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.textView.setText(choreText.get(position));
holder.textView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//what happens when textView is clicked
AlertDialog alertDialog = new AlertDialog.Builder(getContext()).create();
final EditText input = new EditText(getContext());
input.setHint("hint");
alertDialog.setView(input);
alertDialog.setTitle("Set Chore");
alertDialog.setMessage("Alert message to be shown");
alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
holder.textView.setText(input.getText().toString());
dialog.dismiss();
}
});
alertDialog.show();
}
});
holder.imageButton.setImageResource(R.drawable.clock);
return convertView;
}
static class ViewHolder {
ImageButton imageButton;
TextView textView;
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_main"
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="com.example.emilythacker.chorelist.MainActivity">
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/customListView_ID"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true"
android:layout_marginTop="50dp" />
<Button
android:text="Add Chore"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true"
android:id="#+id/button_ID" />
</RelativeLayout>
custon_listview_row.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"
android:orientation="horizontal" android:layout_width="match_parent"
android:layout_height="60dp">
<ImageButton
android:layout_width="60dp"
android:scaleType="fitCenter"
app:srcCompat="#drawable/clock"
android:id="#+id/imageButton_ID"
android:layout_height="60dp"
android:background="#null"
android:layout_alignParentRight="true"
android:padding="5dp"
android:layout_weight="1" />
<TextView
android:text="Click here to add chore"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10"
android:id="#+id/textView_ID"
android:textSize="25dp"
android:layout_centerVertical="true"
android:layout_toStartOf="#+id/imageButton_ID"
android:layout_marginEnd="11dp"
/>
</RelativeLayout>
When text is entered into the edit text, you need to save it to a variable associated with that position, and in getView you need to set the text of the editText to that position's value. Otherwise you'll just have whatever random value was in there last.
Basically, any value that can change in a row's UI must be saved and written to it in getView.

i get the Error: java.lang.IllegalStateException: The content of the adapter has changed but ListView did not receive a notification

I don't know what is wrong with this code. I am trying to make a to do list app. I am new to Android and Java programming so please don't get mad if this is a simple errror.It gives me the error in the title.
Here is my 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:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin" tools:context=".MainActivity">
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/lvItems"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Add"
android:id="#+id/button"
android:layout_alignParentBottom="true"
android:layout_alignParentEnd="true"
android:onClick="onAddItem"/>
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/etNewItem"
android:hint="Enter a new item"
android:layout_alignParentStart="true"
android:layout_alignTop="#+id/button"
android:layout_toStartOf="#+id/button" />
</RelativeLayout>
Here is my Java:
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import java.util.ArrayList;
public class MainActivity extends Activity {
private ArrayList<String> items;
private ArrayAdapter<String> itemsAdapter;
private ListView lvItems;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//EditText
final EditText etTask = (EditText) findViewById(R.id.etNewItem);
final String Task = etTask.getText().toString();
lvItems = (ListView) findViewById(R.id.lvItems);
items = new ArrayList<String>();
itemsAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, items);
lvItems.setAdapter(itemsAdapter);
items.add("First Item");
items.add("Second Item");
//Button
Button btn = (Button) findViewById(R.id.button);
//Adding a Task
//OnClickListeners
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
items.add(etTask.getText().toString());
etTask.setText("");
}
});
}
}
Since you made a change to adapter after ListView was populated, Listview must be informed to repopulate the views with new values by calling notifydatasetchanged() on your adapter ie,
items.add(etTask.getText().toString());
((ArrayAdapter)lvItems.getAdapter()).notifydatasetchanged();
etTask.setText("");

TextView goes out of screen up and down

So I'm creating the custom dialog box which should appear after the required button is pressed. However, when the text is too long, the textView goes out of screen. I tried to find a solution for this, however unsuccessfully.
I hope you will help me, guys. Thanks.
Here is the xml code for the dialog box:
<?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="wrap_content"
android:orientation="vertical"
android:layout_gravity="center"
android:layout_marginTop="20dp"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp">
<ScrollView
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="#+id/txt_dia"
android:layout_height="match_parent"
android:layout_width="match_parent"
android:textSize="16sp"
android:layout_gravity="center"
android:textColor="#color/black"/>
</ScrollView>
<Button
android:id="#+id/btn_back"
android:layout_height="40dp"
android:layout_width="100dp"
android:clickable="true"
android:text="#string/bck"
android:textStyle="bold"
android:layout_gravity="left"/>
</LinearLayout>
Dialog class:
import android.app.Activity;
import android.app.Dialog;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.TextView;
public class CustomDialogClass extends Dialog implements android.view.View.OnClickListener {
public Activity c;
public Dialog d;
public Button back;
private TextView strongHeads;
private String text = "";
public CustomDialogClass(Activity a) {
super(a);
this.c = a;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.custom_dialog);
strongHeads = (TextView) findViewById(R.id.txt_dia);
//strongHeads.setMovementMethod(new ScrollingMovementMethod());
if(text.equalsIgnoreCase("")){
strongHeads.setText(text);
}
strongHeads.setText(text);
back = (Button) findViewById(R.id.btn_back);
back.setOnClickListener(this);
}
#Override
public void onClick(View v) {
dismiss();
}
public void changeText(String txt){
this.text= txt;
}
}

Categories