How to add ArrayList items to my ListView - java

I want to connect to paired Bluetooth devices by clicking on them using two ListViews.
One ListView should display all paired devices, those items should be clickable and get connected due to a click on the item itsself. Then this item should be displayed in the second ListView that shows connected devices.
I had several attempts to this problem but i couldnt manage to get it working. Hope you can help.
Here is my Fragment:
EDIT:
public class MainActivityFragment extends Fragment implements OnClickListener {
Button connectButton;
BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
private static final int ENABLE_BLUETOOTH = 1;
private static final String TAG = MainActivityFragment.class.getSimpleName();
ArrayList<String> mPairedDevicesArrayList;
ArrayAdapter<String> mPairedDevicesAdapter;
ListView listViewPaired, listViewConnected;
public void initBluetooth(){
if(!mBluetoothAdapter.isEnabled()) {
Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(intent, ENABLE_BLUETOOTH);
}
}
#Override
public void onCreate(Bundle savedInstance){
super.onCreate(savedInstance);
mPairedDevicesArrayList = new ArrayList<>();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState){
View rootView = inflater.inflate(R.layout.fragment_connect, parent, false);
connectButton = (Button) rootView.findViewById(R.id.connectButton);
connectButton.setOnClickListener(this);
listViewPaired = (ListView) rootView.findViewById(R.id.listViewPaired);
listViewConnected = (ListView) rootView.findViewById(R.id.listViewConnected);
return rootView;
}
#Override
public void onClick(View rootView){
connectButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(mBluetoothAdapter.isEnabled()) {
if(mBluetoothAdapter.isDiscovering()){
Log.i(TAG, "cancel discovery");
mBluetoothAdapter.cancelDiscovery();
}
Log.i(TAG, "Bluetooth start search");
mBluetoothAdapter.startDiscovery();
getPairedDevices();
}
else {
Log.i(TAG, "Bluetooth not activated");
initBluetooth();
}
}
}); listViewPaired.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
listViewConnected.setAdapter(mPairedDevicesAdapter);
}
});
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1) {
if (resultCode == RESULT_OK) {
Toast.makeText(getActivity().getApplicationContext(), "Bluetooth enabled", Toast.LENGTH_LONG).show();
} else if (resultCode == RESULT_CANCELED) {
Toast.makeText(getActivity().getApplicationContext(), "User canceled", Toast.LENGTH_LONG).show();
}
}
}
private void getPairedDevices() {
Set<BluetoothDevice> pairedDevice = mBluetoothAdapter.getBondedDevices();
if(pairedDevice.size()>0)
{
for(BluetoothDevice device : pairedDevice)
{
mPairedDevicesArrayList.add(device.getName()+"\n"+device.getAddress()); mPairedDevicesAdapter = new ArrayAdapter<>(getActivity().getApplicationContext(), R.layout.fragment_connect); listViewPaired.setAdapter(mPairedDevicesAdapter);
Log.i(TAG, "devices in List");
}
}
}
Here is my Fragment-XML:
<TextView
android:text="Welcome in Fragment!"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/textView"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="36dp" />
<Button
android:text="Connect"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/textView"
android:layout_centerHorizontal="true"
android:layout_marginTop="88dp"
android:id="#+id/connectButton" />
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
tools:background="#android:color/holo_blue_bright"
android:layout_toLeftOf="#+id/connectButton"
android:layout_toStartOf="#+id/connectButton"
android:layout_below="#+id/connectButton"
android:id="#+id/listViewPaired" />
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:background="#android:color/darker_gray"
android:layout_toRightOf="#+id/connectButton"
android:layout_toEndOf="#+id/connectButton"
android:layout_below="#+id/connectButton"
android:id="#+id/listViewConnected" />

ArrayAdapter uses a TextView to display each item within it.
See ArrayAdapter
It has a number of constructors that can be used,You can use this constructor to initialize the adapter with you data
ArrayAdapter(Context context, int resource, T[] objects).
And then set it to your listView
like this:
mPairedDevicesAdapter = new ArrayAdapter<>(getActivity().getApplicationContext(), android.R.layout.simple_list_item_1, mPairedDevicesArrayList);
listViewPaired.setAdapter(mPairedDevicesAdapter);
and to set an onClickListener for ListView rows, do that:
listViewPaired.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
// do you code
}
}
See more details here

Related

Opening a new activity gives null object reference

