Saving Listview data - java

I have an issue where I have a listview, go to another activity to attach uservalues which than implements those values to the listview. However, if I go back to that activity and attach a new set of values, when I return to my listview activity, the new values are implemented but the old values have been removed. Would an sqlite database solve this problem? Or does it have something to do with the actual list being recreate?
ListActivity.java
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import com.personalproject.peter.timerapp.TestingForAlarmData.TestAlarm;
import java.util.ArrayList;
import java.util.List;
public class ListOfAlarms extends ActionBarActivity {
private static final int RESULT = 1000;
List<TestAlarm> alarms = new ArrayList<>();
String title;
int totalTime;
ListView listOfAlarms;
ArrayAdapter<TestAlarm> alarmArrayAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_of_alarms);
final TextView emptyViewForList = (TextView) findViewById(R.id.emptyTextViewForList);
listOfAlarms = (ListView) findViewById(R.id.listView);
alarmArrayAdapter = new ArrayAdapter<>(this,android.R.layout.simple_list_item_1, alarms);
listOfAlarms.setAdapter(alarmArrayAdapter);
// if(listOfAlarms.getCount() <= 0){
// emptyViewForList.setText("No Alarms Currently Available");
// listOfAlarms.setEmptyView(emptyViewForList);
// }
listOfAlarms.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
alarms.get(position);
Intent clockDownActivity = new Intent(ListOfAlarms.this, CountDownAct.class);
clockDownActivity.putExtra("Title", title);
clockDownActivity.putExtra("totalTime", totalTime);
startActivity(clockDownActivity);
}
});
}
#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_list_of_alarms, 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);
}
public void goToFillOut(View view) {
Intent goingToFillOut = new Intent(this, Test.class);
startActivityForResult(goingToFillOut, RESULT);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode == RESULT && resultCode == RESULT_OK){
title = data.getStringExtra("title");
totalTime = data.getIntExtra("totalTime", 0);
alarms.add(new TestAlarm(title, totalTime));
alarmArrayAdapter.notifyDataSetChanged();
}
}
}
SecondActivity
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class Test extends ActionBarActivity {
private static final String LOGTAG = "Test.class";
private static final long timeInterval = 1000;
private Button complete;
private EditText titleEditText;
private EditText hourEditText;
private EditText minuteEditText;
private EditText secondEditText;
public static int hour;
public static int minute;
public static int second;
public static String title;
public int actualTimeFiniliazedInMilliSeconds;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
titleEditText = (EditText) findViewById(R.id.titleEditText);
hourEditText = (EditText) findViewById(R.id.hourEditText);
minuteEditText = (EditText) findViewById(R.id.minuteEditText);
secondEditText = (EditText) findViewById(R.id.secondEditText);
complete = (Button) findViewById(R.id.completeButton);
}
#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);
}
public void saveTimer(View view) {
if(titleEditText.getText().toString().isEmpty() || hourEditText.getText().toString().isEmpty()
|| minuteEditText.getText().toString().isEmpty() || secondEditText.getText().toString().isEmpty()) {
Toast.makeText(this, "Oops you forgot one", Toast.LENGTH_LONG).show();
return;
}
// complete.setVisibility(View.GONE);
title = titleEditText.getText().toString();
hour = Integer.parseInt(hourEditText.getText().toString().trim());
minute = Integer.parseInt(minuteEditText.getText().toString().trim());
second = Integer.parseInt(secondEditText.getText().toString().trim());
hour *= 3600000;
minute *= 60000;
second *= 1000;
actualTimeFiniliazedInMilliSeconds = hour + minute + second;
Intent intent = new Intent(Test.this, ListOfAlarms.class);
intent.putExtra("title", title);
intent.putExtra("totalTime", actualTimeFiniliazedInMilliSeconds);
setResult(RESULT_OK, intent);
finish();
}
}
Alarm.java
public class TestAlarm {
public String title;
public int totalTime;
public TestAlarm (String title, int totalTime) {
this.title = title;
this.totalTime = totalTime;
}
#Override
public String toString() {
return title;
}
}

Simply try the following steps,don't need to use SqliteDB in this situation.
Create a Singleton class
Eg :
public class Singleton {
private static Singleton uniqInstance;
private List<TestAlarm> mAlarms = new ArrayList<>();
private Singleton() {
}
public static synchronized Singleton getInstance() {
if (uniqInstance == null) {
uniqInstance = new Singleton();
}
return uniqInstance;
}
public void setAllarms(List<TestAlarm> alarms){
this.mAlarms = alarms;
}
public List<TestAlarm> getAllarms(){
return this.mAlarms;
}
}
Save the allarms on the singleton class when navigating to another activity
listOfAlarms.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Singleton .getInstance().setAllarms(alarms); // Save the Collection
alarms.get(position);
Intent clockDownActivity = new Intent(ListOfAlarms.this, CountDownAct.class);
clockDownActivity.putExtra("Title", title);
clockDownActivity.putExtra("totalTime", totalTime);
startActivity(clockDownActivity);
}
});
on the onActivityResult retrieve the saved collection from singleton class
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode == RESULT && resultCode == RESULT_OK){
title = data.getStringExtra("title");
totalTime = data.getIntExtra("totalTime", 0);
Singleton.getInstance().getAllarms().add(new TestAlarm(title, totalTime));
this.alarms = Singleton.getInstance().getAllarms();
alarmArrayAdapter.notifyDataSetChanged();
}
}

