Android - Passing an ArrayList of Custom Objects to Another Activity - java

So, I've been struggling on this for a while and have searched on here for hours without finding anything that really helped. I have a custom class Streak. When the user creates a new Streak in my Main Activity, I want for that streak to be added to a list of total streaks, which I would then access from an AllStreaks activity. I have tried using Gson, but received errors. What I have below is working for the time being, but since my global variable has to be declared as new. I don't really want to use a MySQL database as this info needs to be quickly editable and I don't want to have to constantly connect to that to potentially change just one detail.
Sorry if my code is a mess or this makes no sense, I'm coming to realize I'm really shitty at programming anyway.
MainActivity.java:
public class MainActivity extends AppCompatActivity {
private SharedPreferences prefs;
private SharedPreferences.Editor editor;
private String userID;
private int streakCounter;
private int mainStreakCounter;
private RelativeLayout quickAdd;
private EditText quickSubmitStreak;
private Button quickSubmitButton;
private Button mainStreak1;
private Button mainStreak2;
private Button mainStreak3;
private Button mainStreak4;
private Button allStreaks;
private Button addStreak;
private Dialog pickDialog;
private Button healthButton;
private Button mentalButton;
private Button personalButton;
private Button professionalButton;
private Button socialButton;
private Button submitStreakButton;
private TextView todaysDate;
private EditText chooseDate;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
/*
Creates shared preferences and editor
*/
prefs = getSharedPreferences("carter.streakly", MODE_PRIVATE);
editor = prefs.edit();
// Checks if it's the first time the user opens the app. If so, generates a unique user ID and stores it in shared prefs
if (prefs.getBoolean("firstTime", true)){
userID = UUID.randomUUID().toString();
editor.putString("user", userID);
editor.putBoolean("firstTime", false);
editor.commit();
}
streakCounter = 0; // CHANGE TO streakCounter = prefs.getInt("streakCounter", 0) later
mainStreakCounter = 0; // CHANGE TO mainStreakCount = prefs.getInt("mainStreakCounter", 0) later
quickSubmitStreak = (EditText) findViewById(R.id.enter_goal);
quickSubmitButton = (Button) findViewById(R.id.submit_button);
mainStreak1 = (Button) findViewById(R.id.main_goal_1);
mainStreak2 = (Button) findViewById(R.id.main_goal_2);
mainStreak3 = (Button) findViewById(R.id.main_goal_3);
mainStreak4 = (Button) findViewById(R.id.main_goal_4);
allStreaks = (Button) findViewById(R.id.main_goal_5);
addStreak = (Button) findViewById(R.id.add_streak_button);
/*
if (streakCounter > 4){
quickAdd.setVisibility(View.INVISIBLE);
}
mainStreak1.setText(prefs.getString("mainKeyOne", ""));
mainStreak2.setText(prefs.getString("mainKeyTwo", ""));
mainStreak3.setText(prefs.getString("mainKeyThree", ""));
mainStreak4.setText(prefs.getString("mainKeyFour", ""));
/*
Sets the text to the lowest unused main streak to the inputted streak name
Stores the streak name in shared prefs so it will be there for next time app opens
Increases the total streak count
*/
quickSubmitButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (mainStreakCounter < 4){
switch(mainStreakCounter){
case 0:
mainStreak1.setText(quickSubmitStreak.getText().toString());
editor.putString("mainKeyOne", quickSubmitStreak.getText().toString()).commit();
break;
case 1:
mainStreak2.setText(quickSubmitStreak.getText().toString());
editor.putString("mainKeyTwo", quickSubmitStreak.getText().toString()).commit();
break;
case 2:
mainStreak3.setText(quickSubmitStreak.getText().toString());
editor.putString("mainKeyThree", quickSubmitStreak.getText().toString()).commit();
break;
case 3:
mainStreak4.setText(quickSubmitStreak.getText().toString());
editor.putString("mainKeyFour", quickSubmitStreak.getText().toString()).commit();
break;
default:break;
}
}
mainStreakCounter++;
AllStreaks.streakList.add(new Streak(quickSubmitStreak.getText().toString()));
// ADD THESE TO SHARED PREFERENCES AT SOME POINT
}
});
/*
Brings user to the All Streaks activity, and passes the LinkedList<Streak> streakList
*/
allStreaks.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this, AllStreaks.class);
startActivity(intent);
}
});
/*
Shows an Alert Dialog that allows users to enter in the type of streak they want
*/
addStreak.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
createCustomDialog();
}
});
}
private void createCustomDialog(){
pickDialog = new Dialog(MainActivity.this);
pickDialog.setContentView(R.layout.dialog_add_streak);
final EditText chooseName = (EditText) pickDialog.findViewById(R.id.dialog_acitivty_name);
healthButton = (Button) pickDialog.findViewById(R.id.dialog_health);
mentalButton = (Button) pickDialog.findViewById(R.id.dialog_mental);
personalButton = (Button) pickDialog.findViewById(R.id.dialog_personal);
professionalButton = (Button) pickDialog.findViewById(R.id.dialog_professional);
socialButton = (Button) pickDialog.findViewById(R.id.dialog_social);
submitStreakButton = (Button) pickDialog.findViewById(R.id.dialog_submit_button);
todaysDate = (TextView) pickDialog.findViewById(R.id.dialog_today);
chooseDate = (EditText) pickDialog.findViewById(R.id.dialog_input_date);
pickDialog.show();
healthButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
editor.putInt("AddCategory", 0).commit();
editor.putString("Category", "Health");
editor.commit();
recolorCategory();
}
});
mentalButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
editor.putInt("AddCategory", 1).commit();
editor.putString("Category", "Mental");
editor.commit();
recolorCategory();
}
});
personalButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
editor.putInt("AddCategory", 2).commit();
editor.putString("Category", "Personal");
editor.commit();
recolorCategory();
}
});
professionalButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
editor.putInt("AddCategory", 3).commit();
editor.putString("Category", "Professional");
editor.commit();
recolorCategory();
}
});
socialButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
editor.putInt("AddCategory", 4).commit();
editor.putString("Category", "Social");
editor.commit();
recolorCategory();
}
});
todaysDate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
todaysDate.setTextColor(Color.rgb(51,51,255));
chooseDate.setTextColor(Color.rgb(0,0,0));
editor.putInt("todayOrChosen", 1).commit();
}
});
chooseDate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
chooseDate.setTextColor(Color.rgb(51,51,255));
todaysDate.setTextColor(Color.rgb(0,0,0));
editor.putInt("todayOrChosen", 2).commit();
}
});
submitStreakButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
/*
If the user selected today's date, enter the days kept as 0. If the user selected how long they've kept the streak for, enter the days kept as chooseDate
*/
if(prefs.getInt("todayOrChosen", 1) == 1){
//streakList.add(new Streak(chooseName.getText().toString(), prefs.getString("Category", ""),
//new SimpleDateFormat("dd-MM-yyyy").format(new Date()), 0));
AllStreaks.streakList.add(new Streak(chooseName.getText().toString(), prefs.getString("Category", ""),
new SimpleDateFormat("dd-MM-yyyy").format(new Date()), 0));
}
else {
//streakList.add(new Streak(chooseName.getText().toString(), prefs.getString("Category", ""),
//new SimpleDateFormat("dd-MM-yyyy").format(new Date()), Integer.parseInt(chooseDate.getText().toString())));
AllStreaks.streakList.add(new Streak(chooseName.getText().toString(), prefs.getString("Category", ""),
new SimpleDateFormat("dd-MM-yyyy").format(new Date()), Integer.parseInt(chooseDate.getText().toString())));
}
/*
Update streakList in Shared Preferences
*/
/*
Display an Alert Dialog indicating that a streak has been added
*/
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setMessage("Streak Added")
.setPositiveButton("OK", null)
.create()
.show();
pickDialog.dismiss();
}
});
}
/*
Highlights which category is currently chosen
*/
private void recolorCategory(){
Button[] categoryList = {healthButton, mentalButton, personalButton, professionalButton, socialButton};
int recolorIndex = prefs.getInt("AddCategory", 0);
categoryList[recolorIndex].setTextColor(Color.rgb(51,51,255));
for (int i = 0; i < 5; i++){
if (i != recolorIndex) categoryList[i].setTextColor(Color.rgb(153, 255, 102));
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#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();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
AllStreaks.java:
public class AllStreaks extends AppCompatActivity {
public static ArrayList<Streak> streakList = new ArrayList<>();
private SharedPreferences prefs;
private SharedPreferences.Editor editor;
private ArrayList<Streak> allStreakList;
private TableLayout mTableLayout;
private TableRow mTableRow;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_all_streaks);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
/*
if (streakList == null){
Button streakButton = new Button(this);
streakButton.setText("Try again");
}
else{
for (int j = 0; j < streakList.size(); j++){
allStreakList.add(streakList.get(j));
}
}*/
prefs = getSharedPreferences("carter.streakly", MODE_PRIVATE);
editor = prefs.edit();
mTableLayout = (TableLayout) findViewById(R.id.all_streak_table);
int i = 0;
while (i < streakList.size()){
if (i % 2 == 0){
mTableRow = new TableRow(this);
mTableLayout.addView(mTableRow);
}
Button streakButton = new Button(this);
streakButton.setText(String.valueOf(streakList.get(i).getDaysKept()));
streakButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(AllStreaks.this, EnlargedActivity.class);
startActivity(intent);
}
});
mTableRow.addView(streakButton);
i++;
}
}
}