The app is supposed to open a new activity by clicking RecyclerView. but when I try to click on my RecyclerView data, it gives the following error:
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.app.Activity.startActivityForResult(android.content.Intent, int)' on a null object reference
at com.example.studyreminder.CustomAdapter$1.onClick(CustomAdapter.java:69)
I'm using fragments if that makes any difference.
I don't understand how to fix so if anyone knows it will be appreciated.
Class where the error is at:
public class CustomAdapter extends RecyclerView.Adapter<CustomAdapter.myViewHolder> {
private Context context;
private ArrayList task_id, task_subject, task_description, task_due_date;
private Activity activity;
ImageButton deleteTask;
String task;
CustomAdapter(Context context, ArrayList task_id, ArrayList task_subject, ArrayList task_description, ArrayList task_due_date){
this.context = context;
this.task_id = task_id;
this.task_description = task_description;
this.task_subject = task_subject;
this.task_due_date = task_due_date;
}
#NonNull
#Override
public myViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from (context);
View view = inflater.inflate(R.layout.to_do_list, parent, false);
return new myViewHolder(view);
}
#RequiresApi(api = Build.VERSION_CODES.M)
#Override
public void onBindViewHolder(#NonNull myViewHolder holder, final int position) {
holder.taskid_txt.setText(String.valueOf(task_id.get(position)));
holder.taskSubject_txt.setText(String.valueOf(task_subject.get(position)));
holder.taskDescription_txt.setText(String.valueOf(task_description.get(position)));
holder.taskDate_txt.setText(String.valueOf(task_due_date.get(position)));
holder.mainLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(context, UpdateActivity.class);
intent.putExtra("id", String.valueOf(task_id.get(position)));
intent.putExtra("subject", String.valueOf(task_subject.get(position)));
intent.putExtra("description", String.valueOf(task_description.get(position)));
intent.putExtra("dueDate", String.valueOf(task_due_date.get(position)));
activity.startActivityForResult(intent, 1);
}
});
}
#Override
public int getItemCount() {
return task_id.size();
}
public class myViewHolder extends RecyclerView.ViewHolder {
TextView taskid_txt, taskSubject_txt, taskDescription_txt, taskDate_txt;
LinearLayout mainLayout;
public myViewHolder(#NonNull View itemView) {
super(itemView);
taskid_txt = itemView.findViewById(R.id.taskid_txt);
taskSubject_txt = itemView.findViewById(R.id.taskSubject_txt);
taskDescription_txt = itemView.findViewById(R.id.taskDescription_txt);
taskDate_txt = itemView.findViewById(R.id.taskDate_txt);
mainLayout = itemView.findViewById(R.id.mainLayout);
}
}
}
The activity I'm trying to open:
public class UpdateActivity extends AppCompatActivity {
EditText title_input, author_input, pages_input;
Button addBtn2, delete_button;
EditText descEntry2, dateEntry2;
Spinner sp2;
String id, description, dueDate, subject;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_update);
descEntry2 = findViewById(R.id.descEntry2);
dateEntry2 = findViewById(R.id.dateEntry2);
addBtn2= findViewById(R.id.addbtn2);
sp2 = findViewById(R.id.subjectEntry2);
delete_button = findViewById(R.id.delete_button);
//First we call this
getAndSetIntentData();
//Set actionbar title after getAndSetIntentData method
ActionBar ab = getSupportActionBar();
if (ab != null) {
ab.setTitle(subject);
}
addBtn2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//And only then we call this
MyDatabase myDB = new MyDatabase(UpdateActivity.this);
description = descEntry2.getText().toString().trim();
dueDate =dateEntry2.getText().toString().trim();
subject = sp2.getSelectedItem().toString().trim();
myDB.updateData(id, subject, description, dueDate);
}
});
delete_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
confirmDialog();
}
});
}
void getAndSetIntentData(){
if(getIntent().hasExtra("id")
&& getIntent().hasExtra("subject")
&& getIntent().hasExtra("description")
&& getIntent().hasExtra("dueDate")){
//Getting Data from Intent
id = getIntent().getStringExtra("id");
subject = getIntent().getStringExtra("subject");
description = getIntent().getStringExtra("description");
dueDate = getIntent().getStringExtra("dueDate");
//Setting Intent Data
title_input.setText(subject);
author_input.setText(description);
pages_input.setText(dueDate);
Log.d("stev", subject+" "+description+" "+dueDate);
}else{
Toast.makeText(this, "No data.", Toast.LENGTH_SHORT).show();
}
}
void confirmDialog(){
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Delete " + subject + " Task?");
builder.setMessage("Are you sure you want to delete this " + subject + " task?");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
MyDatabase myDB = new MyDatabase(UpdateActivity.this);
myDB.deleteOneRow(subject);
finish();
}
});
builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
}
});
builder.create().show();
}
}
XML code for the UpdateActivity:
<?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">
<TextView
android:id="#+id/addTasktxt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="150dp"
android:layout_marginBottom="50dp"
android:text="#string/addTask"
android:textSize="25dp"
android:textStyle="bold"
app:layout_constraintBottom_toTopOf="#+id/descEntry2"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="#+id/addbtn2"
android:layout_width="155dp"
android:layout_height="57dp"
android:layout_marginTop="50dp"
android:layout_marginBottom="136dp"
android:text="Update"
android:textAllCaps="false"
android:textSize="20dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.488"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/dateEntry2"
/>
<Spinner
android:id="#+id/subjectEntry2"
android:layout_width="228dp"
android:layout_height="55dp"
android:popupBackground="#5c5c5c"
android:textAlignment="center"
app:layout_constraintBottom_toTopOf="#+id/dateEntry2"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent" />
<EditText
android:id="#+id/descEntry2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginStart="50dp"
android:layout_marginEnd="50dp"
android:layout_marginBottom="50dp"
android:ems="10"
android:hint="What needs to be done?"
android:inputType="text"
app:layout_constraintBottom_toTopOf="#+id/subjectEntry2"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent" />
<EditText
android:id="#+id/dateEntry2"
android:layout_width="104dp"
android:layout_height="47dp"
android:layout_marginStart="125dp"
android:layout_marginTop="50dp"
android:layout_marginEnd="125dp"
android:ems="10"
android:hint="#string/taskDueDate"
android:inputType="phone"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.491"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/subjectEntry2" />
<Button
android:id="#+id/delete_button"
android:layout_width="156dp"
android:layout_height="51dp"
android:text="Delete"
android:textAllCaps="false"
android:textSize="20sp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.486"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/addbtn2" />
</androidx.constraintlayout.widget.ConstraintLayout>
you have not intialized private Activity activity; in CustomAdapter constructor.
either initialize it in ctor or try the snippet below:
try replacing:
holder.mainLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(context, UpdateActivity.class);
intent.putExtra("id", String.valueOf(task_id.get(position)));
intent.putExtra("subject", String.valueOf(task_subject.get(position)));
intent.putExtra("description", String.valueOf(task_description.get(position)));
intent.putExtra("dueDate", String.valueOf(task_due_date.get(position)));
activity.startActivityForResult(intent, 1);
}
});
with:
holder.mainLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Context myContext = context == null ? view.getContext() : context;
Intent intent = new Intent(, UpdateActivity.class);
intent.putExtra("id", String.valueOf(task_id.get(position)));
intent.putExtra("subject", String.valueOf(task_subject.get(position)));
intent.putExtra("description", String.valueOf(task_description.get(position)));
intent.putExtra("dueDate", String.valueOf(task_due_date.get(position)));
(activity == null ? (Activity)myContext : activity) .startActivityForResult(intent, 1);
}
});
Try with the following code. I think your activity object is null. You have not initialize your activity object
context.startActivity(intent);
//findViewById() is missing for below variable in UpdateActivity
EditText title_input, author_input, pages_input;