What is happening is that when you leave and come back to the activity, Android is recreating the activity and listview. So you need some way to save the data over this change.
Using a sqlite database would solve the problem, since the databse would be permanent storage, and would save the information long term (for example, if the user shuts off the phone).
Another solution would be to implement onSaveInstanceState and onRestoreInstanceState, which will save information over changing activities (or orientation). If they shut off the phone the information would be lost.
From your question it doesn't sound like you need to keep information really long term, and implementing onSaveInstanceState is less work than sqlite.

You are creating a new instance of the Activity with
Intent intent = new Intent(Test.this, ListOfAlarms.class);
So everything is recreated.
To avoid this, you need to use an empty constructor when creating the Intent that will be sent back to the starting activity.
Intent intent = new Intent(); // this should be empty
intent.putExtra("title", title);
intent.putExtra("totalTime", actualTimeFiniliazedInMilliSeconds);
setResult(RESULT_OK, intent);
finish();
See Going back to previous activity with different Intent value
and
The documentation

Related

Referencing TextViews from Activity in Service and Vice versa

I am working on an Android app with a steadily growing Code basis; the aim of the app is to scan and process QR Codes and Barcodes on Handheld Devices for Storages (not Smartphones). It hast two Activities that contain major parts of the programmatical logic; hence, I want to store major parts of the Code that contains the Functionality for processing the Scanner input in an external Service, called Scanner Service, implement the methods there and use the methods in other Activites;
however, I have a major issue with the use of Context, getApplicationContext() and the reference of the Activity in the Service and vice versa; although I think I have referenced and initialised the Textviews from the Activity in the Service, the app keeps on crashing with the following error message:
AndroidRuntime: Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.app.Activity.findViewById(int)' on a null object reference
at com.xxxx.ScanService.<clinit>(ScanService.java:16)
I know what it means, but I donĀ“t know how I could access the View
private static TextView content = (TextView) a.findViewById(R.id.content_detail);
in such a way that I can use it in the Service and in the Activity and the app stops crashing.
Therefore, any hints or help would be very much appreciated, thank you in advance.
The MainDetailActivity:
package com.example.xxx_app;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.View;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.recyclerview.widget.RecyclerView;
import android.view.MenuItem;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.PopupMenu;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import static com.xxx.ScanService.*;
import static com.xxx.SimpleItemRecyclerViewAdapter.TAGG;
/**
* An activity representing a single Main detail screen. This
* activity is only used on narrow width devices. On tablet-size devices,
* item details are presented side-by-side with a list of items
* in a {#link MainListActivity}.
*/
public class MainDetailActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener,
PopupMenu.OnMenuItemClickListener {
Context context;
private RecyclerView recyclerView;
private RecyclerviewAdapter recyclerviewAdapter;
private RecyclerTouchListener touchListener;
private ListView listView;
public TextView textView4;
public String code;
public static final String TAG = "Barcode ist:" ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_detail);
context = this;
//TextView headerView = findViewById(R.id.txt1);
Spinner spinner = (Spinner) findViewById(R.id.spinner);
EditText editBarcode = (EditText) findViewById(R.id.editText);
TextView content = (TextView) findViewById(R.id.content_detail);
TextView editTextNumber = findViewById(R.id.editTextNumber);
Button addBooking = findViewById(R.id.button);
Button removeBooking = findViewById(R.id.button2);
removeBooking.setEnabled(false);
spinner.setOnItemSelectedListener(this);
//String selectedItem = spinner.getSelectedItem().toString();
// Create an ArrayAdapter using the string array and a default spinner layout
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
R.array.mockdata, android.R.layout.simple_spinner_item);
// Specify the layout to use when the list of choices appears
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// Apply the adapter to the spinner
spinner.setAdapter(adapter);
String scannedCode = getIntent().getStringExtra("scannedCode");
Log.d(TAG, "scannedCode" + scannedCode);
if (scannedCode != null && (content.getText().toString().equals(""))) {
content.setText(scannedCode);
}
Button btn = findViewById(R.id.imageView4);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
PopupMenu popup = new PopupMenu(MainDetailActivity.this, v);
popup.setOnMenuItemClickListener(MainDetailActivity.this);
popup.inflate(R.menu.popup_menu);
popup.show();
}
});
editBarcode.setOnKeyListener(new View.OnKeyListener() {
#Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
// TODO Auto-generated method stub
String code = editBarcode.getText().toString();
if (code.matches("")) //{ if(code.trim().isEmpty())
//|| editBarcode.getText().toString() > 100 )
{
Log.d(TAG, "Code ist leer");
}
if (keyCode == KeyEvent.KEYCODE_ENTER && code.length() > 0) {
editBarcode.setText("");
ScanService.checkEnteredCode(code);
return true;
}
return false;
}
});
recyclerView = findViewById(R.id.recyclerview);
recyclerviewAdapter = new RecyclerviewAdapter(this);
Intent newIntent = getIntent();
String receivedPalNo = newIntent.getStringExtra("palNo");
String receivedNo = newIntent.getStringExtra("no");
String receivedType = newIntent.getStringExtra("type");
String receivedRack = newIntent.getStringExtra("rack");
String receivedCountItems = newIntent.getStringExtra("count_items");
content.setText(receivedCountItems);
RestClient.getPaletteItems(getApplicationContext(),recyclerviewAdapter,receivedPalNo);
Log.d(TAGG,"Intent 1" + receivedPalNo);
Log.d(TAGG, "Intent 2" + receivedNo);
Log.d(TAGG, "Intent 3" + receivedType);
Log.d(TAGG,"Intent 4" + receivedRack);
Log.d(TAGG, "Intent 5" + receivedCountItems);
final ArrayList<Items> itemList = new ArrayList<>();
/*
Items[] items = new Items(12345,123456, 200, 500);
itemList.add(items);*/
recyclerviewAdapter.setItemList((ArrayList<Items>) itemList);
recyclerView.setAdapter(recyclerviewAdapter);
touchListener = new RecyclerTouchListener(this,recyclerView);
RecyclerviewAdapter finalRecyclerviewAdapter = recyclerviewAdapter;
touchListener
.setClickable(new RecyclerTouchListener.OnRowClickListener() {
#Override
public void onRowClicked(int position) {
//Toast.makeText(getApplicationContext(),itemList.get(position), Toast.LENGTH_SHORT).show();
}
#Override
public void onIndependentViewClicked(int independentViewID, int position) {
}
})
.setSwipeOptionViews(R.id.delete_task,R.id.edit_task)
.setSwipeable(R.id.rowFG, R.id.rowBG, new RecyclerTouchListener.OnSwipeOptionsClickListener() {
#Override
public void onSwipeOptionClicked(int viewID, int position) {
switch (viewID){
case R.id.delete_task:
itemList.remove(position);
finalRecyclerviewAdapter.setItemList(itemList);
break;
case R.id.edit_task:
Toast.makeText(getApplicationContext(),"Edit Not Available",Toast.LENGTH_SHORT).show();
break;
}
}
});
recyclerView.addOnItemTouchListener(touchListener);
class StableArrayAdapter extends ArrayAdapter<String> {
HashMap<String, Integer> mIdMap = new HashMap<String, Integer>();
public StableArrayAdapter(Context context, int textViewResourceId,
List<String> objects) {
super(context, textViewResourceId, objects);
for (int i = 0; i < objects.size(); ++i) {
mIdMap.put(objects.get(i), i);
}
}
#Override
public long getItemId(int position) {
String item = getItem(position);
return mIdMap.get(item);
}
#Override
public boolean hasStableIds() {
return true;
}
}
// savedInstanceState is non-null when there is fragment state
// saved from previous configurations of this activity
// (e.g. when rotating the screen from portrait to landscape).
// In this case, the fragment will automatically be re-added
// to its container so we don"t need to manually add it.
// For more information, see the Fragments API guide at:
//
// http://developer.android.com/guide/components/fragments.html
//
String text = getIntent().getStringExtra("palNo");
//headerView.setText(text);
if (receivedType != null && receivedType.equals("FE")) {
ImageView mImgView = findViewById(R.id.id_col_code);
mImgView.setBackgroundResource(R.drawable.backgroun_blue);
}
if (receivedType != null && receivedType.equals("UFE")) {
ImageView mImgView = findViewById(R.id.id_col_code);
mImgView.setBackgroundResource(R.drawable.backgroun_yellow);
}
}
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public boolean onMenuItemClick(MenuItem item) {
Toast.makeText(this, "Selected Item: " +item.getTitle(), Toast.LENGTH_SHORT).show();
switch (item.getItemId()) {
case R.id.search_item:
// do your code
return true;
case R.id.upload_item:
// do your code
return true;
case R.id.copy_item:
// do your code
return true;
/* case R.id.print_item:
// do your code
return true;*/
case R.id.share_item:
// do your code
return true;
/*case R.id.bookmark_item:
// do your code
return true;*/
default:
return false;
}
}
public void newDialog(Activity activity) {
final Dialog dialog = new Dialog(activity);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setCancelable(true);
dialog.setContentView(R.layout.sortiment_layout);
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
Button okButton = dialog.findViewById(R.id.ok);
okButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Toast.makeText(getApplicationContext(),"Ok" ,Toast.LENGTH_SHORT).show();
dialog.dismiss();
}
});
Button cancelButton = dialog.findViewById(R.id.cancel);
cancelButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Toast.makeText(getApplicationContext(),"Abbrechen" ,Toast.LENGTH_SHORT).show();
dialog.cancel();
}
});
dialog.show();
}
public void showDialog(Activity activity) {
final Dialog dialog = new Dialog(activity);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setCancelable(true);
dialog.setContentView(R.layout.newcustom_layout);
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
Button okButton = dialog.findViewById(R.id.ok);
okButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Toast.makeText(getApplicationContext(),"Ok" ,Toast.LENGTH_SHORT).show();
dialog.dismiss();
}
});
dialog.show();
}
public void onItemSelected(AdapterView<?> parent, View view,
int pos, long id) {
// An item was selected. You can retrieve the selected item using
// parent.getItemAtPosition(pos)
}
public void onNothingSelected(AdapterView<?> parent) {
// Another interface callback
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == android.R.id.home) {
// This ID represents the Home or Up button. In the case of this
// activity, the Up button is shown. For
// more details, see the Navigation pattern on Android Design:
//
// http://developer.android.com/design/patterns/navigation.html#up-vs-back
//
navigateUpTo(new Intent(this, MainListActivity.class));
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onResume() {
super.onResume();
recyclerView.addOnItemTouchListener(touchListener);
}
#Override
public void onPointerCaptureChanged(boolean hasCapture) {
}
}
The ScanService Class:
package com.example.xxx;
import android.app.Activity;
import android.content.Context;
import android.util.Log;
import android.widget.TextView;
public class ScanService {
private static final String TAG = "Scan Service Tag";
private static Context mContext;
private static Activity a = (MainDetailActivity)mContext;
private static TextView content = (TextView)
a.findViewById(R.id.content_detail);
private static TextView editTextNumber = (TextView)
a.findViewById(R.id.editTextNumber);
public ScanService (Context mContext) {
this.mContext = mContext;
}
public static void checkEnteredCode(String code, Activity a) {
content.setText("");
//PSP-H1-EA-F3
if
(code.matches("PSP-\\p{Upper}\\d\\p{Punct}\\p{Upper}\\" +
"p{Upper}\\p{Punct}\\p{Upper}\\p{Digit}")) {
content.setText("");
content.setText(code);
Log.d(TAG, "xxx");
}
if (code.matches("LF-[0-9]*")) {
///LF-(\d+)/gi
content.setText("");
content.setText(code);
Log.d(TAG, "xxx");
}
if (code.matches("PAL-[0-9][0-9][0-9]")) {
content.setText("");
content.setText(code);
Log.d(TAG, "xxx");
}
if (code.matches("P-[0-9][0-9][0-9]")) {
content.setText("");
content.setText(code);
Log.d(TAG, "Palette");
}
if (code.matches("[0-9][0-9][0-9][0-9].[0-9][0-9].+DB")) {
if(editTextNumber == null) {
Log.d(TAG, "xxx");
}
else {
editTextNumber.setText(code);
Log.d(TAG, "xxx");
}
Log.d(TAG, "xxx");
}
if (code.matches("[0-9A-Z]*[0-9]*")) {
//editBarcode.setText("");
//editBarcode.setText(keyCode);
Log.d(TAG, "xxx");
}
if (code.matches("\\d{13}")) {
//newDialog(MainDetailActivity.this);
//editBarcode.setText("");
//editBarcode.setText(keyCode);
if(editTextNumber == null) {
Log.d(TAG, "xxx");
}
else {
editTextNumber.setText(code);
Log.d(TAG, "xxx");
}
Log.d(TAG, "xxx");
}
else {
Log.d(TAG, "xxx");
};
//editBarcode.setText("");
//editBarcode.setText(code);
/* String code = editBarcode.getText().toString();
if (code.matches("")) //{ if(code.trim().isEmpty())
//|| editBarcode.getText().toString() > 100 )
{
Log.d(TAG, "xxx");
}
//}
checkEnteredCode(code);
//editBarcode.setText("");
return Boolean.parseBoolean(code);*/
Log.d(TAG, code);
}
public static void checkEnteredCode(String code) {
}
}
You cannot access any Views from a Service! Views belong to the Activity. This is the wrong application architecture. A Service performs background processing (file I/O, network I/O, computation, etc.). The Activity is responsible for interacting with the user (inputs, display, etc.). If your Service wants to put data on the screen, you've broken the division of responsibilities. Your Service should simply notify your Activity (or any other component that is interested) when data has changed, and the Activity can then update the View itself. You can share data between the Service and your other components in a number of ways, including: event bus, publish/subscribe, shared preferences, broadcast Intents, SQLite database, etc.

