How to remove everything from ListView using a button onClick? - java

How to remove everything from ListView using a button onClick? When i try "fullCourseList.clear();", I can't add any more courses and the page is refreshed only after visiting the page again
import static com.example.diplom.MainActivity.fullCourseList;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import com.example.diplom.model.Course;
import com.example.diplom.model.Order;
import java.util.ArrayList;
import java.util.List;
public class OrderPage extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_order_page);
ListView orders_list = findViewById(R.id.orders_list);
List<String> coursesTitle = new ArrayList<>();
for (Course c : MainActivity.fullCourseList) {
if(Order.items_id.contains(c.getId()))
coursesTitle.add(c.getTitle());
}
orders_list.setAdapter(new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, coursesTitle));
}
public void openMain(View view){
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
startActivity(intent);
}
public void onClick(View v) {
//fullCourseList.clear();
}
}

You should save off the adapter so you can call clear() on it. Clearing the list this way will also automatically notify the adapter to update. Since you copied your data into a new list (coursesTitle) clearing the original list will have no immediate effect.
For example:
public class OrderPage extends AppCompatActivity {
private ListView orders_list;
private ArrayAdapter<String> adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_order_page);
orders_list = findViewById(R.id.orders_list);
List<String> coursesTitle = new ArrayList<>();
for (Course c : MainActivity.fullCourseList) {
if(Order.items_id.contains(c.getId()))
coursesTitle.add(c.getTitle());
}
adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, coursesTitle)
orders_list.setAdapter(adapter);
}
public void onClick(View v) {
adapter.clear();
}
}
Edit
If you also want to clear the currently displayed course items out of the master list, you would need to add code like this as well. If that isn't want you want, you need to be more clear in your question about the desired behavior.
public void onClick(View v) {
// clear what is currently shown in the list
adapter.clear();
// Clear the currently displayed entries out of the master list.
// You may also be able to use "removeIf" if you have a new
// enough java/api version
Iterator<Course> itr = MainActivity.fullCourseList.iterator();
while (itr.hasNext()) {
Course c = itr.next();
if(Order.items_id.contains(c.getId())) {
itr.remove();
}
}
// And if you want to ENTIRELY clear the master list, you
// could just do this instead
// MainActivity.fullCourseList.clear()
}

Everything was easier than I thought, I confused myself with my own class names. Thank you all very much for your help!
This worked:
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;;
import android.widget.ListView;
import com.example.diplom.model.Course;
import com.example.diplom.model.Order;
import java.util.ArrayList;
import java.util.List;
public class OrderPage extends AppCompatActivity {
private ListView orders_list;
private ArrayAdapter<String> adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_order_page);
orders_list = findViewById(R.id.orders_list);
List<String> coursesTitle = new ArrayList<>();
for (Course c : MainActivity.fullCourseList) {
if(Order.items_id.contains(c.getId()))
coursesTitle.add(c.getTitle());
}
adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, coursesTitle);
orders_list.setAdapter(adapter);
}
public void onClick(View v) {
adapter.clear();
Order.items_id.clear();
}
public void openMain(View view){
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
startActivity(intent);
}
}

After clearing the ArrayList you have to notify the adapter that the data source has been changed.
public class OrderPage extends AppCompatActivity {
private ListView orders_list;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_order_page);
orders_list = findViewById(R.id.orders_list);
List<String> coursesTitle = new ArrayList<>();
for (Course c : MainActivity.fullCourseList) {
if(Order.items_id.contains(c.getId()))
coursesTitle.add(c.getTitle());
}
orders_list.setAdapter(new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, coursesTitle));
}
public void openMain(View view){
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
startActivity(intent);
}
public void onClick(View v) {
fullCourseList.clear();
orders_list.getAdapter().notifyDataSetChanged();
}
}

Related

ClassCastException: com.nambimobile.widgets.efab.ExpandableFabLayout cannot be cast to Activity onCreate