Android studio RecyclerView Error not displaying anything (got a commit 22 hours ago that works fine)

I did something that destroyed my project. It worked on my latest commit 22 hours ago.
I'm using recylerview to get data from logged in user. I can't even see that the recylerview is on my page anymore. How can I revert back to my latest commit in android studio I did one 22 hours ago. I've tried everything I don't understand things. I did not even touch that activity today but 2 hours ago it stopped working.
only thing i did was to refactor the view called custom_layout used for editing notes but i reverted that afterwards maybe something got saved somewhere and causing the error
here is a picture of my view:
enter code here (MODEL)
package com.example.examapplikation.Models;
public class NotesList {
private String title;
private String text;
public NotesList(){
}
public NotesList(String title, String text){
this.title=title;
this.text= text;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
}
VIEWHOLDER! enter code here
package com.example.examapplikation.ViewHolder;
public class NoteViewHolder extends RecyclerView.ViewHolder implements View.OnCreateContextMenuListener {
public TextView text_title, text_content;
public NoteViewHolder(#NonNull View itemView){
super (itemView);
text_title = itemView.findViewById(R.id.text_title);
text_content = itemView.findViewById(R.id.text_content);
itemView.setOnCreateContextMenuListener(this); // context to this view
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) { // on clik update delete on every object
// menu.setHeaderTitle("Select desired option");
menu.add(0,0,getAdapterPosition(),"Edit Note");
menu.add(0,0,getAdapterPosition(),"Delete Note");
}
}
MAINACTIVITY
enter code here
package com.example.examapplikation;
public class HomeActivity extends AppCompatActivity {
private RecyclerView recyclerView;
private FloatingActionButton addNotePageButton;
private FirebaseAuth firebaseAuth;
FirebaseDatabase database;
DatabaseReference notesDb;
FirebaseRecyclerOptions<NotesList> options;
FirebaseRecyclerAdapter<NotesList, NoteViewHolder> adapter; // adapter
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
//iniate
viewSetUp();
// refrense
notesDb = database.getReference("NoteList").child(firebaseAuth.getCurrentUser().getUid());
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager( new LinearLayoutManager(this) );
showEachRow(); // call function
// buton to add note
addNotePageButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(HomeActivity.this, NoteInputActivity.class);
startActivity(intent);
}
});
}
//Region -used for edit and delete this section start reads whats in the post and open ups a window on the same window based on the Viewholder and a xml file called custom_layout
// recycler view in this section and only the verifed logged in user can See his own data!
#Override
protected void onStart() {
super.onStart();
adapter.startListening();
}
#Override
protected void onStop() {
super.onStop();
adapter.stopListening();
}
#Override
public boolean onContextItemSelected(#NonNull MenuItem item) { // viewholder
if (item.getTitle().equals("Edit Note")){
showUpdateDialog(adapter.getRef(item.getOrder()).getKey(),adapter.getItem(item.getOrder()));
} else if (item.getTitle().equals("Delete Note")){
deleteNote(adapter.getRef(item.getOrder()).getKey());
}
return super.onContextItemSelected(item);
}
private void deleteNote(String adapter) { // delete
notesDb.child(adapter).removeValue();
}
private void showUpdateDialog(final String key, NotesList item) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("[ Note Edit Mode]");
builder.setMessage("Please update the desired fields");
View update_layout = LayoutInflater.from(this).inflate(R.layout.custom_layout,null); // view model layou
final EditText changed_title = update_layout.findViewById(R.id.edit_update_title);
final EditText changed_content = update_layout.findViewById(R.id.edit_update_text);
changed_title.setText(item.getTitle()); // get value to new
changed_content.setText(item.getText());
builder.setView(update_layout);
builder.setPositiveButton("Save changes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
String title = changed_title.getText().toString();
String content = changed_content.getText().toString();
NotesList notesList = new NotesList(title,content);
notesDb.child(key).setValue(notesList);
Toast.makeText(HomeActivity.this,"Note Updated", Toast.LENGTH_SHORT).show();
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
builder.show();
}
//# EndRegion
// Region to read data from dataBase using Viewholder and model Notes and a xml file called note_each_row + the home xml file.
private void showEachRow(){ // recycler view
options = new FirebaseRecyclerOptions.Builder<NotesList>()
.setQuery(notesDb,NotesList.class)
.build();
adapter = new FirebaseRecyclerAdapter<NotesList, NoteViewHolder>(options) { // noteViewModel to model to get
#Override
protected void onBindViewHolder(#NonNull NoteViewHolder holder, int position, #NonNull NotesList model) {
holder.text_title.setText(model.getTitle());
holder.text_content.setText(model.getText());
}
#NonNull
#Override
public NoteViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View itemView = LayoutInflater.from(viewGroup.getContext())
.inflate(R.layout.notes_each_row,viewGroup,false); // inflate the rows
return new NoteViewHolder(itemView);
}
};
recyclerView.setAdapter(adapter);
}
//# end Region
//#start region initate to xml
private void viewSetUp(){
recyclerView = findViewById(R.id.recyclerView);
addNotePageButton = findViewById(R.id.fab_button_addPage);
firebaseAuth = FirebaseAuth.getInstance(); // get inSTACE
database = FirebaseDatabase.getInstance();
}
// end region
//# Menu
private void Logout(){ // sign out method called in switchcase
firebaseAuth.signOut();
finish();
startActivity(new Intent(HomeActivity.this,MainActivity.class));
}
#Override
public boolean onCreateOptionsMenu(Menu menu) { //create menu on toolbar
getMenuInflater().inflate(R.menu.menu,menu); //inflated inside
return true;
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) { // handle on click events on items on menu
switch(item.getItemId()){
case R.id.logoutMenu:{
Logout();
finish();
break;
}
case R.id.ProfileMenu:{
startActivity(new Intent(HomeActivity.this,ProfileActivity.class));
finish();
break;
}
case R.id.HomeMenu:{
startActivity(new Intent(HomeActivity.this,HomeActivity.class));
finish();
break;
}
}
return super.onOptionsItemSelected(item);
}
}
// Endregion
XML for each row in the recyclerVIEW
enter code here
<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
xmlns:app="http://schemas.android.com/apk/res-auto"
app:cardElevation="4dp"
app:cardUseCompatPadding="true">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="8dp">
<ImageView
android:id="#+id/random"
android:layout_width="45dp"
android:layout_height="37dp"
android:src="#drawable/note" />
<TextView
android:id="#+id/text_title"
android:background="#color/LightPink"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Title"
style="#style/TextAppearance.AppCompat.Headline"/>
<View
android:layout_marginTop="5dp"
android:id="#+id/fillView"
android:layout_width="fill_parent"
android:layout_height="3dp"
android:background="#c0c0c0"/>
<TextView
android:id="#+id/text_content"
android:text="content"
android:layout_width="match_parent"
android:layout_height="wrap_content"
style="#style/TextAppearance.AppCompat.Body1"/>
</LinearLayout>
</androidx.cardview.widget.CardView>
Even if I don't get data anymore I should be able to see the cardview on my page..?
Don't worry these maybe help you:
This maybe related to low memory and indexing .
Restart your computer
start your ide(android studio)
Build-->Clean
Build-->Rebuild project
File-->Invalidate caches/Restart-->Invalidate and restart
After restarting of android studio(in previous step): File-->Sync with file system
File-->Sync project with gradle files
Close your project
Restart android studio
10.Open your project after some minutes.