Why was there a run error with some functions?

MainActivity mActivity = new MainActivity();
mActivity.countRecords();
The Way I Used to call function countRecords() Which it was inside OnClickListenerCreateStudent class But I found the message when the button is pressed but with this a way no problems
((MainActivity)context).countRecords(); What is the difference between them now ?
package com.example.train1;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button buttonCreateLocation = (Button) findViewById(R.id.buttonCreateStudent);
buttonCreateLocation.setOnClickListener(new OnClickListenerCreateStudent());
countRecords();
}
public void countRecords() {
int recordCount = new TableControllerStudent(this).count();
TextView textViewRecordCount = (TextView) findViewById(R.id.textViewRecordCount);
textViewRecordCount.setText(recordCount + " records found.");
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
package com.example.train1;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import android.app.Activity;
public class OnClickListenerCreateStudent implements View.OnClickListener {
//MainActivity M_activity;
//MainActivity mActivity// = new MainActivity();
#Override
public void onClick(View view) {
//M_activity = new MainActivity();
final Context context = view.getContext();
LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View formElementsView = inflater.inflate(R.layout.student_input_form, null, false);
final EditText editTextStudentFirstname = (EditText) formElementsView.findViewById(R.id.editTextStudentFirstname);
final EditText editTextStudentEmail = (EditText) formElementsView.findViewById(R.id.editTextStudentEmail);
new AlertDialog.Builder(context).setView(formElementsView).setTitle("Create Student")
.setPositiveButton("Add",
new DialogInterface.OnClickListener() {
// countRecords();
public void onClick(DialogInterface dialog, int id) {
String studentFirstname = editTextStudentFirstname.getText().toString();
String studentEmail = editTextStudentEmail.getText().toString();
ObjectStudent objectStudent = new ObjectStudent();
objectStudent.firstname= studentFirstname;
objectStudent.email= studentEmail;
// call to table controller stud and put objectData
boolean createSuccessful = new TableControllerStudent(context).create(objectStudent);
if(createSuccessful){
Toast.makeText(context, "Student information was saved.", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(context, "Unable to save student information.", Toast.LENGTH_SHORT).show();
}
((MainActivity)context).countRecords();
MainActivity mActivity = new MainActivity();
mActivity.countRecords();
//((MainActivity)).
dialog.cancel();
}
}).show();
// Toast.makeText(context," "+context , Toast.LENGTH_LONG).show();
}
public class ObjectStudent {
int id;
String firstname;
String email;
public ObjectStudent(){
}
}
// class End
}
Never create your activities with the constructor, they're bound to not be initialized correctly sooner or later.
Create the Activity via the Intent, as in the docs:
Intent intent = new Intent(this, DisplayMessageActivity.class);

Trouble updating listview data

I have an application that populates a ListView with user input data from another Activity ; however, whenever I enter that data into the second Activity then return to the ListView activity, I see it populated with the values I entered. But, if I return to the second activity again, enter the values, and go back to the ListView activity, I see the new values updated but the old ones have disappeared.
Now, I don't know if I'm not updating the listview correctly or if I need to use SQLite databases to store this data or shared preferences in order to update the listview to new data while containing the previous information.
Thanks for any help.
ListActivity.java
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import com.personalproject.peter.timerapp.TestingForAlarmData.TestAlarm;
import java.util.ArrayList;
import java.util.List;
public class ListOfAlarms extends ActionBarActivity {
private static final int RESULT = 1000;
List<TestAlarm> alarms = new ArrayList<>();
String title;
int totalTime;
ListView listOfAlarms;
ArrayAdapter<TestAlarm> alarmArrayAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_of_alarms);
final TextView emptyViewForList = (TextView) findViewById(R.id.emptyTextViewForList);
listOfAlarms = (ListView) findViewById(R.id.listView);
alarmArrayAdapter = new ArrayAdapter<>(this,android.R.layout.simple_list_item_1, alarms);
listOfAlarms.setAdapter(alarmArrayAdapter);
// if(listOfAlarms.getCount() <= 0){
// emptyViewForList.setText("No Alarms Currently Available");
// listOfAlarms.setEmptyView(emptyViewForList);
// }
listOfAlarms.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
alarms.get(position);
Intent clockDownActivity = new Intent(ListOfAlarms.this, CountDownAct.class);
clockDownActivity.putExtra("Title", title);
clockDownActivity.putExtra("totalTime", totalTime);
startActivity(clockDownActivity);
}
});
}
#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_list_of_alarms, 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);
}
public void goToFillOut(View view) {
Intent goingToFillOut = new Intent(this, Test.class);
startActivityForResult(goingToFillOut, RESULT);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode == RESULT && resultCode == RESULT_OK){
title = data.getStringExtra("title");
totalTime = data.getIntExtra("totalTime", 0);
alarms.add(new TestAlarm(title, totalTime));
alarmArrayAdapter.notifyDataSetChanged();
}
}
}
SecondActivity
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class Test extends ActionBarActivity {
private static final String LOGTAG = "Test.class";
private static final long timeInterval = 1000;
private Button complete;
private EditText titleEditText;
private EditText hourEditText;
private EditText minuteEditText;
private EditText secondEditText;
public static int hour;
public static int minute;
public static int second;
public static String title;
public int actualTimeFiniliazedInMilliSeconds;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
titleEditText = (EditText) findViewById(R.id.titleEditText);
hourEditText = (EditText) findViewById(R.id.hourEditText);
minuteEditText = (EditText) findViewById(R.id.minuteEditText);
secondEditText = (EditText) findViewById(R.id.secondEditText);
complete = (Button) findViewById(R.id.completeButton);
}
#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);
}
public void saveTimer(View view) {
if(titleEditText.getText().toString().isEmpty() || hourEditText.getText().toString().isEmpty()
|| minuteEditText.getText().toString().isEmpty() || secondEditText.getText().toString().isEmpty()) {
Toast.makeText(this, "Oops you forgot one", Toast.LENGTH_LONG).show();
return;
}
// complete.setVisibility(View.GONE);
title = titleEditText.getText().toString();
hour = Integer.parseInt(hourEditText.getText().toString().trim());
minute = Integer.parseInt(minuteEditText.getText().toString().trim());
second = Integer.parseInt(secondEditText.getText().toString().trim());
hour *= 3600000;
minute *= 60000;
second *= 1000;
actualTimeFiniliazedInMilliSeconds = hour + minute + second;
Intent intent = new Intent(Test.this, ListOfAlarms.class);
intent.putExtra("title", title);
intent.putExtra("totalTime", actualTimeFiniliazedInMilliSeconds);
setResult(RESULT_OK, intent);
finish();
}
}
Alarm.java
public class TestAlarm {
public String title;
public int totalTime;
public TestAlarm (String title, int totalTime) {
this.title = title;
this.totalTime = totalTime;
}
#Override
public String toString() {
return title;
}
}

