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.
Related
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.
I am creating a simple tasklist app in Android Studios.
I have two activities as following (removed imports and package specifications):
MainActivity.java
public class MainActivity extends AppCompatActivity implements View.OnClickListener, AdapterView.OnItemClickListener {
EditText taskAdd;
Button add;
public ListView tasks;
public Integer pos = 0;
public ArrayList<String> taskArray;
public ArrayAdapter<String> adapter;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
taskAdd = findViewById(R.id.taskAdd);
add = findViewById(R.id.add);
tasks = findViewById(R.id.tasks);
taskArray = FileHelper.readData(this);
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, taskArray);
tasks.setAdapter(adapter);
add.setOnClickListener(this);
tasks.setOnItemClickListener(this);
}
#Override
public void onClick(View v) {
switch(v.getId()){
case R.id.add:
String entered = taskAdd.getText().toString();
if (entered != "" || entered != null || entered != "null") {
adapter.add(entered);
taskAdd.setText("");
FileHelper.writeData(taskArray, this);
Toast.makeText(this, "Task Added!", Toast.LENGTH_SHORT).show();
}
break;
}
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
pos = position;
Intent intent = new Intent(MainActivity.this, Pop.class);
startActivity(intent);
}
#Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
setIntent(intent);
processExtraData();
}
private void processExtraData(){
Bundle extras = getIntent().getExtras();
if (extras != null) {
int value = extras.getInt("Value");
if (value == 1) {
taskArray.remove(pos);
adapter.notifyDataSetChanged();
Toast.makeText(this, "Task Removed!", Toast.LENGTH_SHORT).show();
}
}
}
}
Pop.java (a popup)
public class Pop extends Activity implements View.OnClickListener {
Button deleteButton;
Button finishedButton;
Button timerButton;
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.popwindow);
deleteButton = findViewById(R.id.deleteButton);
DisplayMetrics dm = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dm);
int width = dm.widthPixels;
int height = dm.heightPixels;
getWindow().setLayout((int)(width*0.5),(int)(height*0.5));
deleteButton.setOnClickListener(this);
}
#Override
public void onClick(View v) {
Intent i = new Intent(this, MainActivity.class);
i.putExtra("Value", 1);
startActivity(i);
}
}
After I click deleteButton in Pop.java, processExtraData in MainActivity.java is supposed to run. The Toast does appear, but the selected object in the ListView is not deleted. No errors are thrown either. In addition, using Log.d to check the size of taskArray confirmed that this is not just a graphical issue. Why is this the case, and how should I go about fixing it?
Thank you for replying in advance.
The issue is that you are using an object reference instead of a primitive data type, and so when you are calling taskArray.remove(pos), it is looking for pos the object rather than its denoted integer value.
Instead of:
taskArray.remove(pos);
try:
taskArray.remove(pos.intValue());
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
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
I am using checkbox in an listview,while click the checkbox it has to select the content in the row.But is not taking taking the current position.But is not select the current positon first and second time is not selecting anything.Is not selecting the current position,Its selecting randomly.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_item2);
lv =(ListView)findViewById(R.id.list);
mDbHelper = new GinfyDbAdapter(this);
share = (Button)findViewById(R.id.btnget);
btnadd1 = (Button)findViewById(R.id.btnadd);
lv = getListView();
share.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v) {
StringBuilder result = new StringBuilder();
for(int i=0;i<mCheckStates.size();i++)
{
if(mCheckStates.get(i)==true)
{
result.append("Title:");
result.append(bb.get(i));
result.append("\n");
result.append("Content:");
result.append(aa.get(i));
result.append("\n");
}
}
// }
showAlertView(result.toString().trim());
}
});
btnadd1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
createProject();
}
});
mDbHelper.open();
fillData();
registerForContextMenu(getListView());
}
#SuppressLint("NewApi")
#SuppressWarnings("deprecation")
private void fillData() {
mDbHelper.open();
Cursor projectsCursor = mDbHelper.fetchAllProjects();
int count = projectsCursor.getCount();
Log.i(".................",""+count);
if (projectsCursor.moveToFirst()) {
do {
int col1 = projectsCursor.getColumnIndex("title");
String title = projectsCursor.getString(col1 );
bb.add(title);
int col2 = projectsCursor.getColumnIndex("content");
String content = projectsCursor.getString(col2 );
aa.add(content);
} while (projectsCursor.moveToNext());
}
//startManagingCursor(projectsCursor);
// Create an array to specify the fields we want to display in the list (only TITLE)
String[] from = new String[]{GinfyDbAdapter.CATEGORY_COLUMN_TITLE,GinfyDbAdapter.CATEGORY_COLUMN_CONTENT,GinfyDbAdapter.CATEGORY_COLUMN_DATE};
int[] to = new int[]{R.id.text22,R.id.text11,R.id.date};
dataAdapter = new CustomAdapter (YourPrayerActivity .this, R.layout.row2, projectsCursor, from, to);
setListAdapter(dataAdapter);
EditText myFilter = (EditText) findViewById(R.id.myFilter);
myFilter.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
}
public void beforeTextChanged(CharSequence s, int start,
int count, int after) {
}
public void onTextChanged(CharSequence s, int start,
int before, int count) {
dataAdapter.getFilter().filter(s.toString());
}
});
dataAdapter.setFilterQueryProvider(new FilterQueryProvider() {
public Cursor runQuery(CharSequence constraint) {
return mDbHelper.fetchProjectByName(constraint.toString());
}
});
tts = new TextToSpeech(this, this);
final ListView lv = getListView();
txtText = (TextView) findViewById(R.id.text11);
lv.setTextFilterEnabled(true);
}
#Override
public void onDestroy() {
// Don't forget to shutdown tts!
if (tts != null) {
tts.stop();
tts.shutdown();
}
super.onDestroy();
}
public void onInit(int status) {
if (status == TextToSpeech.SUCCESS) {
int result = tts.setLanguage(Locale.US);
if (result == TextToSpeech.LANG_MISSING_DATA
|| result == TextToSpeech.LANG_NOT_SUPPORTED) {
Log.e("TTS", "This Language is not supported");
} else {
//btnaudioprayer.setEnabled(true);
speakOut();
}
} else {
Log.e("TTS", "Initilization Failed!");
}
}
private void createProject() {
Intent i = new Intent(this, AddyourprayerActivity.class);
startActivityForResult(i, ACTIVITY_CREATE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
fillData();
}
private void speakOut() {
// String text = txtText.getText().toString();
// String text = "Android speech";
tts.speak(typed, TextToSpeech.QUEUE_FLUSH, null);
}
class CustomAdapter extends SimpleCursorAdapter implements CompoundButton.OnCheckedChangeListener {
private LayoutInflater mInflater;
private ListView lv;
#SuppressWarnings("deprecation")
public CustomAdapter(Context context, int layout, Cursor c, String[] from, int[] to)
{
super(context, layout, c, from, to);
mInflater= LayoutInflater.from(context);
mCheckStates = new SparseBooleanArray(c.getCount());
}
#Override
public void bindView(View view, Context context, final Cursor cursor){
if (view != null) {
int row_id = cursor.getColumnIndex("_id"); //Your row id (might need to replace)
TextView tv = (TextView) view.findViewById(R.id.text22);
final TextView tv1 = (TextView) view.findViewById(R.id.text11);
TextView tv2 = (TextView) view.findViewById(R.id.date);
CheckBox cb = (CheckBox) view.findViewById(R.id.checkbox);
int col1 = cursor.getColumnIndex("title");
final String title = cursor.getString(col1 );
int col2 = cursor.getColumnIndex("content");
final String content = cursor.getString(col2 );
int col3 = cursor.getColumnIndex("date");
final String date = cursor.getString(col3);
cb.setTag(cursor.getPosition());
cb.setChecked(mCheckStates.get(cursor.getPosition()+1, false));
cb.setOnCheckedChangeListener(this);
tv.setText( title);
tv1.setText( content);
tv2.setText(date);
ImageButton button = (ImageButton) view.findViewById(R.id.sms1);
button.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v){
StringBuffer sb2 = new StringBuffer();
sb2.append("Title:");
sb2.append(Html.fromHtml(title));
sb2.append(",Content:");
sb2.append(Html.fromHtml(content));
sb2.append("\n");
String strContactList1 = (sb2.toString().trim());
sendsmsdata(strContactList1);
}
});
ImageButton button1 = (ImageButton) view.findViewById(R.id.mail1);
button1.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v){
StringBuffer sb3 = new StringBuffer();
sb3.append("Title:");
sb3.append(Html.fromHtml(title));
sb3.append(",Content:");
sb3.append(Html.fromHtml(content));
sb3.append("\n");
String strContactList2 = (sb3.toString().trim());
sendmaildata(strContactList2);
}
});
ImageButton button2 = (ImageButton) view.findViewById(R.id.btnaudioprayer1);
button2.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v){
//ADD STUFF HERE you know which row is clicked. and which button
typed = content;
speakOut();
}
});
}
}
#Override
public View newView(Context context, Cursor cursor, ViewGroup parent){
LayoutInflater inflater = LayoutInflater.from(context);
View v = inflater.inflate(R.layout.row2, parent, false);
bindView(v,context,cursor);
return v;
}
public boolean isChecked(int position) {
return mCheckStates.get(position, false);
}
public void setChecked(int position, boolean isChecked) {
mCheckStates.put(position, isChecked);
}
public void toggle(int position) {
setChecked(position, !isChecked(position));
}
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
// TODO Auto-generated method stub
mCheckStates.put((Integer) buttonView.getTag(), isChecked);
}
while click the checkbox,and then after have to click share button it will shows sms or email,if we click sms,in that content what are the things we checked that content has to be there in msg content.
I checked in debug,if i select the first or second row its taking or otherwise if i selected thirdrow first its not taking the content.
Have a count variable as a class member
int count;
Then in fillData
count = projectsCursor.getCount();
SO when you click on a button
StringBuilder result = new StringBuilder();
if(count>0) // check if count is greater than o
// count can be 0 if you don't select any check box
{
for(int i=0;i<count;i++)
{Log.i("checked content Inside on click of share ",""+aa.get(i));
if(mCheckStates.get(i)==true)
{
result.append("Title:");
result.append(bb.get(i));
result.append("\n");
result.append("Content:");
result.append(aa.get(i));
result.append("\n");
}
}
}
You are using a SparseBoolean array which is true for row that you check. Then you retrieve the data based on the checked items.
Here's the sample from which i picked upon
https://groups.google.com/forum/#!topic/android-developers/No0LrgJ6q2M
What you were doing is you were not going through the whole list of items to check if the checkbox was checked.
for(int i=0;i<mCheckStates.size();i++) // this was the problem
if only two items are checked you will get the first two.
To avoid the problems with CheckBoxes in a ListView you can take a Boolean array initialized false in the beginning and then making true the corresponding position in the array where checkbox is checked in the ListView.Please refer to this demo here:
Android checkbox multiselected issue
Why not you use arrayAdapter?
Have a look at this link. Hope it helps you out.
< http://androidcocktail.blogspot.in/2012/04/adding-checkboxes-to-custom-listview-in.html>
As the behavior or getview() method that it recreate view everytime whenever you scroll, so have to maintain position using setTag & getTag, even store selected checked into array with proper position.
Try below example, you can replace toggle button with check box.
Getview Method Wierd in Listview