How Do I Remove Selected Item From ArrayList and ArrayAdapter On Button Click?

I have ListView with a custom list layout. I am using an ArrayList and ArrayAdapter for this. I am having a difficult time removing selected items from the arraylist. I am not sure want I am doing wrong. Here's an example of a arraylist that I have:
Item A
Item B
Item C
Item D
Let's say that I selected Item C next on button clicked labeled "Remove" I want Item C removed from the list. How do I accomplish this? Currently my code only removes the item on index 0. I want selected item index to be removed.
Here's my codes...
Java Class:
public class MainActivity extends AppCompatActivity {
ListView lstVw;
Button addBtn, removeBtn, clearListBtn;
ArrayList<String> arrayList;
ArrayAdapter<String> adapter;
int getPosition = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lstVw = findViewById(R.id.lstView);
addBtn = findViewById(R.id.add_item_btn);
removeBtn = findViewById(R.id.remove_item_btn);
clearListBtn = findViewById(R.id.clear_list_btn);
arrayList = new ArrayList<>();
adapter = new ArrayAdapter<>(getApplicationContext(), R.layout.item_list, R.id.item_tv, arrayList);
lstVw.setAdapter(adapter);
lstVw.setOnItemClickListener(new android.widget.AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String getItem = adapter.getItem(position);
getPosition = Integer.parseInt(getItem);
}
});
addBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final AlertDialog.Builder adb = new AlertDialog.Builder(MainActivity.this);
adb.setTitle("Enter Item Name");
final EditText itemTxt = new EditText(MainActivity.this);
itemTxt.setText(getString(R.string.default_item_name_value));
itemTxt.setInputType(InputType.TYPE_CLASS_TEXT);
adb.setView(itemTxt);
adb.setPositiveButton("Add", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
String getItem = itemTxt.getText().toString();
Set<String> s = new LinkedHashSet<>(arrayList);
if (s.contains(getItem)) {
arrayList.clear();
arrayList.addAll(s);
Toast.makeText(getApplicationContext(), getItem + " already exists in the list!", Toast.LENGTH_LONG).show();
} else {
arrayList.add(getItem);
adapter.notifyDataSetChanged();
}
}
});
adb.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
adb.create();
adb.show();
}
});
clearListBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!arrayList.isEmpty()) {
arrayList.clear();
adapter.notifyDataSetChanged();
}
}
});
removeBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String getItem = arrayList.get(getPosition);
arrayList.remove(getItem);
adapter.notifyDataSetChanged();
Toast.makeText(getApplicationContext(), getItem + " is removed!", Toast.LENGTH_LONG).show();
}
});
}
}
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/rl"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center">
<ScrollView
android:layout_width="match_parent"
android:layout_height="650dp">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="650dp">
<ListView
android:id="#+id/lstView"
android:layout_width="match_parent"
android:layout_height="650dp"
tools:ignore="NestedScrolling" />
</RelativeLayout>
</ScrollView>
<include layout="#layout/action_buttons"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"/>
Action Buttons XML:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="50dp"
android:layout_gravity="center|top">
<Button
android:id="#+id/add_item_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:textAllCaps="false"
android:text="#string/add_item_text"
android:textSize="14sp"
android:textStyle="bold"
android:textColor="#android:color/black"/>
<Button
android:id="#+id/remove_item_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_toEndOf="#id/add_item_btn"
android:textAllCaps="false"
android:text="Remove Item"
android:textColor="#android:color/black"
android:textSize="14sp"
android:textStyle="bold"/>
<Button
android:id="#+id/clear_list_btn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_toEndOf="#id/remove_item_btn"
android:textAllCaps="false"
android:text="#string/clear_list_text"
android:textSize="14sp"
android:textStyle="bold"
android:textColor="#android:color/black"/>
My Custom List Layout XML:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/container"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ScrollView
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="#+id/item_tv"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textStyle="bold"
android:textSize="20sp"
android:textColor="#android:color/black"/>
</ScrollView>
I appreciate the help! Thanks!
removeBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String getItem = arrayList.get(getPosition);
arrayList.remove(getItem);
adapter.notifyDataSetChanged();
Toast.makeText(getApplicationContext(), getItem + " is removed!", Toast.LENGTH_LONG).show();
}
});
From where are you getting this getPosition?
It looks to me like your int getPosition = 0; variable is not getting updated with your new position. On your click listener you are trying to parse the value of your selected item to an Integer, maybe you could try simply updating with the current position instead?
lstVw.setOnItemClickListener(new android.widget.AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
getPosition = position;
}
});
Edit:
You could go with something like this:
Create an interface that your activity will implement and will be used by your adapter to notify a position change:
public interface PositionChangeListener {
void onPositionChanged(int newPosition);
}
Create a custom adapter:
public class CustomAdapterView extends BaseAdapter {
private Context context;
private PositionChangeListener listener;
private ArrayList<String> items;
public CustomAdapterView(Context context, ArrayList<String> items, PositionChangeListener listener) {
this.context = context;
this.items = items;
this.listener = listener;
}
#Override
public int getCount() {
return items.size();
}
#Override
public Object getItem(int position) {
return items.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder = null;
if (convertView == null) {
convertView = LayoutInflater.from(context).inflate( R.layout.item_list, null);
viewHolder = new ViewHolder();
viewHolder.txt = convertView.findViewById(R.id.item_tv);
viewHolder.txt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
listener.onPositionChanged(position);
}
});
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
viewHolder.txt.setText(items.get(position));
return convertView;
}
private class ViewHolder {
TextView txt;
}
}
And now in your activity:
public class MainActivity extends AppCompatActivity implements PositionChangeListener{
ListView lstVw;
Button addBtn, removeBtn, clearListBtn;
ArrayList<String> arrayList;
BaseAdapter adapter;
int getPosition = 0;
#Override
public void onPositionChanged(int newPosition) {
getPosition = newPosition;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lstVw = findViewById(R.id.lstView);
addBtn = findViewById(R.id.add_item_btn);
removeBtn = findViewById(R.id.remove_item_btn);
clearListBtn = findViewById(R.id.clear_list_btn);
arrayList = new ArrayList<>();
adapter = new CustomAdapterView(this, arrayList, this);
lstVw.setAdapter(adapter);
addBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final AlertDialog.Builder adb = new AlertDialog.Builder(MainActivity.this);
adb.setTitle("Enter Item Name");
final EditText itemTxt = new EditText(MainActivity.this);
itemTxt.setText("default item name");
itemTxt.setInputType(InputType.TYPE_CLASS_TEXT);
adb.setView(itemTxt);
adb.setPositiveButton("Add", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
String getItem = itemTxt.getText().toString();
Set<String> s = new LinkedHashSet<>(arrayList);
if (s.contains(getItem)) {
arrayList.clear();
arrayList.addAll(s);
Toast.makeText(getApplicationContext(), getItem + " already exists in the list!", Toast.LENGTH_LONG).show();
} else {
arrayList.add(getItem);
adapter.notifyDataSetChanged();
}
}
});
adb.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
adb.create();
adb.show();
}
});
clearListBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!arrayList.isEmpty()) {
arrayList.clear();
adapter.notifyDataSetChanged();
}
}
});
removeBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String getItem = arrayList.get(getPosition);
arrayList.remove(getItem);
adapter.notifyDataSetChanged();
Toast.makeText(getApplicationContext(), getItem + " is removed!", Toast.LENGTH_LONG).show();
}
});
}
}