Person Detail App

I am quite new to programming Android (7 months), and I am having a problem with creating an app.
What I am trying to do is create a "Person Detail" test app for my own Android learning, by having EditText on the Main Activity with TextViews next to them (displaying default values at first), open up another activity called EditData (with a button on the main) which displays the values the user entered into the EditText (via Parcelable), return back to the Main Activty (via another button) and have those entered values displayed in the TextViews next to the EditText (upon a "Update Info" button click) instead of the default ones. I have managed to get everything working right except for displaying the changed values. Everything checks out, no errors in LogCat, but when the user / I clicks the update button, what shows are the default values. Can someone help me?
Here is my Main Activity code:
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends Activity {
final Person firstPerson = new Person();
TextView displayName, displayAge, displayHeight, displayWeight;
EditText editName, editAge, editHeight, editWeight;
Button editActivity, update;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
instantiateUi();
editActivity.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
firstPerson.setPersonName(editName.getText().toString());
firstPerson.setPersonAge(Integer.parseInt(editAge.getText().toString()));
firstPerson.setPersonHeight(Integer.parseInt(editHeight.getText().toString()));
firstPerson.setPersonWeight(Integer.parseInt(editWeight.getText().toString()));
Intent editIntent = new Intent(MainActivity.this, EditData.class);
editIntent.putExtra("First_Person_Data", firstPerson);
MainActivity.this.startActivity(editIntent);
}
});
update.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
displayName.setText(firstPerson.getPersonName());
displayAge.setText(String.valueOf(firstPerson.getPersonAge()));
// String.valueOf is needed to set int for TextViews
displayHeight.setText(String.valueOf(firstPerson.getPersonHeight()));
displayWeight.setText(String.valueOf(firstPerson.getPersonWeight()));
}
});
}
private void instantiateUi() {
editName = (EditText)findViewById(R.id.edit_name);
editAge = (EditText)findViewById(R.id.edit_age);
editHeight = (EditText)findViewById(R.id.edit_height);
editWeight = (EditText)findViewById(R.id.edit_weight);
displayName = (TextView)findViewById(R.id.display_name);
displayAge = (TextView)findViewById(R.id.display_age);
displayHeight = (TextView)findViewById(R.id.display_height);
displayWeight = (TextView)findViewById(R.id.display_weight);
editActivity = (Button)findViewById(R.id.edit_activity);
update = (Button)findViewById(R.id.update_info);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_settings:
break;
default:
return super.onOptionsItemSelected(item);
}
return true;
}
}
My EditData activity code:
import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class EditData extends ActionBarActivity {
TextView changedName, changedAge, changedHeight, changedWeight;
Button MainActivity;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.edit_activity);
Person incomingObject = getIntent().getParcelableExtra("First_Person_Data");
instantiateUi();
changedName.setText(incomingObject.getPersonName());
changedAge.setText(String.valueOf(incomingObject.getPersonAge()));
changedHeight.setText(String.valueOf(incomingObject.getPersonHeight()));
changedWeight.setText(String.valueOf(incomingObject.getPersonWeight()));
MainActivity.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent EditActivity = new Intent(EditData.this, MainActivity.class);
EditData.this.startActivity(EditActivity);
}
});
}
private void instantiateUi() {
changedName = (TextView)findViewById(R.id.changed_name);
changedAge = (TextView)findViewById(R.id.changed_age);
changedHeight = (TextView)findViewById(R.id.changed_height);
changedWeight = (TextView)findViewById(R.id.changed_weight);
MainActivity = (Button)findViewById(R.id.main_activity);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.edit_data_menu, 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);
}
}
And my Parcelable class used for transferring data values:
import android.os.Parcel;
import android.os.Parcelable;
public class Person implements Parcelable{
String personName;
int personAge, personHeight, personWeight;
public Person(){
personName = "No Name!";
personAge = 0;
personHeight = 0;
personWeight = 0;
}
public Person(String pName, int pAge, int pHeight, int pWeight) {
personName = pName;
personAge = pAge;
personHeight = pHeight;
personWeight = pWeight;
}
public Person(Parcel in) {
personName = in.readString();
personAge = in.readInt();
personHeight = in.readInt();
personWeight = in.readInt();
}
public String getPersonName() {
return personName;
}
public void setPersonName(String personName) {
this.personName = personName;
}
public int getPersonAge() {
return personAge;
}
public void setPersonAge(int personAge) {
this.personAge = personAge;
}
public int getPersonHeight() {
return personHeight;
}
public void setPersonHeight(int personHeight) {
this.personHeight = personHeight;
}
public int getPersonWeight() {
return personWeight;
}
public void setPersonWeight(int personWeight) {
this.personWeight = personWeight;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(personName);
dest.writeInt(personAge);
dest.writeInt(personHeight);
dest.writeInt(personWeight);
}
public static final Parcelable.Creator<Person> CREATOR =
new Parcelable.Creator<Person>() {
#Override
public Person createFromParcel(Parcel in) {
return new Person(in);
}
#Override
public Person[] newArray(int size) {
return new Person[size];
}
};
}
Sorry if there are problems, this is my first question and I would very much appreciate what help you can give to a noob C0D3R :P
You shouldn't start variable names with capital letters. Your button MainActivity is very confusing. Better name it something like btMainActivity or something like that.
It think your problem is, that you forget to put an extra to your MainActivity, like you did when starting EditData:
editActivity.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
firstPerson.setPersonName(editName.getText().toString());
firstPerson.setPersonAge(Integer.parseInt(editAge.getText().toString()));
firstPerson.setPersonHeight(Integer.parseInt(editHeight.getText().toString()));
firstPerson.setPersonWeight(Integer.parseInt(editWeight.getText().toString()));
Intent editIntent = new Intent(MainActivity.this, EditData.class);
editIntent.putExtra("First_Person_Data", firstPerson);
MainActivity.this.startActivity(editIntent);
}
});
MainActivity.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent EditActivity = new Intent(EditData.this, MainActivity.class);
// put your extra here
EditData.this.startActivity(EditActivity);
}
});
For what you want, you could also use startActivityForResult. Take a look at it! You should also check out AndroidAnnotations. It can safe you a lot of code and time. I can't imagine making an Android app without it anymore.

