I am working on an app with tab views that needs the Android app combat theme. I want to implement a listview in this app. However, I need to extend the Main Activity Class with the AppCombat Activity Class and the List Activity Class, to get both working - which is not possible in one class, as far as I know. I´m a bit stuck here and any help would be appreciated.
MainActivity.class
package com.example.TodoList;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListAdapter;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import com.example.TodoList.db.TaskContract;
import com.example.TodoList.db.TaskDBHelper;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private ListAdapter listAdapter;
private TaskDBHelper helper;
private Toolbar toolbar;
private Button btnIconTextTabs;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
updateUI();
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
btnIconTextTabs = (Button) findViewById(R.id.btnIconTextTabs);
btnIconTextTabs.setOnClickListener(this);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
final EditText inputField = new EditText(this);
builder.setNegativeButton("Cancel", null);
switch (item.getItemId()) {
case R.id.action_add_task:
builder.setTitle("Add an article to your shopping list");
builder.setMessage("What would you like to add?");
builder.setView(inputField);
builder.setPositiveButton("Add", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
String task = inputField.getText().toString();
helper = new TaskDBHelper(MainActivity.this);
SQLiteDatabase db = helper.getWritableDatabase();
ContentValues values = new ContentValues();
values.clear();
values.put(TaskContract.Columns.TASK, task);
db.insertWithOnConflict(TaskContract.TABLE, null, values, SQLiteDatabase.CONFLICT_IGNORE);
updateUI();
}
});
builder.create().show();
return true;
case R.id.action_remove_task:
builder.setTitle("Remove an article from the shopping list");
builder.setMessage("Did you found this article?");
builder.setNegativeButton("Remove", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
String task = inputField.getText().toString();
helper = new TaskDBHelper(MainActivity.this);
SQLiteDatabase db = helper.getWritableDatabase();
ContentValues values = new ContentValues();
values.clear();
updateUI();
}
});
case R.id.action_show_mylocation:
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Log.d("MyTagGoesHere", "This is my log message at the debug level here");
//Intent intent=new Intent(this,LbsGeocodingActivity.class);
//startActivity(intent);
Intent GeoLocationIntent = new Intent(MainActivity.this, GeoActivity.class);
//myIntent.putExtra("key", value); //Optional parameters
MainActivity.this.startActivity(GeoLocationIntent);
}
builder.create().show();
return true;
}
private void updateUI() {
helper = new TaskDBHelper(MainActivity.this);
SQLiteDatabase sqlDB = helper.getReadableDatabase();
Cursor cursor = sqlDB.query(TaskContract.TABLE,
new String[]{TaskContract.Columns._ID, TaskContract.Columns.TASK},
null, null, null, null, null);
listAdapter = new SimpleCursorAdapter(
this,
R.layout.task_view,
cursor,
new String[]{TaskContract.Columns.TASK},
new int[]{R.id.taskTextView},
0
);
this.setListAdapter(listAdapter);
}
public void onDoneButtonClick(View view) {
View v = (View) view.getParent();
TextView taskTextView = (TextView) v.findViewById(R.id.taskTextView);
String task = taskTextView.getText().toString();
String sql = String.format("DELETE FROM %s WHERE %s = '%s'",
TaskContract.TABLE,
TaskContract.Columns.TASK,
task);
helper = new TaskDBHelper(MainActivity.this);
SQLiteDatabase sqlDB = helper.getWritableDatabase();
sqlDB.execSQL(sql);
updateUI();
}
public void onSubmitPriceClick(View view) {
Intent SubmitPriceIntent = new Intent(MainActivity.this, SubmitPriceActivity.class);
MainActivity.this.startActivity(SubmitPriceIntent);
}
public void onScrollViewButtonClick(View view) {
Intent SubmitPriceIntent = new Intent(MainActivity.this, IconTextTabsActivity.class);
MainActivity.this.startActivity(SubmitPriceIntent);
}
public void onWebViewButtonClick(View view) {
Intent intent = new
Intent(Intent.ACTION_VIEW,
Uri.parse("http://www.batprice.com:1337"));
startActivity(intent);
finish();
}
public void onGeoLocationButtonClick(View view) {
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Log.d("MyTagGoesHere", "This is my log message at the debug level here");
Intent GeoLocationIntent = new Intent(MainActivity.this, GeoActivity.class);
MainActivity.this.startActivity(GeoLocationIntent);
}
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.btnIconTextTabs:
startActivity(new Intent(MainActivity.this, IconTextTabsActivity.class));
break;
}
}
}
I get the error "Cannot resolve method 'setListAdapter(android.widget.ListAdapter)'.
How can I solve this problem?
You are extending AppCompatActivity not ListActivity, AppCompatActivity does not inherently implement a ListView, so there is no setListAdapter() method. You need to either extend ListActivity (which does not extend AppCompatActivity, so this may not be preferable) or put a ListView in your layout and call setAdapter() on your ListView. Something like this:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView listView = (ListView) findViewById(R.id.listview);
listView.setAdapter(listAdapter);
...
}
Or you can use an android.support.v4.app.ListFragment, which is implemented in a similar manner to ListActivity.
Related
I've been working on a Android Project (A Basic College Information App), I have three main activities, the user goes in like, Goal/Course Select activity-> CollegeList activity-> College Details Activity. Now When I press back on College Details Activity it crashes with this Error:
Attempt to invoke virtual method 'int java.lang.String.hashCode()' on a null object reference
Below are the files/code which I think might be responsible for this.....
CollegeListActivity.java file
package com.anurag.college_information.activities;
import static com.anurag.college_information.activities.CareerGoalActivity.GOAL;
import static com.anurag.college_information.activities.CareerGoalActivity.SHARED_PREFS;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.anurag.college_information.R;
import com.anurag.college_information.adapters.RecyclerAdapter;
import com.anurag.college_information.models.ModelClass;
import java.util.ArrayList;
import java.util.List;
public class CollegeListActivity extends AppCompatActivity {
private RecyclerAdapter.RecyclerViewClickListener listener;
//ListView collegeList;
TextView collegeListTitle;
Button courseChange;
RecyclerView recyclerView;
LinearLayoutManager LayoutManager;
RecyclerAdapter recyclerAdapter;
List<ModelClass> cList;
String courseName;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_college_list);
collegeListTitle = findViewById(R.id.college_list_title);
courseChange = findViewById(R.id.btn_change_course);
//collegeListTitle.setText(goal + "Colleges");
collegeListTitle.setText(getIntent().getStringExtra("Title") + " Colleges");
initData();
initRecyclerView();
//collegeList = findViewById(R.id.lv_college_list);
courseChange.setTransformationMethod(null);
courseChange.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SharedPreferences sharedPreferences = getSharedPreferences(SHARED_PREFS, MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.clear();
editor.apply();
Intent i = new Intent(CollegeListActivity.this, CareerGoalActivity.class);
startActivity(i);
//finish();
}
});
}
private void initData() {
cList = new ArrayList<>();
courseName = getIntent().getStringExtra("Title");
switch (courseName) {
case "BE/BTech":
cList.add(new ModelClass("https://images.static-collegedunia.com/public/college_data/images/campusimage/1479294300b-5.jpg", "A.P. Shah College of Engineering", "Thane", "8.0"));
break;
case "Pharmacy":
cList.add(new ModelClass("https://images.static-collegedunia.com/public/college_data/images/campusimage/14382400753.jpg", "Bombay College Of Pharmacy", "Mumbai", "9.0"));
break;
}
}
private void initRecyclerView() {
setOnClickListener();
recyclerView = findViewById(R.id.recycler_view);
LayoutManager = new LinearLayoutManager(this);
LayoutManager.setOrientation(RecyclerView.VERTICAL);
recyclerView.setLayoutManager(LayoutManager);
recyclerAdapter = new RecyclerAdapter(cList, listener);
recyclerView.setAdapter(recyclerAdapter);
}
private void setOnClickListener() {
listener = new RecyclerAdapter.RecyclerViewClickListener() {
#Override
public void onClick(View v, int position) {
Intent i = new Intent(CollegeListActivity.this, CollegeDetailsActivity.class);
startActivity(i);
}
};
}
#Override
public void onBackPressed() {
new AlertDialog.Builder(this)
.setMessage("Are you sure you want to exit?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
finish();
}
})
.setNegativeButton("No", null)
.show();
}
}
RecyclerAdapter.java
package com.anurag.college_information.adapters;
import android.content.Context;
import android.content.Intent;
import android.telecom.Call;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import com.anurag.college_information.activities.CollegeDetailsActivity;
import com.anurag.college_information.models.ModelClass;
import com.anurag.college_information.R;
import com.squareup.picasso.Picasso;
import java.util.List;
public class RecyclerAdapter extends RecyclerView.Adapter<RecyclerAdapter.ViewHolder> {
private List<ModelClass> collegeList ;
private RecyclerViewClickListener listener;
List<String> imageUrl, collegeName, collegeLocation, collegeRating;
public RecyclerAdapter(List<ModelClass> collegeList, RecyclerViewClickListener listener){
this.collegeList=collegeList;
this.listener = listener;
}
#NonNull
#Override
public RecyclerAdapter.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.college_list_single_row, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull RecyclerAdapter.ViewHolder holder, int position) {
String imageLink = collegeList.get(position).getImageLink();
//int img = collegeList.get(position).getCollegeImage();
String cName = collegeList.get(position).getCollegeName();
String cRating = collegeList.get(position).getCollegeRating();
String cLocation = collegeList.get(position).getLocation();
Picasso.get().load(imageLink).into(holder.imageView);
//holder.setData(img, cName, cRating);
holder.setData(imageLink, cName, cLocation ,cRating);
}
#Override
public int getItemCount() {
return collegeList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
private ImageView imageView;
private TextView collegeName, collegeRating, collegeLocation;
public ViewHolder(#NonNull View itemView) {
super(itemView);
imageView = itemView.findViewById(R.id.college_image);
collegeName = itemView.findViewById(R.id.college_name);
collegeRating = itemView.findViewById(R.id.college_rating);
collegeLocation = itemView.findViewById(R.id.college_location);
itemView.setOnClickListener(this);
}
public void setData(String imageLink, String cName, String cLocation, String cRating) {
//imageView.setImageResource(img);
Picasso.get().load(imageLink).error(R.drawable.error).into(imageView);
collegeName.setText(cName);
collegeRating.setText(cRating);
collegeLocation.setText(cLocation);
}
#Override
public void onClick(View v) {
listener.onClick(v, getAdapterPosition());
Intent i = new Intent(v.getContext(), CollegeDetailsActivity.class);
i.putExtra("collegeImage", collegeList.get(getAdapterPosition()).getImageLink());
i.putExtra("collegeName", collegeList.get(getAdapterPosition()).getCollegeName());
i.putExtra("collegeRating", collegeList.get(getAdapterPosition()).getCollegeRating());
i.putExtra("collegeLocation", collegeList.get(getAdapterPosition()).getLocation());
v.getContext().startActivity(i);
}
}
public interface RecyclerViewClickListener{
void onClick(View v, int position);
}
}
CollegeDetailsActivity.java
package com.anurag.college_information.activities;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import com.anurag.college_information.R;
import com.squareup.picasso.Picasso;
public class CollegeDetailsActivity extends AppCompatActivity {
Button btnApply;
ImageView dCollegeImage;
TextView dCollegeName, dCollegeRating, dCollegeLocation;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_college_details);
dCollegeImage = findViewById(R.id.details_college_image);
dCollegeName = findViewById(R.id.details_college_name);
dCollegeRating = findViewById(R.id.details_college_rating);
dCollegeLocation = findViewById(R.id.details_college_location);
btnApply = findViewById(R.id.btn_apply);
Intent i = getIntent();
String cn = i.getStringExtra("collegeName");
String cr = i.getStringExtra("collegeRating");
String ci = i.getStringExtra("collegeImage");
String cl = i.getStringExtra("collegeLocation");
Picasso.get().load(ci).error(R.drawable.error).into(dCollegeImage);
dCollegeName.setText(cn);
dCollegeRating.setText(cr);
dCollegeLocation.setText(cl);
btnApply.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "The institute will be notified, of your application", Toast.LENGTH_LONG).show();
Toast.makeText(getApplicationContext(), "The college will contact you, Thank you", Toast.LENGTH_LONG).show();
}
});
}
#Override
public void onBackPressed() {
Intent i = new Intent(CollegeDetailsActivity.this, CollegeListActivity.class);
startActivity(i);
}
}
This is the Error Screenshot:
I'm pretty new to android I've just worked on just 4 to 5 projects,
Any Assistance will be appreciated, Thank You
The commented Out code, is just a normal listview I implemented just In Case, I have to remove the recycler view.
This will probably go away if you don't override onBackPressed in CollegeDetailsActivity. Instead of going back to an activity that had a valid "Title" string extra, the code you posted will go to a new activity where "Title" isn't defined, then get a NullPointerException since courseName will be null in initData (which the error message tells you results in an error on line 81 in that method). Using a null string in a switch results in that type of error
Just remove your onBackPressed entirely in CollegeDetailsActivity.
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) {
//
// }
//
}
I'm developing a Grade/GPA Calculator app on Android during my free time. What the app basically does until now is let the user add Semesters in the Main Activity and when the user clicks on a certain Semester the user is redirected to another Activity where the user can add new Courses for that specific semester. The problem I'm having is that when the user hits on the back button to go to to the Main Activity where the Semesters are located the courses that were added in that semester are erased. The same happens when I go to the phone's homepage and re-launch the app, everything that the user had created has been deleted.
I'm pretty sure my problem is that I'm not saving the data that the user creates to the phone's storage/app's storage, but I can't seem to figure out on how to do this. If anyone can point me in the right direction I would appreciate it. Thanks!
This is my MainActivity class's code: (My MainActivity is where Semesters are added)
package com.example.gradecalculator;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import java.util.ArrayList;
import java.util.Random;
public class MainActivity extends AppCompatActivity {
// Private Fields
private Dialog d;
private EditText semesterName;
private ListView semesterListView;
private ArrayList<String> semesterArray = new ArrayList<String>();
private SemesterAdapter customSemesterAdapter;
private ArrayList<Semester> mySemesters = new ArrayList<>();
private ArrayList<String> semesterBackgrounds = new ArrayList<String>();
private String getSemesterName;
private int randomBackground[] = new int[7];
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Initiating toolbar
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// Making a new dialog
d = new Dialog(this);
// Initializing variables
semesterName = (EditText) d.findViewById(R.id.editTextSemesterName);
semesterListView = (ListView) findViewById(R.id.semesterList);
// Calling the removeSemesters() method
removeSemesters();
// Adding backgrounds to the backgrounds ArrayList
semesterBackgrounds.add("orange_background");
semesterBackgrounds.add("green_background");
semesterBackgrounds.add("aqua_background");
semesterBackgrounds.add("blue_background");
semesterBackgrounds.add("pink_background");
semesterBackgrounds.add("purple_background");
semesterBackgrounds.add("red_background");
semesterBackgrounds.add("yellow_background");
}
// Creating a custom Menu
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.top_menu, menu);
return true;
}
// Buttons in the custom Menu
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.editButton:
Toast.makeText(this, "Delete the desired Semesters by clicking on the trash button located to the right of each Semester", Toast.LENGTH_LONG).show();
return true;
}
return super.onOptionsItemSelected(item);
}
// When user clicks on "+New Semester" button open a popup where the user is prompted to
// type in the Semester Name and when "Done" is clicked the new semester appears in the Main
// Activity
public void newSemesterPopup(View v) {
TextView closePopup;
ImageButton doneButton;
d.setContentView(R.layout.new_semester_popup);
semesterName = (EditText) d.findViewById(R.id.editTextSemesterName);
semesterListView = (ListView) findViewById(R.id.semesterList);
doneButton = (ImageButton) d.findViewById(R.id.doneButton);
doneButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
addSemesters();
}
});
closePopup = (TextView) d.findViewById(R.id.exitButton);
closePopup.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
d.dismiss();
}
});
d.show();
}
// Adds semesters to Main Activity
public void addSemesters() {
getSemesterName = semesterName.getText().toString();
if (semesterArray.contains(getSemesterName)) {
Toast.makeText(getBaseContext(), "Semester Name Already Exists", Toast.LENGTH_SHORT).show();
} else if (getSemesterName == null || getSemesterName.trim().equals("")) {
Toast.makeText(getBaseContext(), "Cannot Add Empty Semester Name", Toast.LENGTH_SHORT).show();
} else {
semesterArray.add(getSemesterName);
mySemesters.add(new Semester(getSemesterName, semesterBackgrounds.get(new Random().nextInt(randomBackground.length))));
customSemesterAdapter = new SemesterAdapter(getApplicationContext(), R.layout.semester_row, mySemesters);
semesterListView.setAdapter(customSemesterAdapter);
d.dismiss();
}
}
// Removes unwanted semesters from Main Activity
public void removeSemesters() {
semesterListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id) {
AlertDialog.Builder deleteAlert = new AlertDialog.Builder(MainActivity.this);
deleteAlert.setTitle("Semester Deletion Process");
deleteAlert.setMessage("Are you sure you want to delete the selected Semesters?");
deleteAlert.setNegativeButton("No! Cancel", null);
deleteAlert.setPositiveButton("Yes! Delete", new AlertDialog.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
customSemesterAdapter.remove(customSemesterAdapter.getItem(position));
semesterArray.remove(position);
customSemesterAdapter.notifyDataSetChanged();
Toast.makeText(MainActivity.this, "Semester Deleted Successfully.", Toast.LENGTH_SHORT).show();
}
});
deleteAlert.show();
return false;
}
});
openSemestersActivity();
}
// Open the SemesterActivity and uses .putExtra to pass data to the SemesterActivity to tell it what semester to render
// data accordingly
public void openSemestersActivity() {
final Intent semester = new Intent(this, SemesterActivity.class);
semesterListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
semester.putExtra("semester", semesterName.getText().toString());
startActivity(semester);
}
});
}
}
This is my SemesterActivity code: (My SemestersActivity is where Courses are added)
package com.example.gradecalculator;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import java.util.ArrayList;
import java.util.Random;
public class SemesterActivity extends AppCompatActivity {
// Private Fields
private Dialog d;
private EditText courseName;
private EditText courseCode;
private EditText courseCredits;
private ListView courseListView;
private ArrayList<String> courseArray = new ArrayList<String>();
private CourseAdapter customCourseAdapter;
private ArrayList<Course> myCourses = new ArrayList<>();
private ArrayList<String> coursesBackgrounds = new ArrayList<String>();
private String getCourseName;
private String getCourseCode;
private String getCourseCredits;
private int randomBackground[] = new int[7];
private TextView courseNameView;
private TextView courseCodeView;
private TextView courseCreditsView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_semester);
d = new Dialog(this);
courseNameView = (TextView) d.findViewById(R.id.editTextCourseName);
courseCodeView = (TextView) d.findViewById(R.id.editTextCourseCode);
courseCreditsView = (TextView) d.findViewById(R.id.editTextCourseCredits);
courseListView = (ListView) findViewById(R.id.coursesList);
// Retrieving the Extra and determining the semester we want to load
Intent myIntent = getIntent();
String semester = myIntent.getStringExtra("semester");
removeCourses();
// Initiating toolbar
Toolbar toolbar = findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// Adding backgrounds to the backgrounds ArrayList
coursesBackgrounds.add("orange_background_big");
coursesBackgrounds.add("green_background_big");
coursesBackgrounds.add("aqua_background_big");
coursesBackgrounds.add("blue_background_big");
coursesBackgrounds.add("pink_background_big");
coursesBackgrounds.add("purple_background_big");
coursesBackgrounds.add("red_background_big");
coursesBackgrounds.add("yellow_background_big");
}
// Creating a custom Menu
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.top_menu, menu);
return true;
}
// Buttons in the custom Menu
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
switch (item.getItemId()) {
case R.id.editButton:
Toast.makeText(this, "Delete the desired Courses by clicking on the trash button located to the right of each Semester", Toast.LENGTH_LONG).show();
return true;
}
return super.onOptionsItemSelected(item);
}
// New course popup
public void newCoursePopup(View v) {
TextView closePopup;
ImageButton doneButton;
d.setContentView(R.layout.new_course_popup);
courseName = (EditText) d.findViewById(R.id.editTextCourseName);
courseCode = (EditText) d.findViewById(R.id.editTextCourseCode);
courseCredits = (EditText) d.findViewById(R.id.editTextCourseCredits);
doneButton = (ImageButton) d.findViewById(R.id.doneButton);
doneButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
addCourses();
}
});
closePopup = (TextView) d.findViewById(R.id.exitButton);
closePopup.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
d.dismiss();
}
});
d.show();
}
// Adding courses to the Semester
public void addCourses() {
getCourseName = courseName.getText().toString();
getCourseCode = courseCode.getText().toString();
getCourseCredits = courseCredits.getText().toString();
if(courseArray.contains(getCourseName)) {
Toast.makeText(getBaseContext(), "Course Name Already Exists", Toast.LENGTH_SHORT).show();
}
else if(getCourseName == null || getCourseName.trim().equals("")) {
Toast.makeText(getBaseContext(), "Cannot Add Empty Course Name", Toast.LENGTH_SHORT).show();
}
else {
courseArray.add(getCourseName);
myCourses.add(new Course(getCourseName, getCourseCode, getCourseCredits, coursesBackgrounds.get(new Random().nextInt(randomBackground.length))));
customCourseAdapter = new CourseAdapter(getApplicationContext(), R.layout.course_row, myCourses);
courseListView.setAdapter(customCourseAdapter);
d.dismiss();
}
}
// Removing courses from the Semester
public void removeCourses() {
courseListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id) {
AlertDialog.Builder deleteAlert = new AlertDialog.Builder(SemesterActivity.this);
deleteAlert.setTitle("Course Deletion Process");
deleteAlert.setMessage("Are you sure you want to delete the selected Courses?");
deleteAlert.setNegativeButton("No! Cancel", null);
deleteAlert.setPositiveButton("Yes! Delete", new AlertDialog.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
customCourseAdapter.remove(customCourseAdapter.getItem(position));
courseArray.remove(position);
customCourseAdapter.notifyDataSetInvalidated();
Toast.makeText(SemesterActivity.this, "Course Deleted Successfully", Toast.LENGTH_SHORT).show();
}
});
deleteAlert.show();
return false;
}
});
}
}
There are a couple of databases you can look into; You can use Room or Realm. You can also check out online DBs like Firestore by Firebase. The beauty about having an online db a user(Student) can access their data from a different phone if they lose or replace their current one. A recommended way to go is to have both to cover both scenarios.
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.
I'm trying to pass data from a custom listview to a new activity and populate its TextViews. It does work but it always takes the first position that was added and passes it through. How do I get it to pass the data clicked on?
MainActivity
package uk.co.jaunt_app.jaunt;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import com.crashlytics.android.answers.Answers;
import com.crashlytics.android.answers.CustomEvent;
import com.firebase.client.DataSnapshot;
import com.firebase.client.Firebase;
import com.firebase.client.FirebaseError;
import com.firebase.client.ValueEventListener;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import java.util.ArrayList;
import java.util.List;
import static uk.co.jaunt_app.jaunt.R.id.Posts;
public class MainActivity extends AppCompatActivity {
private FloatingActionButton addmap;
private Button settingbtn;
private TextView mNameTextView;
private TextView mEmailTextView;
ListView mPosts;
private DrawerLayout mDrawerLayout;
private ActionBarDrawerToggle mDrawerToggle;
private CharSequence mDrawerTitle;
private CharSequence mTitle;
ArrayAdapter<String> adapter;
private FirebaseAuth auth;
private ArrayList<feed> feedPop = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setLogo(R.drawable.jauntlogodark);
getSupportActionBar().setDisplayUseLogoEnabled(true);
setContentView(R.layout.activity_main);
Firebase.setAndroidContext(this);
Firebase ref = new Firebase(Config.FIREBASE_URL);
FirebaseUser currentFirebaseUser = FirebaseAuth.getInstance().getCurrentUser();
String uid = currentFirebaseUser.getUid();
Firebase usersRef = ref.child("Users").child(uid).child("name");
Firebase emailRef = ref.child("Users").child(uid).child("email");
Firebase postRef = ref.child("Users").child(uid).child("Maps");
postRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot snapshot) {
for (final DataSnapshot postSnapshot : snapshot.getChildren()) {
//Getting the data from snapshot
Person person = postSnapshot.getValue(Person.class);
final String mapName = person.getMapName();
final String mapid = person.getMapID();
final String mapStartLat = person.getStartLat();
final String mapStartLong = person.getStartLong();
final String mapEndLat = person.getEndLat();
final String mapEndLong = person.getEndLong();
adapter.notifyDataSetChanged();
feedPop.add(
new feed(mapName, mapStartLat, mapStartLong, mapEndLat, mapEndLong));
final ArrayAdapter<feed> adapter = new feedArrayAdapter(MainActivity.this, 0, feedPop);
ListView listView = (ListView) findViewById(R.id.customListView);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Intent intent = new Intent(MainActivity.this, ViewUserMapActivity.class);
intent.putExtra("mapName", mapName.toString());
intent.putExtra("mapStartLat", mapStartLat.toString());
intent.putExtra("mapStartLong", mapStartLong.toString());
intent.putExtra("mapEndLat", mapEndLat.toString());
intent.putExtra("mapEndLong", mapEndLong.toString());
startActivity(intent);
}
});
}
}
#Override
public void onCancelled(FirebaseError firebaseError) {
Toast.makeText(getApplicationContext(),
"Cancelled", Toast.LENGTH_LONG)
.show();
}
});
//create property elements
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1);
mPosts = (ListView) findViewById(Posts);
mPosts.setAdapter(adapter);
List<Nav> navList= new ArrayList<Nav>();
navList.add(new Nav("Profile"));
navList.add(new Nav("Feed"));
navList.add(new Nav("Maps"));
navList.add(new Nav("Most Popular"));
navList.add(new Nav("Settings"));
navList.add(new Nav("Report a Bug"));
ArrayAdapter<Nav> navadapter = new ArrayAdapter<Nav>(this,android.R.layout.simple_list_item_1, navList);
final ListView lv= (ListView) findViewById(R.id.left_drawer);
lv.setAdapter(navadapter);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
int itemPosition = position;
switch(itemPosition) {
case 0:
Intent menuItem = new Intent(MainActivity.this, UserMapActivity.class);
startActivity(menuItem);
break;
case 1:
menuItem = new Intent(MainActivity.this, UserMapActivity.class);
startActivity(menuItem);
break;
case 2:
menuItem = new Intent(MainActivity.this, UserMapActivity.class);
startActivity(menuItem);
break;
case 3:
menuItem = new Intent(MainActivity.this, UserMapActivity.class);
startActivity(menuItem);
break;
case 4:
menuItem = new Intent(MainActivity.this, SettingsActivity.class);
startActivity(menuItem);
break;
case 5:
menuItem = new Intent(MainActivity.this, UserMapActivity.class);
startActivity(menuItem);
break;
}
}
});
mNameTextView = (TextView) findViewById(R.id.NameTextView);
usersRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String name = dataSnapshot.getValue(String.class);
mNameTextView.setText(name);
}
#Override
public void onCancelled(FirebaseError firebaseError) {
}
});
mEmailTextView = (TextView) findViewById(R.id.EmailTextView);
emailRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String email = dataSnapshot.getValue(String.class);
mEmailTextView.setText(email);
}
#Override
public void onCancelled(FirebaseError firebaseError) {
}
});
addmap = (FloatingActionButton) findViewById(R.id.add_map);
addmap.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Answers.getInstance().logCustom(new CustomEvent("Added Map"));
Intent intent = new Intent(MainActivity.this, MapStartActivity.class);
startActivity(intent);
}
});
settingbtn = (Button) findViewById(R.id.settingbtn);
settingbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, SettingsActivity.class);
startActivity(intent);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.activity_menu_drawer, menu);
return true;
}
}
//custom ArrayAdapter
class feedArrayAdapter extends ArrayAdapter<feed>{
private Context context;
private List<feed> feedPop;
//constructor, call on creation
public feedArrayAdapter(Context context, int resource, ArrayList<feed> objects) {
super(context, resource, objects);
this.context = context;
this.feedPop = objects;
}
//called when rendering the list
public View getView(int position, View convertView, ViewGroup parent) {
//get the property we are displaying
feed feed = feedPop.get(position);
//get the inflater and inflate the XML layout for each item
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.feed_listview, null);
TextView others = (TextView) view.findViewById(R.id.others);
TextView mapname = (TextView) view.findViewById(R.id.address);
//set address and description
String completeOthers = feed.getFeedStartLat() + ", " + feed.getFeedStartLong() + ", " + feed.getFeedEndLat() + ", " + feed.getFeedEndLong();
others.setText(completeOthers);
//set address and description
String completeAddress = feed.getFeedName();
mapname.setText(completeAddress);
return view;
}
}
Get value from ArrayList based on position then pass to activity
intent.putExtra("mapName", feedPop.get(position).getmapName().toString());