List to individual item swipe

I have an activity that returns a list of information derived from Parse.com in a listview. I would want that each item on the list is shown individually on a page, and where user are able to swipe left or right or navigate through arrows left and right through the list to view other list item.
Below is the code for that produces the list:
public class MatchingActivity extends Activity {
private String currentUserId;
private ArrayAdapter<String> namesArrayAdapter;
private ArrayList<String> names;
private ListView usersListView;
private Button logoutButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.matching);
logoutButton = (Button) findViewById(R.id.logoutButton);
logoutButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ParseUser.logOut();
Intent intent = new Intent(getApplicationContext(), LoginActivity.class);
startActivity(intent);
}
});
setConversationsList();
}
private void setConversationsList() {
currentUserId = ParseUser.getCurrentUser().getObjectId();
names = new ArrayList<String>();
ParseQuery<ParseUser> query = ParseUser.getQuery();
query.whereNotEqualTo("objectId", currentUserId);
query.findInBackground(new FindCallback<ParseUser>() {
public void done(List<ParseUser> userList, ParseException e) {
if (e == null) {
for (int i=0; i<userList.size(); i++) {
names.add(userList.get(i).getUsername().toString());
}
usersListView = (ListView)findViewById(R.id.usersListView);
namesArrayAdapter =
new ArrayAdapter<String>(getApplicationContext(),
R.layout.user_list_item, names);
usersListView.setAdapter(namesArrayAdapter);
usersListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> a, View v, int i, long l) {
openConversation(names, i);
}
});
} else {
Toast.makeText(getApplicationContext(),
"Error loading user list",
Toast.LENGTH_LONG).show();
}
}
});
}
public void openConversation(ArrayList<String> names, int pos) {
ParseQuery<ParseUser> query = ParseUser.getQuery();
query.whereEqualTo("username", names.get(pos));
query.findInBackground(new FindCallback<ParseUser>() {
public void done(List<ParseUser> user, ParseException e) {
if (e == null) {
Intent intent = new Intent(getApplicationContext(), MessagingActivity.class);
intent.putExtra("RECIPIENT_ID", user.get(0).getObjectId());
startActivity(intent);
} else {
Toast.makeText(getApplicationContext(),
"Error finding that user",
Toast.LENGTH_SHORT).show();
}
}
});
}
}
The XML layout
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center">
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/logout"
android:id="#+id/logoutButton"
android:gravity="center_vertical|center_horizontal"
android:layout_gravity="center_horizontal"
android:background="#color/dark_gray"
android:textSize="24sp"
android:padding="15dp"
android:textColor="#color/sinch_purple" />
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="16dp"
android:textColor="#ffffff"
android:background="#drawable/bac_blue"
android:id="#+id/usersListView">
</ListView>
</RelativeLayout>
I have also have looked into http://developer.android.com/training/implementing-navigation/lateral.html, but not sure how I would incorporate that into my listview.
If you require additional information, let me know.
Try using a Viewpager, Here you have examples and documentation.