How do I refresh TextView on activity calling after closing alert dialog in Android?

I have an alert dialog that allows user to edit a TextView. Currently, once the alert dialog closes, the user has to hit the back button and then re-enter the activity for the TextView to update. I've tried many solutions on SO but none seem to work. When the user clicks 'Save Changes', the TextView should update.
Calling activity:
package com.group1.workouttracker;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import java.util.List;
public class DayActivity extends Activity {
//does not extend ListActivity, so list functions must be called by myList object
private String buttonClicked;
private String thisSummary;
private Intent intent;
DatabaseHelper db;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_day);
db = DatabaseHelper.getInstance(getApplicationContext());
intent = getIntent();
buttonClicked = intent.getStringExtra("Day");
Button buttonCreateExercise = (Button) findViewById(R.id.buttonAddExercise);
buttonCreateExercise.setOnClickListener(new OnClickListenerCreateExercise(buttonClicked));
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public void readSummary(String buttonClicked) {
TextView textViewSummary = (TextView) findViewById(R.id.textViewSummary);
textViewSummary.setOnLongClickListener(new OnLongClickListenerEditSummary(buttonClicked));
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onResume() {
super.onResume();
thisSummary = db.readSummary(buttonClicked).getSummary();
TextView summary = (TextView) findViewById(R.id.textViewSummary);
summary.setOnLongClickListener(new OnLongClickListenerEditSummary(buttonClicked));
summary.setText(thisSummary);
}
}
Alert Dialog that activates on a long press:
package com.group1.workouttracker;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnLongClickListener;
import android.widget.EditText;
import android.widget.NumberPicker;
import android.widget.Toast;
public class OnLongClickListenerEditSummary implements View.OnLongClickListener {
Context context;
String dayClicked = "";
#Override
public boolean onLongClick(View view) {
context = view.getContext();
final DatabaseHelper db = DatabaseHelper.getInstance(context);
ObjectDay objectDay = db.readSummary(dayClicked);
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View formElementsView = inflater.inflate(R.layout.edit_summary_form, null, false);
final long dayId = objectDay.getId();
final String dName = objectDay.getDayName();
final EditText editTextSummary = (EditText) formElementsView.findViewById(R.id.editTextSummary);
final CharSequence[] items = { "Edit", "Delete" };
new AlertDialog.Builder(context).setTitle("Exercise");
new AlertDialog.Builder(context)
.setView(formElementsView)
.setTitle("Edit Summary for " + dayClicked + ":")
.setPositiveButton("Save Changes",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
ObjectDay objectDay = new ObjectDay();
objectDay.setId(dayId);
objectDay.setDayName(dName);
objectDay.setSummary(editTextSummary.getText().toString());
boolean updateSuccessful = DatabaseHelper.getInstance(context).updateSummary(objectDay);
if(updateSuccessful) {
Toast.makeText(context, "Summary was updated.", Toast.LENGTH_SHORT).show();
}
else {
Toast.makeText(context, "Unable to update summary.", Toast.LENGTH_SHORT).show();
}
//dialog.cancel();
dialog.dismiss();
}
}).show();
return false;
}
public void editRecord(final String dName) {
final DatabaseHelper db = DatabaseHelper.getInstance(context);
ObjectDay objectDay = db.readSummary(dName);
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
final View formElementsView = inflater.inflate(R.layout.edit_summary_form, null, false);
final EditText editTextDay = (EditText) formElementsView.findViewById(R.id.editTextSummary);
final EditText editTextSummary = (EditText) formElementsView.findViewById(R.id.editTextSummary);
editTextSummary.setText(objectDay.getSummary());
}
public OnLongClickListenerEditSummary(String dayClicked) {
this.dayClicked = dayClicked;
}
}
Edit: I was able to get this working correctly by adding the following code:
Activity:
public void passThrough(ObjectDay objDay) {
textViewSummary.setText(objDay.getSummary());
}
In .setpositive button:
((DayActivity) context).passThrough(objectDay);
Opening a dialog wont trigger the Activity's onPause/onResume (I'm not sure if that's true for dialog fragments). Instead you can apply an onDismissListener (which can be a member variable of the Activity or anonymous) to the dialog.
When the dialog is closed (by any means) you'll get some information and you can update your textfield. Alternatively you could do the same from the positive click listener.
Either
alert.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
//UPDATE FROM HERE (call a method or manipulate an Activity member var)
}
});
OR
alert.setOnDismissListener(new OnDismissListener() {
public void onDismiss(DialogInterface dialog) {
//UPDATE FROM HERE (Check DialogInterface for positive if you want)
}
});
Edit, for your example:
class Whatever extends Activity {
private TextView mTextView;
private MyPassThroughListener mPassThroughListener = new MyPassThroughListener() {
#Override
public function passThrough(ObjectDay objDay) {
mTextView.setText(objDay.getSummary());
}
}
protected void onCreate(Bundle savedInstanceState) {
....
buttonCreateExercise.setOnClickListener(new OnClickListenerCreateExercise(mPassThroughListener ));
}
}
class OnLongClickListenerEditSummary {
MyPassThroughListener mPassThroughListener;
...
public OnLongClickListenerEditSummary (MyPassThroughListener passThroughListener) {
mPassThroughListener = passThroughListener;
}
#Override
public boolean onLongClick(View view) {
....
new AlertDialog.Builder(context)
.setPositiveButton("Save Changes",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
ObjectDay objectDay = new ObjectDay();
objectDay.setId(dayId);
objectDay.setDayName(dName);
objectDay.setSummary(editTextSummary.getText().toString());
mPassThroughListener.passThrough(objectDay);
dialog.dismiss();
}
...
}
}
public interface MyPassThroughListener {
public function passThrough(ObjectDay objDay);
}

Categories