So I'm adding an expandable fab, but I'm having this error and I don't understand why...
this is the exact error in log:
ava.lang.ClassCastException: com.nambimobile.widgets.efab.ExpandableFabLayout cannot be cast to com.nambimobile.widgets.efab.ExpandableFab
at CategoryActivity.onCreate(CategoryActivity.java:56)
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
public class CategoryActivity extends AppCompatActivity implements CategoryAdapter.onCategoryClickListener {
public static final String CATEGORY_NAME = "category_name";
private NoteViewModel noteViewModel;
private CategoryAdapter adapter;
private RecyclerView recyclerView;
private List<FolderWithNotes> folderWithNotes;
private Note note;
private Folder folder;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
noteViewModel = new ViewModelProvider.AndroidViewModelFactory(this.getApplication()).create(NoteViewModel.class);
recyclerView = findViewById(R.id.category_recyclerview);
recyclerView.setHasFixedSize(true);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
noteViewModel.getFolderWithNotes().observe(this, folderWithNotes -> {
});
ExpandableFab exFab = findViewById(R.id.exFab);
exFab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
switch (view.getId()) {
case (R.id.exfab_add_category):
Intent intent = new Intent(CategoryActivity.this, AddCategoryActivity.class);
startActivity(intent);
case (R.id.exfab_delete_category):
default:
break;
}
}
});
ActivityResultLauncher<Intent> launcher = registerForActivityResult( new ActivityResultContracts.StartActivityForResult(), result -> {
if(result.getResultCode() == Activity.RESULT_OK) {
Intent data = result.getData();
String category = data.getStringExtra(AddCategoryActivity.CATEGORY_REPLY);
String notes = data.getStringExtra(AddNoteActivity.NOTE_REPLY);
Folder folder = new Folder(note.getFolder_name());
noteViewModel.insert(folder, note);
}
});
}
#Override
protected void onResume() {
super.onResume();
adapter = new CategoryAdapter(folderWithNotes, this, this);
recyclerView.setAdapter(adapter);
}
#Override
public void onCategoryClick(int position) {
// code to transfer to AddNoteActivity (where the note list is) by clicking the category folder
noteViewModel.getFolderWithNotes().observe(this, folderWithNotes -> {
Intent intent = new Intent(CategoryActivity.this, NotesActivity.class);
intent.putExtra(CATEGORY_NAME, folderWithNotes.get(position).getFolder().getFolderName());
});
}
public void addCategoryClicked(View view) {
EditText editCategory = findViewById(R.id.et_add_category);
String categoryTitle = editCategory.getText().toString().trim();
Intent intent = new Intent(CategoryActivity.this, AddCategoryActivity.class);
}
public void deleteCategoryClicked(View view) {
}
// #Override
// public void addCategoryClicked(int position) {
//
// }
//
}

how is onActivityResult is different from registerForActivityResult?