you cannot pass object directly.you have to parcelable or serialize it. but in parecelable is part of android where serialzation is part of java so i suggest you to use parcelable.
you can make model class to parcelable from this link if you dont want to code for parcelabel.
parcelable creator
you can achieve like this.
class Car implements Parcelable {
public int regId;
public String brand;
public String color;
public Car(Parcel source) {
regId = source.getInt();
brand = source.getString();
color = source.getString();
}
public Car(int regId, String brand, String color) {
this.regId = regId;
this.brand = brand;
this.color = color;
}
public int describeContents() {
return this.hashCode();
}
public void writeToParcel(Parcel dest, int flags) {
dest.writeInt(regId);
dest.writeString(brand);
dest.writeString(color);
}
public static final Parcelable.Creator CREATOR
= new Parcelable.Creator() {
public Car createFromParcel(Parcel in) {
return new Car(in);
}
public Car[] newArray(int size) {
return new Car[size];
}
};}
And you can pass it like below.
ArrayList carList = new ArrayList();
carList.add(new Car('1','Honda','Black');
carList.add(new Car('2','Toyota','Blue');
carList.add(new Car('3','Suzuki','Green');
Intent i = new Intent(getApplicationContext(), CarDetailActivity.class);
i.putParcelableArrayListExtra("cars", carList);
this.startActivity(i);
you can get it like below:
Intent i = this.getIntent();
ArrayList<Car> carList = (ArrayList<Car>)i.getParcelableArrayListExtra("cars");`

You need to use Parcelable or Serializable interface.
and the pass it with intent
Intent mIntent = new Intent(context, ResultActivity.class);
mIntent.putParcelableArrayListExtra("list", mArraylist);
startActivity(mIntent);
fetch it in ResultActivity
Bundle bundle = getIntent().getExtras();
mArraylist1 = bundle.getParcelableArrayList("list");
Check this thread for reference

Do this on your Streak class and try,
Streak implements Parcelable
Since your modal class has not serialized, it may not able to pass via bundle. You can do that by implementing the Parcelable interface.
Parcelable is an Android specific interface where you implement the
serialization yourself. It was created to be far more efficient that
Serializable, and to get around some problems with the default Java
serialization scheme.
Serializable is a standard Java interface. You simply mark a class
Serializable by implementing the interface, and Java will
automatically serialize it in certain situations.
Courtsy

Related

saving and getting spinner items with shared preferences

I have a problem with saving spinner items to shared preferences. By problem I mean I really don't know how to do it. It would be nice if someone could actually explain it to me if someone knows.Thanks in advance :)
so I have set my button 1 to open a dialog with spinner and in spinner i have 3 items (declared in strings.xml). I should use shared preferences to set spinner to item 1 :"-" by default, and if user selects item 2 "lang1" or "lang2" it should be saved in app. So that when i open app next time its on "lang1" or "lang2" depends on selection.
Everything else is working fine.
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
SharedPreferences sharedpreferences;
public static final String mypreference = "mypref";
int spinnerPosition;
public Button btnTrans, btnSelect,btnInput,btnCheck;
public TextView tv_title, tv_message;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnSelect= (Button) findViewById(R.id.btnLanguage);
btnInput = (Button) findViewById(R.id.btnInput);
btnTrans = (Button) findViewById(R.id.btnTranslate);
btnTrans.setOnClickListener((View.OnClickListener) this);
btnInput.setOnClickListener(this);
btnSelect.setOnClickListener(this);
Spinner lang_spinner = (Spinner) findViewById(R.id.lang_spinner);
}
public void onClick(View v)
{
int id=v.getId();
switch (id){
case R.id.btnLanguage:
AlertDialog.Builder mBuilder = new AlertDialog.Builder(MainActivity.this);
View mView = getLayoutInflater().inflate(R.layout.language_dialog, null);
mBuilder.setTitle("select language");
final Spinner mSpinner = (Spinner) mView.findViewById(R.id.lang_spinner);
final ArrayAdapter<String> adapter = new ArrayAdapter<String>(MainActivity.this,
android.R.layout.simple_spinner_item, getResources().getStringArray(R.array.lang_array));
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
mSpinner.setAdapter(adapter);
mSpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
SharedPreferences.Editor editor = sharedpreferences.edit();
//SELECTING LANGUAGE switch case (translate btn)-
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int position, long id) {
Object item = adapterView.getItemAtPosition(position);
if (item != null) {
switch (position) {
case 0:
item = "-";
btnTrans.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(getApplicationContext(), R.string.nista, Toast.LENGTH_LONG).show();
}
});
break;
case 1:
item = "lang1";
btnTrans.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(getApplicationContext(), R.string.hrvatski, Toast.LENGTH_LONG).show();
}
});
break;
case 2:
item = "lang2";
btnTrans.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(getApplicationContext(), R.string.english, Toast.LENGTH_LONG).show();
}
});
break;
}
}
//on selected save
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
//nothing selected "-"
}
});
I am rep is less then 50 so I am posting link here for shared preference
https://www.google.com/amp/s/www.geeksforgeeks.org/shared-preferences-in-android-with-examples/amp/
Get your Lang from spinner and store value in share preference.

How to save state of game

I am trying to get my app to save when closed down or if back button is pressed. I'd like for it to remember which boxes are checked and what the score is on.
I've tried looking through previous articles to save the checkbox state to shared preferences but it doesn't seem to do anything. I've tried at least 5 different ways that I've found on here but it either just crashes the app or does nothing at all.
This is the code I've got:
public class levelOneActivity extends AppCompatActivity {
TextView scoreTextView;
Button backButton;
ConstraintLayout pictureConstraint;
Button nextLevelButton;
ListView levelOneListView;
ArrayAdapter arrayAdapter;
int score;
public static final String PREFS_NAME = "MyPrefsFile";
// SharedPreferences sharedPrefs = context.getSharedPreferences("sharedPrefs", Context.MODE_PRIVATE);
public void backButton(View view) {
pictureConstraint.setVisibility(View.INVISIBLE);
}
public void nextLevelButton(View view) {
Log.i("info", "next level!");
Intent intent = new Intent(getApplicationContext(), levelTwoActivity.class);
startActivity(intent);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_level_one);
levelOneListView = findViewById(R.id.levelOneListView);
scoreTextView = findViewById(R.id.scoreTextView);
pictureConstraint = findViewById(R.id.pictureConstraint);
backButton = findViewById(R.id.backButton);
final ImageView imageView2 = findViewById(R.id.imageView2);
final TextView factTextView = findViewById(R.id.factTextView);
score = 0;
final ConstraintLayout levelFinishedConstraint = findViewById(R.id.finishedLevelConstraint);
nextLevelButton = findViewById(R.id.nextLevelButton);
final SharedPreferences sharedPreferences = this.getSharedPreferences("com.example.woodlandwanderer", Context.MODE_PRIVATE);
final String[] levelOneListList = new String[]{
"Daisy", "Rock", "Tree", "Dandelion", "Grass"
};
final int[] imageList = new int[]{
R.drawable.daisy, R.drawable.rock, R.drawable.tree, R.drawable.dandelion, R.drawable.grass
};
final String[] factList = new String[]{
"Daisies are cool", "Rocks are fun to throw!", "Trees have leaves!", "Dandelions are yellow", "Grass is green"
};
arrayAdapter = new ArrayAdapter(this, android.R.layout.simple_list_item_checked, levelOneListList);
levelOneListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> adapterView, View view, int i, long l) {
pictureConstraint.setVisibility(View.VISIBLE);
imageView2.setImageResource(imageList[i]);
factTextView.setText(factList[i]);
return true;
}
});
levelOneListView.setChoiceMode(AbsListView.CHOICE_MODE_MULTIPLE);
levelOneListView.setAdapter(arrayAdapter);
levelOneListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
Log.i("Info", "Clicked");
CheckedTextView checkedTextView = (CheckedTextView) view;
if (checkedTextView.isChecked()) {
if (score < 9) {
score++;
} else {
score++;
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
levelFinishedConstraint.setVisibility(View.VISIBLE);
}
}, 1000);
}
} else {
Log.i("Info", "Not checked");
score = score - 1;
}
scoreTextView.setText(Integer.toString(score) + "/10");
}
});
}
}
I would suggest you to come up with an xml-file in which you set your own tag for check or unchecked boxes. Whenever the user exits the programm or presses the back button, the last thing before the application shut down is saving the current state of the checked boxes and replace the old version.
Another way to save the current state would be the database. I would modify it so can even type in xml-style, or you just push the names of the checked boxes to your database. Always the last step before shutting the application down.

Update list view after navigating back to previous activity

Excuse my noobness. I just don't understand how to implement it to work with my code. What I'm doing is editing a name that's in a list view. When editing the name in "EditDeleteList" and get back to the previous activity (ListView) to see the name updated within the list view, nothing happens. I have to go out of the activity completely to see the change reflected. How do I get this to update? I implement an onActivityReult() method but then get this error message "java.lang.NullPointerException: Attempt to invoke interface method 'int java.util.List.size()' on a null object reference" so I removed it completely. How I could get the list view to update without getting that error message?
ListView.Java
public class ListView extends AppCompatActivity {
private static final String TAG = "ListView";
DatabaseHelper mDatabaseHelper;
Button btnAdd;
private EditText editText;
private android.widget.ListView listView;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_view);
mDatabaseHelper = new DatabaseHelper(this);
btnAdd = (Button) findViewById(R.id.btnAdd);
editText = (EditText) findViewById(R.id.editText);
listView = (android.widget.ListView) findViewById(R.id.lv);
ArrayList<String> list = getIntent().getStringArrayListExtra("myList");
android.widget.ListView lv = (android.widget.ListView) findViewById(R.id.lv);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, list);
lv.setAdapter(adapter);
//Takes user back to the main activity
ImageView ivBack = (ImageView) findViewById(R.id.ivBackArrow);
ivBack.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d(TAG, "onClick: pressed back arrow");
Intent intent = new Intent(ListView.this, MainActivity.class);
startActivity(intent);
}
});
btnAdd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String newEntry = editText.getText().toString();
if (editText.length() != 0) {
addData(newEntry);
editText.setText("");
} else {
toastMessage("you must put something in the text field");
}
}
});
populateListView();
}
public void addData(String newEntry) {
boolean insertData = mDatabaseHelper.addData(newEntry);
if (insertData) {
toastMessage("Successfully inserted");
recreate();
} else {
toastMessage("Whoops, something went wrong");
}
}
private void toastMessage(String message) {
Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
}
private void populateListView() {
Log.d(TAG, "populateListView: displaying data in the listview");
//get data and append to list
Cursor data = mDatabaseHelper.getData();
ArrayList<String> listData = new ArrayList<>();
while(data.moveToNext()) {
//get the value from the database in column 1
//set it to the arraylist
listData.add(data.getString(1));
}
//create arraylist and set it to the adapter
ListAdapter adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, listData);
listView.setAdapter(adapter);
//set onclick listen to edit activity
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
String name = adapterView.getItemAtPosition(position).toString();
Log.d(TAG, "onItemClick: you clicked on " + name);
Cursor data = mDatabaseHelper.getItemID(name); //get the id associated with that name
int itemID = -1;
while (data.moveToNext()) {
itemID = data.getInt(0);
}
if (itemID > -1) {
Log.d(TAG, "onItemID: the ID is: " + itemID);
Intent editScreenIntent = new Intent(ListView.this, EditDeleteList.class);
editScreenIntent.putExtra("id",itemID);
editScreenIntent.putExtra("name",name);
startActivity(editScreenIntent);
} else {
toastMessage("No ID found");
}
}
});
}
}
EditDeleteList.java
public class EditDeleteList extends AppCompatActivity {
private static final String TAG = "EditDeleteList";
DatabaseHelper mDatabaseHelper;
private ImageView ivDelete;
private ImageView ivApprove;
private EditText editHashtag;
private String selectedName;
private int selectedID;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_edit_delete);
mDatabaseHelper = new DatabaseHelper(this);
editHashtag = (EditText) findViewById(R.id.editHashtag);
ivDelete = (ImageView) findViewById(R.id.ivDelete);
ivApprove = (ImageView) findViewById(R.id.ivApprove);
//get the intent extra from the ListView activity
final Intent receivedIntent = getIntent();
//get item ID passed as an extra
selectedID = receivedIntent.getIntExtra("id", -1);
//get name passed as an extra
selectedName = receivedIntent.getStringExtra("name");
//set text field to selected item text
editHashtag.setText(selectedName);
ivApprove.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String item = editHashtag.getText().toString();
if (!item.equals(null)) {
mDatabaseHelper.updateName(item, selectedID, selectedName);
} else {
toastMessage("you must enter a #hashtag");
}
finish();
}
});
}
private void toastMessage(String message) {
Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
}
}
In the EditDeleteList.java I have an onClickListener that saves the changes and goes back to the previous activity by using finish();
ivApprove.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String item = editHashtag.getText().toString();
if (!item.equals(null)) {
mDatabaseHelper.updateName(item, selectedID, selectedName);
} else {
toastMessage("you must enter a #hashtag");
}
finish();
}
});
Notify the adapter in some part of the activity lifecycle.
OnCreate() should not run when you go back (this is the reason you have to completely recreate the activity to see the list updated) so you should use OnRestart/OnStart/OnResume to notify the adapter to check for new items.
Check this image

Syntax to complete shared preferences for number of clicks count

Hi I just need a little bit of a helping hand in completing this shared preferences code I have.
Currently I have a class where I stored in the relevant code for SharedPreferences:
public class SharedPreferencesManager {
private static final String APP_PREFS = "AppPrefsFile";
private static final String NUMBER_OF_CLICKS = "numberOfClicks";
private SharedPreferences sharedPrefs;
private static SharedPreferencesManager instance;
private SharedPreferencesManager(Context context) {
sharedPrefs =
context.getApplicationContext().getSharedPreferences(APP_PREFS, MODE_PRIVATE);
}
public static synchronized SharedPreferencesManager getInstance(Context context){
if(instance == null)
instance = new SharedPreferencesManager(context);
return instance;
}
public void storeClicks(int count)
{
SharedPreferences.Editor editor = sharedPrefs.edit();
editor.putInt(NUMBER_OF_CLICKS, count);
editor.apply();
}
public int getNumberOfClicks(){
int clicksNumber = sharedPrefs.getInt(NUMBER_OF_CLICKS, 0);
return clicksNumber;
}
}
I want to count the number of clicks for buttons jokes, poems and funnystories from the MainActivity class and the 'select another' button from the Content class. So if each button was clicked 4 times, the total click count should be 16.
I want to keep the number of clicks count even after the app is closed and re-open. It's just the syntax of the counting of the clicks I am unsure of. I think for main activity it is correct but I am unsure on how to store it for the Content class.
TO recap, count the number of clicks for all of those buttons mentioned and this number should be accessible and updated no matter which page the user is in.
Below is the Main Activity class:
public class MainActivity extends AppCompatActivity{
final Context context = this;
int clicksCount = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SharedPreferencesManager.getInstance(context).storeClicks(clicksCount);
Button jokesButton = findViewById(R.id.button_jokes);
Button poemsButton = findViewById(R.id.button_poems);
Button funnyStoriesButton = findViewById(R.id.button_funny_stories);
jokesButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
clicksCount++;
}
});
poemsButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
clicksCount++;
}
});
funnyStoriesButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
clicksCount++;
}
});
}
Below is Content class:
public class Content extends AppCompatActivity{
Button backButton;
Button selectAnotherButton;
TextView contentText;
Context context;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_content);
int clicksCount = SharedPreferencesManager.getInstance(context).getNumberOfClicks();
backButton = findViewById(R.id.button_back);
selectAnotherButton = findViewById(R.id.button_select_another);
selectAnotherButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
clicksCount++;
}
});
backButton.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick (View v){
finish();
}
});
}
}
Instead of having the two methods getNumberOfClicks() and storeClicks() in your SharedPreferencesManager, you could only have one like this:
public void increaseClickCount() {
int clickCount = sharedPrefs.getInt(NUMBER_OF_CLICKS, 0);
clickCount++;
SharedPreferences.Editor editor = sharedPrefs.edit();
editor.putInt(NUMBER_OF_CLICKS, clickCount);
editor.apply();
}
You call this on every click. No need for the activities to know about the clicks count.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final SharedPreferencesManager prefManager = SharedPreferencesManager.getInstance(context);
jokesButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
prefManager.increaseClickCount();
}
});
...
}
Also there's no need to store your context as a global variable because your activity is already a context itself, you can just use this or MainActivity.this for a context.

Android:How to set listener on multiple image buttons?

First of all, I'm using Andorid and Java only for a week and I'm a total newbie.
I need to know which button user clicked and then compare it with good or bad answer.
Here is the code
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.questions);
Integer[] flags = {
R.drawable.flag_albania,
R.drawable.flag_andorra,
R.drawable.flag_angola,
R.drawable.flag_avganistan,
};
String[] questions = {
"What is the flag of Albania",
"What is the flag of Andorra",
"What is the flag of Angola",
"What is the flag of Avganistan",
};
TextView tv = (TextView) findViewById(R.id.textView1);
int arraySize = flags.length;
Random rand = new Random();
ImageButton button1 = (ImageButton) findViewById(R.id.imageButton1);
int index = rand.nextInt(arraySize);
int questionIndex1 = index;
button1.setImageResource(flags[index]);
flags[index] = flags[--arraySize];
ImageButton button2 = (ImageButton) findViewById(R.id.imageButton2);
index = rand.nextInt(arraySize);
int questionIndex2 = index;
button2.setImageResource(flags[index]);
flags[index] = flags[--arraySize];
ImageButton button3 = (ImageButton) findViewById(R.id.imageButton3);
index = rand.nextInt(arraySize);
int questionIndex3 = index;
button3.setImageResource(flags[index]);
flags[index] = flags[--arraySize];
ImageButton button4 = (ImageButton) findViewById(R.id.imageButton4);
index = rand.nextInt(arraySize);
int questionIndex4 = index;
button4.setImageResource(flags[index]);
flags[index] = flags[--arraySize];
Integer[] question = {
questionIndex1,
questionIndex2,
questionIndex3,
questionIndex4
};
int questionArraySize = question.length;
int questionArray = rand.nextInt(questionArraySize);
tv.setText(questions[question[questionArray]]);
My idea is to compare questionIndex that is randomly selected to a button id but I really don't know how to implement it. Every help is appreciated.
Use this reduced code
ImageButton button1,button2,button3,button4;
ImageButton imagebuttons[]={ button1,button2,button3,button4};
int ids[]={R.id.imageButton1,R.id.imageButton2,R.id.imageButton3,R.id.imageButton4};
for(final int i=0;i<imagebuttons.length;i++)
{
imagebuttons[i]=(ImageButton) findViewById(ids[i]);
int index=rand.nextInt(arraySize);
imagebuttons[i].setImageResource(flags[index]);
flags[index] = flags[--arraySize];
indexes.put(i,index);
imagebuttons[i].setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if( questionArray==indexes.get(i))
{
}
}
});
I hope this will help you
Try out this way:
button1.setOnClickListener(onClickListener);
button2.setOnClickListener(onClickListener);
/**
* Common click listener
*/
OnClickListener onClickListener = new OnClickListener()
{
#Override
public void onClick(View p_v)
{
switch (p_v.getId())
{
case R.id.imageButton1:
//Your logic here.
break;
case R.id.imageButton2:
//Your logic here.
break;
}
}
}
Write below code
public class MainActivity extends Activity implements OnClickListener{
protected void onCreate(Bundle savedInstanceState) {
/// Your Above Code ///
tv.setText(questions[question[questionArray]]);
Imagebutton1.setOnClickListener(this);
Imagebutton2.setOnClickListener(this);
Imagebutton3.setOnClickListener(this);
Imagebutton4.setOnClickListener(this);
}
#Override
public void onClick(View v) {
if(v == Imagebutton1){
// Write Your Code Here
} else if(v == Imagebutton2){
// Write Your Code Here
} else if(v == Imagebutton3){
// Write Your Code Here
} else if(v == Imagebutton4){
// Write Your Code Here
}
}
}
You can do it this way:
First, make your activity implements onClick Listener:
public class MyActivity extends Activity implements View.OnClickListener{
Then set the action listeners to your buttons:
button1.setOnClickListener(this);
button2.setOnClickListener(this);
.....
then in the listener, check the id:
public void onClick(View v) {
switch(v.getId()){
case R.id.imageButton1:
break;
case R.id.imageButton2:
break;
....
}
}
You can do the it this way also. You have to use some int variables to keep the tag value of the button. And also you have to create a onClickListner for the button actions. Coding is as follow
public class MyActivity extends Activity{
//Define the Tag values for image buttons.
private static final int TAG_IMAGE_BTN_1 = 0;
private static final int TAG_IMAGE_BTN_2 = 1;
private static final int TAG_IMAGE_BTN_3 = 2;
private static final int TAG_IMAGE_BTN_4 = 3;
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
initActivity();
}
private void initActivity(){
//Initialize the image buttons via xml or from the code itself.
//Add the onClickListner_BTN_CLICK and the corresponding tag to the image button
imageBtn1.setTag(TAG_IMAGE_BTN_1);
imageBtn1.setOnClickListener(onClickListner_BTN_CLICK);
imageBtn2.setTag(TAG_IMAGE_BTN_2);
imageBtn2.setOnClickListener(onClickListner_BTN_CLICK);
.......................................................
.......................................................
}
OnClickListener onClickListner_BTN_CLICK = new OnClickListener(){
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
int iTag = (Integer)v.getTag();
switch (iTag) {
case TAG_IMAGE_BTN_1:
break;
case TAG_IMAGE_BTN_2:
break;
case TAG_IMAGE_BTN_3:
break;
case TAG_IMAGE_BTN_4:
break;
}
}
};
}
The advantages of using the tag values for capture the action,
1)If we use R.id....... then we have to change the value in switch case if we change it in the xml file
2)We can use only one onClickListner for every action in an activity.

Categories