Android - ListView disappears after setContentView()?

I have a ListView in one my activity_main.xml file, the problem is, when I click on a Item in that ListView (activity_main.xml), it calls setContentView() and loads another XML file called activity_settings.xml.
The problem is, when I click the back button in activity_settings.xml (Button to call setContentView() again and go back to activity_main.xml) The ListView from activity_main.xml disappears.
I have tried about dozen ways of fixing it, but nothing seems to work.
Here is my MainActivity.java (It is pretty big):
package com.NautGames.xectav2.app;
import {...}
public class MainActivity extends ASR {
private ToggleButton homeOnOff;
HomeHoldDown hhd = new HomeHoldDown();
int keyCode;
KeyEvent event;
Context context;
private static final String LOGTAG = "Xecta";
private static final String BOTID = "e38006d97e34053e";
private TTS myTts;
private ImageButton speakButton;
private Bot bot;
Button backB1;
Button backB2;
Button backB3;
boolean mBound = false;
SimpleAdapter simpleAdpt;
BoundService myService = new BoundService();
boolean isBound = false;
EditText name, email, mMessage, subject;
String key;
String Name;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent intent = new Intent(this, BoundService.class);
bindService(intent, myConnection, Context.BIND_AUTO_CREATE);
//homeOnOff = (ToggleButton) findViewById(R.id.toggleButton);
name = (EditText) findViewById(R.id.etName);
email = (EditText) findViewById(R.id.etEmail);
mMessage = (EditText) findViewById(R.id.etAdd);
subject = (EditText) findViewById(R.id.txtSubject);
Button startBtn = (Button) findViewById(R.id.send);
backB1 = (Button)findViewById(R.id.button1);
backB2 = (Button)findViewById(R.id.button2);
backB3 = (Button)findViewById(R.id.button3);
//Initialize GUI elements
setSpeakButton();
//Initialize the speech recognizer
createRecognizer(getApplicationContext());
//Initialize text to speech
myTts = TTS.getInstance(this);
//Create bot
bot = new Bot(this, BOTID, myTts, "assistant");
initList();
// We get the ListView component from the layout
ListView lv = (ListView) findViewById(R.id.listView);
// This is a simple adapter that accepts as parameter
// Context
// Data list
// The row layout that is used during the row creation
// The keys used to retrieve the data
// The View id used to show the data. The key number and the view id must match
simpleAdpt = new SimpleAdapter(this, planetsList, android.R.layout.simple_list_item_1, new String[] {"page"}, new int[] {android.R.id.text1});
lv.setAdapter(simpleAdpt);
// React to user clicks on item
lv.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
public void onItemClick(AdapterView<?> parentAdapter, View view, int position,
long id)
{
// We know the View is a TextView so we can cast it
TextView clickedView = (TextView) view;
//Toast.makeText(MainActivity.this, "Item with id ["+id+"] - Position ["+position+"] - Planet ["+clickedView.getText()+"]", Toast.LENGTH_SHORT).show();
if(id == 0)
{
setContentView(R.layout.activity_settings);
}
if(id == 1)
{
setContentView(R.layout.activity_about);
}
if(id == 2)
{
setContentView(R.layout.activity_feedback);
}
}
});
}
public void onClickSend(View v) {
Intent i = new Intent(Intent.ACTION_SEND);
i.setType("message/rfc822");
i.putExtra(Intent.EXTRA_EMAIL , new String[]{"name#email.com"});
i.putExtra(Intent.EXTRA_SUBJECT, subject.getText().toString());
i.putExtra(Intent.EXTRA_TEXT , mMessage.getText().toString());
try {
startActivity(Intent.createChooser(i, "Send mail..."));
} catch (android.content.ActivityNotFoundException ex) {
Toast.makeText(MainActivity.this, "There are no email clients installed.", Toast.LENGTH_SHORT).show();
}
}
//from here
private ServiceConnection myConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className,
IBinder service) {
BoundService.MyLocalBinder binder = (BoundService.MyLocalBinder) service;
myService = binder.getService();
isBound = true;
}
public void onServiceDisconnected(ComponentName arg0) {
isBound = false;
}
};
//to HERE
public void showTime(View view)
{
myService.getCurrentTime();
}
/************************************************************************
* WHEN THE USER TURNS THE HOME LISTENING ON AND OFF
* IT WILL START SERVICE AND STOP SERVICE
*************************************************************************/
/*public void onToggleClicked(View view) {
boolean on = ((ToggleButton) view).isChecked();
if (on) {
//Toast.makeText(MainActivity.this, "Activate Xecta with Home ON", Toast.LENGTH_LONG).show();
//startService(new Intent(getBaseContext(), Service1.class));
} else {
//Toast.makeText(MainActivity.this, "Activate Xecta with Home OFF", Toast.LENGTH_LONG).show();
//stopService(new Intent(getBaseContext(), LocalService.class));
}
}*/
#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;
}
/*public void onClickService(View view)
{
if(isApplicationSentToBackground(context))
{
hhd.onKeyLongPress(keyCode, event);
}
}*/
/**************************************************************************
* WHEN THE USER HOLDS DOWN THE HOME BUTTON
*************************************************************************/
#Override
public boolean onKeyLongPress(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
Toast.makeText(MainActivity.this, "Key pressed long!", Toast.LENGTH_LONG).show();
return true;
}
return super.onKeyLongPress(keyCode, event);
}
public void onClickBack(View view)
{
setContentView(R.layout.activity_main);
}
// The data to show
List<Map<String, String>> planetsList = new ArrayList<Map<String,String>>();
private void initList() {
// We populate the planets
planetsList.add(newList("page", "Settings"));
planetsList.add(newList("page", "About"));
planetsList.add(newList("page", "FeedBack"));
}
private HashMap<String, String> newList(String key, String name) {
HashMap<String, String> planet = new HashMap<String, String>();
planet.put(key, name);
return planet;
}
public void onClick(View view)
{
speakButton = (ImageButton) findViewById(R.id.speech_btn);
try {
listen(RecognizerIntent.LANGUAGE_MODEL_WEB_SEARCH, 10);
} catch (Exception e) {
Toast.makeText(getApplicationContext(),"ASR could not be started: invalid params", Toast.LENGTH_SHORT).show();
Log.e(LOGTAG, e.getMessage());
}
}
private void setSpeakButton() {
speakButton = (ImageButton) findViewById(R.id.speech_btn);
speakButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
listen(RecognizerIntent.LANGUAGE_MODEL_WEB_SEARCH, 10);
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "ASR could not be started: invalid params", Toast.LENGTH_SHORT).show();
Log.e(LOGTAG, e.getMessage());
}
}
});
}
/**
* Provides feedback to the user when the ASR encounters an error
*/
public void processAsrError(int errorCode) {
String errorMessage;
switch (errorCode)
{
case SpeechRecognizer.ERROR_AUDIO:
errorMessage = "Audio recording error";
break;
case SpeechRecognizer.ERROR_CLIENT:
errorMessage = "Client side error";
break;
case SpeechRecognizer.ERROR_INSUFFICIENT_PERMISSIONS:
errorMessage = "Insufficient permissions" ;
break;
case SpeechRecognizer.ERROR_NETWORK:
errorMessage = "Network related error" ;
break;
case SpeechRecognizer.ERROR_NETWORK_TIMEOUT:
errorMessage = "Network operation timeout";
break;
case SpeechRecognizer.ERROR_RECOGNIZER_BUSY:
errorMessage = "RecognitionServiceBusy" ;
break;
case SpeechRecognizer.ERROR_SERVER:
errorMessage = "Server sends error status";
break;
case SpeechRecognizer.ERROR_NO_MATCH:
errorMessage = "No matching message" ;
break;
case SpeechRecognizer.ERROR_SPEECH_TIMEOUT:
errorMessage = "Input not audible";
break;
default:
errorMessage = "ASR error";
break;
}
try {
myTts.speak(errorMessage,"EN");
} catch (Exception e) {
Log.e(LOGTAG, "English not available for TTS, default language used instead");
}
//If there is an error, shows feedback to the user and writes it in the log
Log.e(LOGTAG, "Error: "+ errorMessage);
Toast.makeText(this, errorMessage, Toast.LENGTH_LONG).show();
}
public void processAsrReadyForSpeech() {
Toast.makeText(this, "I'm listening", Toast.LENGTH_LONG).show();
}
public void processAsrResults(ArrayList<String> nBestList, float[] confidences) {
String bestResult = nBestList.get(0);
Log.d(LOGTAG, "Speech input: " + bestResult);
// insert %20 for spaces in query
bestResult = bestResult.replaceAll(" ", "%20");
bot.initiateQuery(bestResult);
//Toast.makeText(MainActivity.this, "", Toast.LENGTH_LONG).show();
}
#Override
public void onDestroy() {
myTts.shutdown();
super.onDestroy();
}
#Override
public void onBackPressed() {
super.onBackPressed();
setContentView(R.layout.activity_main);
newList(key, Name);
initList();
}
#Override
public void onStop()
{
super.onStop();
Toast.makeText(MainActivity.this, "Bye bye!", Toast.LENGTH_SHORT).show();
onKeyLongPress(keyCode, event);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
onClickBack is the button to go back to activity_main.xml, I am also initialising the ListView in onCreate().
activity_main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#drawable/onericblur"
android:orientation="vertical"
android:paddingBottom="5dp"
android:onClick="onClick"
android:weightSum="1">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#000000"
android:orientation="vertical" >
<TextView
android:id="#+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:background="#000000"
android:paddingBottom="10dip"
android:paddingTop="10dip"
android:text="#string/title"
android:textColor="#FFFFFF"
android:textSize="18sp" />
</LinearLayout>
<ViewAnimator
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/viewAnimator"
android:layout_gravity="right" />
<ImageButton
android:id="#+id/speech_btn"
android:background="#null"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/xectaicon"
android:onClick="onClick"
android:layout_marginTop="32dp"
android:layout_gravity="center_horizontal|top" />
<ListView
android:layout_width="match_parent"
android:layout_height="127dp"
android:id="#+id/listView"
android:layout_weight="1.22"
android:background="#android:drawable/screen_background_light_transparent" />
</LinearLayout>
And activity_settings...
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent"
android:weightSum="1"
android:background="#drawable/onericblur">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
style="?android:attr/listSeparatorTextViewStyle"
android:text="Settings"
android:id="#+id/textView"
android:layout_gravity="center_horizontal"
android:textSize="30dp"
android:textColor="#android:color/black" />
<TextView
android:layout_width="291dp"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Xecta is currently in Beta being tested, you can request settings by going to the feedback section. Sorry!"
android:id="#+id/textView2"
android:layout_weight="0.04"
android:layout_gravity="center_horizontal"
android:textSize="20dp"
android:gravity="center|top" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Back to home"
android:id="#+id/button3"
android:onClick="onClickBack"
android:layout_gravity="center_horizontal" />
</LinearLayout>
What could be causing the problem?!?!?
Thanks.
As suggested by Ram Kiran, it's better to have different activities for Settings / Home.
The problem with the code you have posted is that you are not populating the list with the contents when you press back. I believe it should be fixed with the following code,
public void onClickBack(View view)
{
setContentView(R.layout.activity_main);
ListView lv = (ListView) findViewById(R.id.listView);
lv.setAdapter(simpleAdpt);
}
Basically when you call setContentView(layoutId) new view will be inflated from the layout and you need to do all the UI lookup, initialization again.
I dont think loading xml files repeatedly in same activity is a good one. Try to use two activities instead of loading different xml files in same activity.
MainActivity.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView lv = (ListView) findviewById(R.id.list);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
public void onItemClick(AdapterView<?> parentAdapter, View view, int position,
long id)
{
Intent n = new Intent(getApplicationContext(),SettingsActivity.class);
startActivity(n);
}
}
SettingsActivity.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Buttoon btn = (Button) findviewById(R.id.btn);
btn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent n = new Intent(getApplicationContext(),MainActivity.class);
startActivity(n);
}
});
Try out as below:
#Override
public void onResume()
{
super.onResume();
setContentView(R.layout.activity_main);
Intent intent = new Intent(this, BoundService.class);
bindService(intent, myConnection, Context.BIND_AUTO_CREATE);
//homeOnOff = (ToggleButton) findViewById(R.id.toggleButton);
name = (EditText) findViewById(R.id.etName);
email = (EditText) findViewById(R.id.etEmail);
mMessage = (EditText) findViewById(R.id.etAdd);
subject = (EditText) findViewById(R.id.txtSubject);
Button startBtn = (Button) findViewById(R.id.send);
backB1 = (Button)findViewById(R.id.button1);
backB2 = (Button)findViewById(R.id.button2);
backB3 = (Button)findViewById(R.id.button3);
//Initialize GUI elements
setSpeakButton();
//Initialize the speech recognizer
createRecognizer(getApplicationContext());
//Initialize text to speech
myTts = TTS.getInstance(this);
//Create bot
bot = new Bot(this, BOTID, myTts, "assistant");
initList();
// We get the ListView component from the layout
ListView lv = (ListView) findViewById(R.id.listView);
// This is a simple adapter that accepts as parameter
// Context
// Data list
// The row layout that is used during the row creation
// The keys used to retrieve the data
// The View id used to show the data. The key number and the view id must match
simpleAdpt = new SimpleAdapter(this, planetsList, android.R.layout.simple_list_item_1, new String[] {"page"}, new int[] {android.R.id.text1});
lv.setAdapter(simpleAdpt);
}

Categories

Resources