actually previously i wanted to pick image fromthe gallery so i came
to know that onActivityResult was deprecated and we should use
registerForActivityResult(). so i used it by defining the mime type
as "image/*" but now i want to import pdf from gallery but there is
no such mime type for that i want to understand how these mime
things works and how can i achieve my task by
registerForActivityResult() method
i also want to understand the how we define the datatype of the someActivityResultLauncher as a string ?? i want to understand how this whole things work...can we define custom mime type by our own ?? please help me in this
'''
package com.parth.iitktimes;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.appcompat.app.AppCompatActivity;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.material.card.MaterialCardView;
import java.io.IOException;
public class addBooks extends AppCompatActivity {
private MaterialCardView selectImage;
private TextView docName;
private Spinner semSpinner, branchSpinner;
private Button btnUpload;
private ActivityResultLauncher<String> someActivityResultLauncher; // why string
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_books);
selectImage = findViewById(R.id.select_image);
docName = findViewById(R.id.tvDocName);
semSpinner = findViewById(R.id.spinner_sem);
branchSpinner = findViewById(R.id.spinner_branch);
btnUpload = findViewById(R.id.btnUploadNotes);
btnUpload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(getApplicationContext(), "uploaded notes successfully", Toast.LENGTH_SHORT).show();
}
});
selectImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
someActivityResultLauncher.launch("");//what used i fill here??
}
});
String[] semesterItems = {"First", "Second", "Third", "Fourth", "Fifth", "Sixth", "Seventh", "Eighth"};
//attaching array adapter to the spinner
//since we not using custom spinner therefore we are using the default array adapter
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, R.layout.support_simple_spinner_dropdown_item, semesterItems);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
semSpinner.setAdapter(adapter);
//on item selected listener to the spinner
semSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
imageCategory = eventSpinner.getSelectedItem().toString();
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
//setting the default category as others
imageCategory = spinnerItems[0];
}
});
String[] branchItems = {"Mchanical", "Electrical", "CSE", "MTH"};
//attaching array adapter to the spinner
//since we not using custom spinner therefore we are using the default array adapter
ArrayAdapter<String> branchAdapter = new ArrayAdapter<String>(this, R.layout.support_simple_spinner_dropdown_item, branchItems);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
branchSpinner.setAdapter(adapter);
//on item selected listener to the spinner
branchSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
imageCategory = eventSpinner.getSelectedItem().toString();
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
//setting the default category as others
imageCategory = spinnerItems[0];
}
});
//activity result launcher
someActivityResultLauncher = registerForActivityResult(
new ActivityResultContracts.GetContent(), new ActivityResultCallback<Uri>() {
#Override
public void onActivityResult(Uri result) {
try {
bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), result);
} catch (IOException e) {
e.printStackTrace();
}
preview_events_image.setImageBitmap(bitmap);
}
});
}
}

pass value between two activities in java

I'm trying to pass a value from an ArrayList in one Activity (LensActivity) to a TextView on my MainActivity. On this site i found the Intent method and was experimenting with that, but seem unable to pass it, the info is getting fetched in the String lensString, and passed to the Intent, but in Main Activity seems to not be passing or getting on the TextView, and in some experiments, since the getIntent is on MainActivity, i got a null pointer.
Here is the code for the LensActivity which has the Button that send the info.
package com.komorebiestudio.cam_report_funcionality;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
public class LensActivity extends AppCompatActivity {
private RecyclerView mRecyclerView;
private LensAdapter mAdapter;
private RecyclerView.LayoutManager mLayoutManager;
private TextView LensChange;
private String lensString;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.lens_activity);
Intent lensIntent = new Intent(LensActivity.this,MainActivity.class);
lensIntent.putExtra("LensIntent",lensString);
final ArrayList <LensItem> lensList = new ArrayList<>();
lensList.add(new LensItem(R.drawable.zeiss,"24mm","Zeiss Compact Prime"));
lensList.add(new LensItem(R.drawable.ic_camera,"35mm","Angenieux"));
lensList.add(new LensItem(R.drawable.cooke,"50mm","Cooke S5I"));
mRecyclerView = findViewById(R.id.lens_list);
mRecyclerView.setHasFixedSize(true);
mLayoutManager = new LinearLayoutManager(this);
mAdapter = new LensAdapter(lensList);
LensChange = findViewById(R.id.lensinfo);
mRecyclerView.setLayoutManager(mLayoutManager);
mRecyclerView.setAdapter(mAdapter);
final Intent ChangeLens = new Intent(this, MainActivity.class);
mAdapter.setOnItemClickListener(new LensAdapter.OnItemClickListener() {
#Override
public void onItemClick(int position) {
//Crea String con la informacion de posicion y texto del lente
String lensPosition = lensList.get(position).getLens();
lensString = lensPosition;
Toast.makeText(getApplicationContext(),"this is " + lensString , Toast.LENGTH_SHORT).show();
startActivity(new Intent(LensActivity.this,MainActivity.class));
}
});
}
}
and here is the code of the MainActivity that receives it.
package com.komorebiestudio.cam_report_funcionality;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity implements FpsDialog.FpsDialogListener{
private TextView textViewinfo1;
private Button button1;
private Button lensButton;
private TextView lensInfo;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lensInfo = findViewById(R.id.lensinfo);
lensInfo.setText(getIntent().getStringExtra("LensIntent"));
textViewinfo1 = findViewById(R.id.info1);
button1 = findViewById(R.id.button1);
button1.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view) {
openDialog();
}
});
lensButton = findViewById(R.id.lensbutton);
lensButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(MainActivity.this,LensActivity.class));
}
});
}
public void openDialog(){
FpsDialog fps_dialog = new FpsDialog();
fps_dialog.show(getSupportFragmentManager(),"Fps Dialog");
}
#Override
public void applyText(String fpsinfo) {
textViewinfo1.setText(fpsinfo);
}
}
In your LensActivity, you're creating an Intent that you never use. The Intent is this one:
Intent lensIntent = new Intent(LensActivity.this,MainActivity.class);
lensIntent.putExtra("LensIntent",lensString);
Instead, you should create it in the Item Click Listener. Just remove the code above, and modify the listener in this way:
mAdapter.setOnItemClickListener(new LensAdapter.OnItemClickListener() {
#Override
public void onItemClick(int position) {
//Crea String con la informacion de posicion y texto del lente
String lensPosition = lensList.get(position).getLens();
lensString = lensPosition;
Intent lensIntent = new Intent(LensActivity.this,MainActivity.class);
lensIntent.putExtra("LensIntent",lensString);
Toast.makeText(getApplicationContext(),"this is " + lensString , Toast.LENGTH_SHORT).show();
startActivity(lensIntent);
}
});
You need to use the putExtra method after you assign a value to the variable lensString
mAdapter.setOnItemClickListener(new LensAdapter.OnItemClickListener() {
#Override
public void onItemClick(int position) {
//Crea String con la informacion de posicion y texto del lente
String lensPosition = lensList.get(position).getLens();
lensString = lensPosition;
lensIntent.putExtra("LensIntent",lensString);
Toast.makeText(getApplicationContext(),"this is " + lensString , Toast.LENGTH_SHORT).show();
// Notice that you are not using your previously created intent in you
// original code.
startActivity(lensIntent);
}
});

Delete a listview item from activity on button click from another activity

I have a MainActivity that shows a listview with items that I add dynamically to it. So far everything works. Now wanted to create a button that should delete the listview item that was clicked on. Here is the code I came with.
MainActivity
package news;
import android.app.Activity;
import android.content.Intent;
import android.support.design.widget.FloatingActionButton;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
ArrayAdapter<String> newslist_adapter;
ArrayList<String> new_subject = new ArrayList<>();
ArrayList<String> new_post = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final ListView post_view = findViewById(R.id.news_feed);
FloatingActionButton add_post_button = findViewById(R.id.post_btn);
//create click event and pass values of arrays
post_view.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
Intent intent = new Intent(getApplicationContext(), full_post_activity.class);
intent.putExtra("Subject", new_subject);
intent.putExtra("Post", new_post);
intent.putExtra("position", id);
// getApplicationContext().startActivity(intent);
startActivityForResult(intent, 2);
}
});
//create button connection and create keylistener
add_post_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this, addpost_activity.class);
startActivityForResult(intent, 1);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
final ListView post_view = findViewById(R.id.news_feed);
if (requestCode == 1) {
if(resultCode == Activity.RESULT_OK){
//get subject and post from second activity
String new_subject_value = data.getStringExtra("newSubject");
String new_post_value = data.getStringExtra("newPost");
new_subject.add(new_subject_value);
new_post.add(new_post_value);
newslist_adapter = new ArrayAdapter<>(
MainActivity.this,
android.R.layout.simple_expandable_list_item_1, new_subject);
post_view.setAdapter(newslist_adapter);
}
}
if (requestCode == 2) {
if(resultCode == Activity.RESULT_OK){
String item2delete = data.getStringExtra("id");
new_subject.remove(item2delete);
newslist_adapter = new ArrayAdapter<>(
MainActivity.this,
android.R.layout.simple_expandable_list_item_1, new_subject);
post_view.setAdapter(newslist_adapter);
}
}
}
}
SecondActivity
package news;
import android.app.Activity;
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.TextView;
import java.util.ArrayList;
public class full_post_activity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.full_post_activity);
final int id = getIntent().getExtras().getInt("id");
//create view reference
final TextView subject_edit = findViewById(R.id.subject_input);
final TextView post_edit = findViewById(R.id.post_input);
//create button reference
Button delete_button = findViewById(R.id.full_post_delete_btn);
//create click event
delete_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
intent.putExtra("id", id);
setResult(Activity.RESULT_OK, intent);
finish();
}
});
ArrayList<String> subject_array = (ArrayList<String>) getIntent().getSerializableExtra("Subject");
ArrayList<String> post_array = (ArrayList<String>) getIntent().getSerializableExtra("Post");
String subject_string = subject_array.get(0);
String post_string = post_array.get(0);
//set textview text
subject_edit.setText(subject_string);
post_edit.setText(post_string);
}
}
My problem now is that the delete button doesn't do anything besides returning to the MainActivity. What am I doing wrong?
You cannot get id value to MainActivity. This line in second activity cause problem
final int id = getIntent().getExtras().getInt("id");
In Main Activity, You can put id value using name index "position"
intent.putExtra("position", id);
So you should change them to
In Second Activity
final int id = getIntent().getExtras().getInt("position");
or Main Activity
intent.putExtra("id", id);
UPDATED try this in Main Activity
intent.putExtra("id", position);
If you want to stay in the activity where the delete button is I would suggest creating a getter and a setter for the list behind your ListView(Easily generate them with ALT+INSERT).
You can then make an instance of your MainActivity inside the delete_buttons OnClick methode and get said List with the getter.
Remove the Item you need to remove and update the list with your setter, again using your MainActivity instance.
Edit: here are some code samples
Getter and Setter:
public ArrayList<String> getNewPost() {
return this.new_post;
}
public void setNewPost(ArrayList<String> np) {
this.new_post = np;
}
delete_button OnClick methode:
delete_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
MainActivity main=new MainActivity();
ListView<String> np=main.getNewPost();
np.remove("StringToRemove");
main.setNewPost(np);
}
});
I would also suggest you to make a back_button to check if the list was updated, you can use your old delete_button onclick for that.

android arrayadapter declaration Error

When i declare the array adapter up as golbal public the app crash when i just start it
but when i declare it inside the onClick method it works fine
i need to know that happen ?
package com.rafahya.myapplication;
import android.content.DialogInterface;
import android.support.v7.app.AlertDialog;
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.Toast;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
public ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(MainActivity.this , android.R.layout.simple_list_item_1 ,arrayList);
public ArrayList<String> arrayList = new ArrayList<String>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
arrayList.add("momen");
arrayList.add("ahmed");
arrayList.add("Amin");
Button button = (Button)findViewById(R.id.ok);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AlertDialog.Builder momen = new AlertDialog.Builder(MainActivity.this)
.setTitle("Enter the Zip Code")
.setAdapter(arrayAdapter , new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(MainActivity.this , "Momen" ,Toast.LENGTH_LONG).show();
}
});
momen.show();
}
});
}
}
public ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(MainActivity.this , android.R.layout.simple_list_item_1 ,arrayList);
With this line you are trying to access MainActivity before it is initialised. When you type this in the onClick it will be executed when you are inside onCreate and the class is already initialised.
As to how to fix it- First declare the variable
public ArrayAdapter<String> arrayAdapter;
and then inside the onCreate
arrayAdapter = new ArrayAdapter<String>(MainActivity.this , android.R.layout.simple_list_item_1 ,arrayList);

Categories