NullPointerException on calling a public method from another activity - android

I have an Activity SaveData.class with a public method addEvent() use to add some information in a DataBase table as follows:
public class SaveData extends Activity implements OnClickListener {
public SoftCopyDatabase dB ;
public static String FILE_NAME;
String _subject, _topic,_lecturenumber,_date;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.save);
View add = findViewById(R.id.saveSave);
add.setOnClickListener(this);
View home = findViewById(R.id.saveBack);
home.setOnClickListener(this);
}public void onStart() {
super.onStart();
dB = new SoftCopyDatabase(this);
}
public void onStop() {
super.onStop();
if (dB.getReadableDatabase().isOpen()) {
//dB.close();
}
}
public void onDestroy() {
super.onDestroy();
if (dB.getReadableDatabase().isOpen()) {
dB.close();
}
}
public void onClick(View v) {
switch (v.getId()) {
case R.id.saveBack:
Intent i = new Intent(this, OpenScreen.class);
startActivity(i);
break;
case R.id.saveSave:
EditText subject = (EditText) findViewById(R.id.subjectid);
EditText topic = (EditText) findViewById(R.id.topicid);
EditText lecturenumber = (EditText) findViewById(R.id.lecturenumberid);
EditText date = (EditText) findViewById(R.id.dateid);
_subject = ((TextView) subject).getText().toString();
_topic = ((TextView) topic).getText().toString();
_lecturenumber = ((TextView) lecturenumber).getText()
.toString();
_date = ((TextView) date).getText().toString();
FILE_NAME = _subject + _topic + _lecturenumber;
//addEvent();
Intent j = new Intent(this, LectureNoting.class);
startActivity(j);
break;
}
}
public void addEvent() {
ContentValues values = new ContentValues();
values.put(SUBJECT, _subject);
values.put(TOPIC, _topic);
values.put(LECTURENUMBER, _lecturenumber);
values.put(DATE, _date);
values.put(_DATA, FILE_NAME + ".png");
dB.getWritableDatabase().insertOrThrow(TABLE_NAME, null, values);
}
}
Another activity LectureNoting.class is used to save Drawings on the disk and updates the entry in Database Table as follows:
public class LectureNoting extends Activity implements View.OnTouchListener{
private SaveData sD=new SaveData();
private File directory = new File("/sdcard/SoftCopy");
//...remaining code
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.drawing_activity);
}
//...remaining code
public void onClick(View view){
switch (view.getId()){
case R.id.saveBtn:
addEvent();
final Activity currentActivity = this;
Handler saveHandler = new Handler(){
#Override
public void handleMessage(Message msg) {
Toast.makeText(currentActivity, "Lecture Saved", Toast.LENGTH_SHORT).show();
}
} ;
new ExportBitmapToFile(this,saveHandler, softCopyInterface.getBitmap()).execute();
break;
//...remaining code
}
private class ExportBitmapToFile extends AsyncTask<Intent,Void,Boolean> {
private Context mContext;
private Handler mHandler;
private Bitmap nBitmap;
public ExportBitmapToFile(Context context,Handler handler,Bitmap bitmap) {
mContext = context;
nBitmap = bitmap;
mHandler = handler;
}
#Override
protected Boolean doInBackground(Intent... arg0) {
try {
if (!directory.exists()) {
directory.mkdirs();
}
final FileOutputStream out = new FileOutputStream(new File(directory + "/"+SaveData.FILE_NAME+".png"));
nBitmap.compress(Bitmap.CompressFormat.PNG, 90, out);
out.flush();
out.close();
return true;
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
return false;
}
#Override
protected void onPostExecute(Boolean bool) {
super.onPostExecute(bool);
if ( bool ){
mHandler.sendEmptyMessage(1);
}
}
}
}
And I am receiving following error:
Unable to start activity componentInfo(com.ned.LectureNoting):NullPointerException
At the addEvent(), used in the onClick method of LectureNoting.
Kindly tell me where I am going wrong. One point I would like to mention is if addEvent() is called from the same activity in which it was defined, this error does not appear.

Couple of things:
Logcat should be giving more information about the error. You may have to scroll down a bit to see the source of the problem in your code, but there should be more info.
you shouldnt be defining public methods inside of classes that extend Activity to be used by other classes. If you want to expose some database method to multiple activities, then create a separate class for that and then call that method inside of your activity. You said LectureNoting extends Activity. You sure about this? You must have it extending SaveData if you are just calling addEvent() like that.
Either way, DON'T CALL METHODS FROM ONE ACTIVITY INSIDE OF ANOTHER. If you want to expose a method to multiple activities, create it in it's own class with a sensible name related to the group of functions that you expose.

Related

Callbacks in Android

I am new to Android and programming as a whole and I need a little help with callbacks. I understand the gist of callbacks but I am unsure of how to go about implementing.
Context: I am writing a simple notetaking app that allows the user to write text and saving it to the app. The user can then request to read the file with a button. The text is then displayed on a textview in the main activity. There is an option to wipe this file and this is done with a confirmation pop up, which is another activity. This pop up contains 2 buttons, one to cancel and one to wipe. If the file is not empty it will wipe and does nothing if empty. I am not sure if this is the best way to implement it but I want to use the wipe button to callback to the main activity to clear the textview. The way I was thinking of was by using the callback to send a boolean value back. The main activity will check if the boolean is true and clear the textview if it is. I am unsure of how to implement the callback in my popup display to send this boolean value back to the main activity.
Code for main activity
public class MainActivity extends AppCompatActivity implements Popout.ClearTextView {
Button bnRead,bnWrite,bnClear;
TextView tvFileOP;
EditText etInput;
// private static final String INPUT_CONTENT = "inputContent";
public static final String TV_CONTENT = "textViewContent";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bnRead = (Button) findViewById(R.id.bnRead);
bnWrite = (Button) findViewById(R.id.bnWrite);
bnClear = (Button) findViewById(R.id.bnClear);
tvFileOP = (TextView) findViewById(R.id.tvFileOP);
etInput = (EditText) findViewById(R.id.etInput);
tvFileOP.setMovementMethod(new ScrollingMovementMethod());
final String fileName = "test_file";
String data;
bnRead.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
FileInputStream fIn = openFileInput(fileName);
int c;
String temp = "";
while ( (c=fIn.read()) != -1){
temp = temp + Character.toString((char) c);
}
tvFileOP.setText(temp);
Toast.makeText(getBaseContext(),"file successfully read", Toast.LENGTH_LONG).show();
} catch (Exception e) {
e.printStackTrace();
}
}
});
bnWrite.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String data = etInput.getText().toString();
try {
FileOutputStream fOut = openFileOutput(fileName,MODE_APPEND);
fOut.write(data.getBytes());
fOut.close();
etInput.setText("");
Toast.makeText(getBaseContext(),"file successfully written", Toast.LENGTH_LONG).show();
} catch (Exception e) {
e.printStackTrace();
}
}
});
bnClear.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(MainActivity.this,Popout.class));
}
});
}
#Override
protected void onSaveInstanceState(#NonNull Bundle outState) {
outState.putString(TV_CONTENT,tvFileOP.getText().toString());
super.onSaveInstanceState(outState);
}
#Override
protected void onRestoreInstanceState(#NonNull Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
tvFileOP.setText(savedInstanceState.getString(TV_CONTENT));
}
#Override
public void clearTextView(Boolean clear) {
if (clear){
tvFileOP.setText("");
}
}
}
Code for popup confirmation menu
public class Popout extends AppCompatActivity {
Button bnClosepopup,bnWipe;
TextView tvConfirmation;
String fileName = "test_file";
TextView tvFileOP;
public interface ClearTextView {
public void clearTextView(Boolean clear);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.popupwindow);
bnClosepopup = (Button) findViewById(R.id.bnClosepopup);
bnWipe = (Button) findViewById(R.id.bnWipe);
tvConfirmation = (TextView) findViewById(R.id.tvConfirmation);
//HIDING THE TOOL BAR AT THE TOP OF THE SCREEN
this.getSupportActionBar().hide();
//GETTING THE SIZE OF THE SCREEN
DisplayMetrics displayMetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
int height = displayMetrics.heightPixels;
int width = displayMetrics.widthPixels;
getWindow().setLayout((int) (width*0.8) , (int) (0.8*height));
bnClosepopup.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
bnWipe.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
File dir = getFilesDir();
File file = new File(dir, fileName);
boolean deleted = file.delete();
Toast.makeText(getBaseContext(),"file has been deleted",Toast.LENGTH_SHORT).show();
} catch (Exception e) {
Toast.makeText(getBaseContext(), e.getMessage(), Toast.LENGTH_LONG).show();
}
finish();
}
});
}
}
I am very new to android development and any tips on how to improve my code would be greatly appreciated :)
In this case there is no way to pass the interface to the other activity, because this is an activity to activity communication.
You have to use some other method, there is multiple ways to approach, the best way I can think of is to use startActivityForResult() to start the activity and then wait for a response to come back, and then query this response in the MainActivity by overriding the onActivityResult() method:
Example
In the MainActivity:
//on click of this button
bnClear.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this,Popout.class);
int requestCode = 12; //it could be whatever you want
startActivityForResult(intent , requestCode);
}
});
//override this method
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
//this is triggered when you finish the Popout Activity
if(requestCode == 12 && resultCode == Activity.RESULT_OK){
// get the boolean data returned from the Popout Activity
boolean deleted = data.getBooleanExtra("deleted_state" , false); //false is default if no value exists
}
}
In the Popout activity:
bnWipe.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
File dir = getFilesDir();
File file = new File(dir, fileName);
boolean deleted = file.delete();
//send the result to onActivtyResult() in MainActivity
Intent result = new Intent();
result.putExtra("deleted_state", deleted );
setResult(Activity.RESULT_OK, result);
Toast.makeText(getBaseContext(),"file has been deleted",Toast.LENGTH_SHORT).show();
} catch (Exception e) {
Toast.makeText(getBaseContext(), e.getMessage(), Toast.LENGTH_LONG).show();
}
finish();
}
});
UPDATE:
It will be like this:
// get the boolean data returned from the Popout Activity
boolean deleted = data.getBooleanExtra("deleted_state" , false);
if (deleted){
tvFileOP.setText("");
}
..........
As far as what if Understood your problem correctly: You want to control your 'Wipe' button click event from your activity. Here is the solution which may help you.
1: Make an overridden constructor of your dialog class.
2: Create one abstract method in the dialog class. (say - onWipeButtonClick)
You need to make your dialog class abstract as well.
3: Inside on Click Listener of 'Wipe' button, call onWipeButtonClick abstract method.
4: Create the instance of dialog in the main activity where ever you want. The compiler will give you an error because you haven't implemented the call back method.
do implement your onWipeButtonClick method and do needful for wipe data inside the method.
public abstract class WipeDialog extends Dialog{
private Context context;
public WipeDialog(Context context){
this.context = context;
}
public abstract void onWipeButtonClick(boolean isTextEmpty);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.<XML_FILE>);
<initialization>
btnWipe.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
onWipeButtonClick(<YOUR_BOOLEAN_CHECK>);
}
});
}
}
And now in Activity:
WipeDialog dialog = new WipeDialog(MainActivity.this) {
#Override
public void onWipeButtonClick(boolean isTextEmpty) {
//Do Need full with respected to your requirement on click of button 'WIPE'
}
};
Hope this will help.
Thanks!

Async task not populating list properly

I'm developing a feed app, where people can make posts and these posts will populate a RecyclerView.
I have a FAB button that leads to a post activity, but when I post and then comeback to the MainActivity the list is not updated. But when I use the logout button and log back in, the list gets updated, or when I launch the activity it works.
I think this happens because my Async function gets called to work on onCreate, but I can't work like these, I need the AsyncTask to automatically fetch, otherwise people won't get the list updated in real time.
Could you please show me a light in the dark? Here are the codes for MainActivity, PostActivity and logout function from another class.
Main Activity:
public class MainActivity extends AppCompatActivity {
private AppCompatActivity activity = MainActivity.this;
private RecyclerView recyclerViewNews;
private List<Noticia> listNoticias;
private NewsRecyclerAdapter newsRecyclerAdapter;
private DBNoticias databaseHelper;
private Button btnLogout;
private LinearLayoutManager mLayoutManager;
UserSession userSession;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
userSession = new UserSession(getApplicationContext());
recyclerViewNews = findViewById(R.id.recyclerViewNews);
btnLogout = findViewById(R.id.btlogout);
TextView usuario = findViewById(R.id.textView5);
/**
* Olá mundo by Alciomar
*/
SharedPreferences sharedPreferences = getSharedPreferences("Reg", Context.MODE_PRIVATE);
String uName = sharedPreferences.getString("Name", "");
usuario.setText(uName.toUpperCase());
try {
btnLogout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
userSession.logoutUser();
}
});
} catch (Exception e) {
e.printStackTrace();
}
initStuff();
getDataFromPostgres();
FloatingActionButton fab = findViewById(R.id.fabNews);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this, PostNews.class);
startActivity(intent);
}
});
}
/**
* This method is to initialize objects to be used
*/
private void initStuff() {
try {
listNoticias = new ArrayList<>();
newsRecyclerAdapter = new NewsRecyclerAdapter(listNoticias);
mLayoutManager = new LinearLayoutManager(getApplicationContext());
mLayoutManager.setReverseLayout(true);
mLayoutManager.setStackFromEnd(true);
recyclerViewNews.setLayoutManager(mLayoutManager);
recyclerViewNews.setItemAnimator(new DefaultItemAnimator());
recyclerViewNews.setHasFixedSize(true);
recyclerViewNews.setAdapter(newsRecyclerAdapter);
databaseHelper = new DBNoticias(activity);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* This method is to fetch all user records from SQLite
*/
private void getDataFromPostgres() {
// AsyncTask is used that SQLite operation not blocks the UI Thread.
new AsyncTask<Void, Void, Void>() {
#Override
protected Void doInBackground(Void... params) {
listNoticias.clear();
for (DBNoticias dbNoticias : databaseHelper.getNewsList()) {
Noticia noticia = new Noticia();
noticia.setUser_id(dbNoticias.getId());
noticia.setNewsTitle(dbNoticias.getNewsTitle());
noticia.setNewsMessage(dbNoticias.getNewsPost());
listNoticias.add(noticia);
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
newsRecyclerAdapter.notifyDataSetChanged();
}
}.execute();
}
Post News Activity:
public class PostNews extends AppCompatActivity {
private DBNoticias dbNoticias;
private Button btnpostar;
private EditText editTextCDNewsTitle;
private EditText editTextCDNewsPost;
private Noticia noticia;
private SharedPreferences sharedPreferences;
public void alert(String titulo, String txt){
AlertDialog alertDialog = new AlertDialog.Builder(PostNews.this).create();
alertDialog.setTitle(titulo);
alertDialog.setMessage(txt);
alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alertDialog.show();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_post_news);
btnpostar = findViewById(R.id.btn_postar);
dbNoticias = new DBNoticias();
editTextCDNewsTitle = findViewById(R.id.EditTextNewsTitle);
editTextCDNewsPost = findViewById(R.id.EditTextNewsPost);
}
public void salvarNoticia(View view) {
try {
{
String newsTitle = editTextCDNewsTitle.getText().toString();
String newsPost = editTextCDNewsPost.getText().toString();
if (!(editTextCDNewsTitle.getText().toString().equals("") || editTextCDNewsTitle.getText() == null ||
editTextCDNewsPost.getText().toString().equals("") || editTextCDNewsPost.getText() == null
)) {
sharedPreferences = getSharedPreferences("Reg", Context.MODE_PRIVATE);
String uName = sharedPreferences.getString("Name", "");
String uEmail = sharedPreferences.getString("Email", "");
int uIdUser = sharedPreferences.getInt("IdUser", 0);
dbNoticias.setNewsTitle(newsTitle);
dbNoticias.setNewsPost(newsPost);
dbNoticias.setIdUser(uIdUser);
dbNoticias.salvar();
noticia = new Noticia();
Toast.makeText(getApplicationContext(), "Notícia postada com sucesso",
Toast.LENGTH_LONG).show();
editTextCDNewsTitle.setText("");
editTextCDNewsPost.setText("");
}
}
}
catch (Exception e){
alert("Erro", e.getMessage());
}
}
Thank you in advance if you read and try to help!
There are multiple ways to do this:
Method 1 – Use onResume()
If you call your getDataFromPostgres() method in onResume instead of onCreate, it'll fetch data and refresh list every time the activity wakes from a pause (for example coming back from another activity)
// existing code
#Override
public void onResume(){
super.onResume();
getDataFromPostgres()
}
(This would be the simplest solution)
Method 2 – Poll the DB continuously
If there are other services that might be updating the database and you need to always show the latest state in the activity, another way (although really inefficient) would be to keep refreshing the list after a defined time period (let's say 10 seconds as an example).
How to run an async task for every x mins in android?
Method 3 – Use onActivityResult
If you want to update the list only when a new entry has been created in the second activity, you can use onActivityResult to notify the first activity on action and then refresh your list there.
How to manage `startActivityForResult` on Android?
Please use this, it's working for me
newsRecyclerAdapter.notifyItemInserted(position);
newsRecyclerAdapter.notifyDataSetChanged();

how to get object reference from other activity [android]

I have two major classes in my project. The first is for creating the connection between the client and the server. The second is for switching between activities.
first:
public class MyActivity extends Activity{
private ListView mList;
private ArrayList<String> arrayList;
private MyCustomAdapter mAdapter;
public TCPClient mTcpClient;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
boolean flag = getIntent().getBooleanExtra("flag",false);
arrayList = new ArrayList<String>();
final EditText editText = (EditText) findViewById(R.id.editText);
Button send = (Button)findViewById(R.id.send_button);
Button menu = (Button)findViewById(R.id.button1);
if (flag == true)
{
//relate the listView from java to the one created in xml
mList = (ListView)findViewById(R.id.list);
mAdapter = new MyCustomAdapter(this, arrayList);
mList.setAdapter(mAdapter);
new connectTask().execute("");
Intent myIntent = new Intent(MyActivity.this,Menu.class);
startActivity(myIntent);
}
send.setOnClickListener(new View.OnClickListener() {
// #Override
public void onClick(View view) {
String message = editText.getText().toString();
//clean the listView to 1 item
if (message.equals("clean"))
{
arrayList.removeAll(arrayList);
mList.removeAllViewsInLayout();
}
//add the text in the arrayList
arrayList.add("c: " + message);
//sends the message to the server
if (mTcpClient != null) {
mTcpClient.sendMessage(message);
}
//refresh the list
mAdapter.notifyDataSetChanged();
editText.setText("");
}
});
//change Activity to live screen mode (live)
menu.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent myIntent = new Intent(MyActivity.this, Menu.class);
startActivity(myIntent);
}
});
}
public class connectTask extends AsyncTask<String,String,TCPClient> {
#Override
protected TCPClient doInBackground(String... message) {
//we create a TCPClient object and
mTcpClient = new TCPClient(new TCPClient.OnMessageReceived() {
// #Override
//print the message as an Item
public void messageReceived(String message) {
//this method calls the onProgressUpdate
publishProgress(message);
}
});
mTcpClient.run();
return null;
}
#Override
protected void onProgressUpdate(String... values) {
super.onProgressUpdate(values);
//in the arrayList we add the messaged received from server
arrayList.add(values[0]);
// notify the adapter that the data set has changed. This means that new message received
// from server was added to the list
mAdapter.notifyDataSetChanged();
}
}
}
the object TCPClient mTcpClient is the major factor in my app. I use it communicate with the server. In addition, even if I switch between activities it is still running properly so I still get info from server even though I am not in that activity.
second:
public class Menu extends Activity
{
public MyActivity myActivity;
public TCPClient mtcp;
protected void onCreate(Bundle savedInstanceState, MyActivity myActivity)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.menu);
ImageView action = (ImageView) findViewById(R.id.imageView1);
action.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event)
{
// here I would like to use mTcpClient object mentioned in the first class
return false;
}
});
}
Basically what I need is a help on how to create in the second class reference to the object mTcpClient that is described in the first class.
You are doing it wrong. If you want to use TcpClient class regardless of context it should NOT be related to first Activity. What you should do is to use singleton pattern:
class TcpClient {
protected static TcpClient mInstance = null;
public TcpClient() {
// your init code...
}
public static TcpClient getInstance() {
if( mInstance == null ) {
mInstance = new TcpClient();
}
return mInstance;
}
...
}
and then, whenever you want to use TcpClient you just do:
TcpClient client = TcpClient.getInstance();

AsyncTask : passing value to an Activity (onCreate method )

Update1
activity:
public Integer _number = 0;
#Override
public void onCreate(Bundle savedInstanceState) {
if (_number >0)
{
Log.d("onSuccessfulExecute", ""+_number);
}
else
{
Log.d("onSuccessfulExecute", "nope empty songs lists");
}
}
public int onSuccessfulExecute(int numberOfSongList) {
_number = numberOfSongList;
if (numberOfSongList >0)
{
Log.d("onSuccessfulExecute", ""+numberOfSongList);
}
else
{
Log.d("onSuccessfulExecute", "nope empty songs lists");
}
return numberOfSongList;
}
end Update1
UPDATE: AsynchTask has its own external class.
How to pass an value from AsyncTask onPostExecute()... to activity
my code does returning value from onPostExecute() and updating on UI but i am looking for a way to set the activity variable (NumberOfSongList) coming from AsynchTask.
AsyncTask class:
#Override
public void onPostExecute(asynctask.Payload payload)
{
AsyncTemplateActivity app = (AsyncTemplateActivity) payload.data[0];
//the below code DOES UPDATE the UI textView control
int answer = ((Integer) payload.result).intValue();
app.taskStatus.setText("Success: answer = "+answer);
//PROBLEM:
//i am trying to populate the value to an variable but does not seems like the way i am doing:
app.NumberOfSongList = payload.answer;
..............
..............
}
Activity:
public Integer NumberOfSongList;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//Several UI Code
new ConnectingTask().execute();
Log.d("onCreate", ""+NumberOfSongList);
}
What about using a setter method? e.g.
private int _number;
public int setNumber(int number) {
_number = number;
}
UPDATE:
Please look at this code. This will do what you're trying to accomplish.
Activity class
public class TestActivity extends Activity {
public int Number;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.test);
Button btnDisplay = (Button) findViewById(R.id.btnDisplay);
btnDisplay.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Toast toast = Toast.makeText(v.getContext(), "Generated number: " + String.valueOf(Number), Toast.LENGTH_LONG);
toast.show();
}
});
new TestTask(this).execute();
}
}
AsyncTask class
public class TestTask extends AsyncTask<Void, Void, Integer> {
private final Context _context;
private final String TAG = "TestTask";
private final Random _rnd;
public TestTask(Context context){
_context = context;
_rnd = new Random();
}
#Override
protected void onPreExecute() {
//TODO: Do task init.
super.onPreExecute();
}
#Override
protected Integer doInBackground(Void... params) {
//Simulate a long-running procedure.
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
Log.e(TAG, e.getMessage());
}
return _rnd.nextInt();
}
#Override
protected void onPostExecute(Integer result) {
TestActivity test = (TestActivity) _context;
test.Number = result;
super.onPostExecute(result);
}
}
Just a word of caution: Be very careful when attempting to hold a reference to an Activity instance in an AsyncTask - I found this out the hard way :). If the user happens to rotate the device while your background task is still running, your activity will be destroyed and recreated thus invalidating the reference being to the Activity.
Create a listener.
Make a new class file. Called it something like MyAsyncListener and make it look like this:
public interface MyAsyncListener() {
onSuccessfulExecute(int numberOfSongList);
}
Make your activity implement MyAsyncListener, ie,
public class myActivity extends Activity implements MyAsyncListener {
Add the listener to the constructor for your AsyncTask and set it to a global var in the Async class. Then call the listener's method in onPostExecute and pass the data.
public class MyCustomAsync extends AsyncTask<Void,Void,Void> {
MyAsyncListener mal;
public MyCustomAsync(MyAsyncListener listener) {
this.mal = listener;
}
#Override
public void onPostExecute(asynctask.Payload payload) {
\\update UI
mal.onSuccessfulExecute(int numberOfSongList);
}
}
Now, whenever your AsyncTask is done, it will call the method onSuccessfulExecute in your Activity class which should look like:
#Override
public void onSuccessfulExecute(int numberOfSongList) {
\\do whatever
}
Good luck.

keeping a variable value across all android activities

I have a database with one row of data that will be used across a number of activities. I need to be able to keep the row id available in all activites so I can read and write data across different activites with my DB adapter. I have successfully used putExtra (Overthelimit.java) via an intent to pass a row id to the next activity. mRowId variable is then given the row id using getExtra (Profile.java). The problem I now have is making mRowId available to other activities i.e. MyUsual and DrinksList so I can update data as I go.
You can see I have tried putExtras, putSerializable but can't get it to work. I think I am missing some understanding.
So for my profile menu option in the activity below I can send the value of the cursor row id to Profile class:
public class Overthelimit extends ListActivity {
private OverLimitDbAdapter dbHelper;
private Cursor cursor;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
this.getListView();
dbHelper = new OverLimitDbAdapter(this);
dbHelper.open();
fillData();
registerForContextMenu(getListView());
}
#Override
protected void onActivityResult(int requestCode, int resultCode,
Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
fillData();
}
private void fillData() {
cursor = dbHelper.fetchAllUserDrinks();
startManagingCursor(cursor);
//cursor.getCount();
String[] from = new String[] { OverLimitDbAdapter.KEY_USERNAME };
int[] to = new int[] { R.id.label };
// Now create an array adapter and set it to display using our row
SimpleCursorAdapter notes = new SimpleCursorAdapter(this,
R.layout.user_row, cursor, from, to);
setListAdapter(notes);
}
#Override
protected void onDestroy() {
super.onDestroy();
if (dbHelper != null) {
dbHelper.close();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.profile:
Intent myIntent1 = new Intent(this, Profile.class);
if(cursor.getCount() != 0) {
//Toast.makeText(getApplicationContext(), "no profile",Toast.LENGTH_SHORT).show();
myIntent1.putExtra(OverLimitDbAdapter.KEY_ROWID, cursor.getString(cursor.getColumnIndexOrThrow(OverLimitDbAdapter.KEY_ROWID)));
}
startActivityForResult(myIntent1, 0);
return true;
case R.id.myusual:
Intent myIntent2 = new Intent(this, MyUsual.class);
startActivityForResult(myIntent2, 0);
return true;
case R.id.trackme:
Intent myIntent3 = new Intent(this, TrackMe.class);
startActivityForResult(myIntent3, 0);
return true;
case R.id.moreinfo:
Intent myIntent4 = new Intent(this, MoreInfo.class);
startActivityForResult(myIntent4, 0);
return true;
}
return super.onOptionsItemSelected(item);
}
}
Then make it available as mRowId in my Profile activity below:
mRowId = (bundle == null) ? null :
(Long) bundle.getSerializable(OverLimitDbAdapter.KEY_ROWID);
if (mRowId == null) {
Bundle extras = getIntent().getExtras();
mRowId = extras != null ? Long.parseLong(extras.getString(OverLimitDbAdapter.KEY_ROWID))
: null;
}
I then need to make this mRowId available to another activity called DrinkList from MyUsual. so I have MyUsual below with a drink1 button onClickListener to try and send the row id to DrinksList:
public class MyUsual extends Activity {
private Long mRowId;
private OverLimitDbAdapter mDbHelper;
private Cursor cursor;
private TextView mDrink1Label;
private TextView mDrink1Units;
/** Called when the activity is first created. */
#Override
public void onCreate(final Bundle bundle) {
super.onCreate(bundle);
mDbHelper = new OverLimitDbAdapter(this);
mDbHelper.open();
setContentView(R.layout.my_usual);
mDrink1Label = (TextView) findViewById(R.id.drink1Label);
mDrink1Units = (TextView) findViewById(R.id.drink1Units);
Button drink1 = (Button) findViewById(R.id.drink1Button);
// get intent data i.e. which drink button pressed and mRowId
mRowId = (bundle == null) ? null :
(Long) bundle.getSerializable(OverLimitDbAdapter.KEY_ROWID);
if (mRowId == null) {
Bundle extras = getIntent().getExtras();
mRowId = extras != null ? Long.parseLong(extras.getString(OverLimitDbAdapter.KEY_ROWID))
: null;
}
//populateFields();
drink1.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
setResult(RESULT_OK);
//finish();
Intent myIntent1 = new Intent(view.getContext(), DrinksList.class);
myIntent1.putExtra("drinkButton", "drink1");
if(cursor.getCount() != 0) {
myIntent1.putExtra(OverLimitDbAdapter.KEY_ROWID, cursor.getString(cursor.getColumnIndexOrThrow(OverLimitDbAdapter.KEY_ROWID)));
}
startActivityForResult(myIntent1, 0);
}
});
}
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
//saveState();
outState.putSerializable(OverLimitDbAdapter.KEY_ROWID, mRowId);
}
}
From DrinksList I select a drink and I need to use the mRowId write the data to the database via the onListItemclick:
public class DrinksList extends ListActivity {
private ProgressDialog m_ProgressDialog = null;
private ArrayList<CreateDrinkOption> m_drinks = null;
private DrinkAdapter m_adapter;
private Runnable viewDrinks;
private String drinkButton;
private Long mRowId;
private OverLimitDbAdapter mDbHelper;
private String databaseRow;
private Cursor cursor;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle bundle) {
super.onCreate(bundle);
setContentView(R.layout.drinks_list);
mDbHelper = new OverLimitDbAdapter(this);
mDbHelper.open();
m_drinks = new ArrayList<CreateDrinkOption>();
this.m_adapter = new DrinkAdapter(this, R.layout.drink_row, m_drinks);
setListAdapter(this.m_adapter);
viewDrinks = new Runnable(){
#Override
public void run() {
getDrinks();
}
};
Thread thread = new Thread(null, viewDrinks, "MagentoBackground");
thread.start();
m_ProgressDialog = ProgressDialog.show(DrinksList.this,
"Please wait...", "Retrieving data ...", true);
// get intent data i.e. which drink button pressed and mRowId
mRowId = (bundle == null) ? null :
(Long) bundle.getSerializable(OverLimitDbAdapter.KEY_ROWID);
if (mRowId == null) {
Bundle extras = getIntent().getExtras();
drinkButton = extras.getString(drinkButton);
mRowId = extras != null ? Long.parseLong(extras.getString(OverLimitDbAdapter.KEY_ROWID))
: null;
}
}
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
//saveState();
outState.putSerializable(OverLimitDbAdapter.KEY_ROWID, mRowId);
}
private Runnable returnRes = new Runnable() {
#Override
public void run() {
if(m_drinks != null && m_drinks.size() > 0){
m_adapter.notifyDataSetChanged();
for(int i=0;i<m_drinks.size();i++)
m_adapter.add(m_drinks.get(i));
}
m_ProgressDialog.dismiss();
m_adapter.notifyDataSetChanged();
}
};
#Override
protected void onListItemClick(ListView l, View v, int position, long id)
{
try
{
super.onListItemClick(l, v, position, id);
CreateDrinkOption bkg = (CreateDrinkOption)l.getItemAtPosition(position);
String drink1type = bkg.getDrinkType().toString();
float drink1units = (bkg.getPercentageByVolume() * bkg.getVolume());
//Toast.makeText(this, mRowId.toString(), Toast.LENGTH_LONG).show();
mDbHelper.updateDrink(mRowId, drink1type, drink1units);
finish();
}
catch(Exception ex)
{
Toast.makeText(this, "error", Toast.LENGTH_LONG).show();
}
}
private void getDrinks(){
try{
m_drinks = new ArrayList<CreateDrinkOption>();
CreateDrinkOption o1 = new CreateDrinkOption();
o1.setDrinkType("Beer - 1 pint");
o1.setPercentageByVolume((float) 4.5);
o1.setVolume((float) 0.5);
m_drinks.add(o1);
CreateDrinkOption o2 = new CreateDrinkOption();
o2.setDrinkType("Wine - small glass");
o2.setPercentageByVolume((float) 12);
o2.setVolume((float) 0.125);
m_drinks.add(o2);
CreateDrinkOption o3 = new CreateDrinkOption();
o3.setDrinkType("Spirit - single");
o3.setPercentageByVolume((float) 40);
o3.setVolume((float) 0.25);
m_drinks.add(o3);
CreateDrinkOption o4 = new CreateDrinkOption();
o4.setDrinkType("Alcopop - bottle");
o4.setPercentageByVolume((float) 5);
o4.setVolume((float) 0.275);
m_drinks.add(o4);
Thread.sleep(1000);
Log.i("ARRAY", ""+ m_drinks.size());
} catch (Exception e) {
Log.e("BACKGROUND_PROC", e.getMessage());
}
runOnUiThread(returnRes);
}
private class DrinkAdapter extends ArrayAdapter<CreateDrinkOption> {
private ArrayList<CreateDrinkOption> items;
public DrinkAdapter(Context context, int textViewResourceId, ArrayList<CreateDrinkOption> items) {
super(context, textViewResourceId, items);
this.items = items;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater vi = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.drink_row, null);
}
CreateDrinkOption o = items.get(position);
if (o != null) {
TextView tt = (TextView) v.findViewById(R.id.drinkdetail);
TextView bt = (TextView) v.findViewById(R.id.drinkunits);
if (tt != null) {
tt.setText("Type: "+o.getDrinkType());
}
if(bt != null){
bt.setText("Units: "+ String.valueOf(o.getPercentageByVolume() * o.getVolume()));
}
}
return v;
}
}
}
Sorry for the long post, but all I need to do is make this value for mRowId available to all activites so I can read/write data at any point. The data also needs to be there if the app is paused or interupted by say an incoming call, so I use onSaveInstanceState.
ok, thanks. So reply to great answers and I have done this, but it crashes trying to get the data. I have this as my Application class:
public class OverthelimitApplication extends Application {
private Long rowId;
public Long getRowId() {
return rowId;
}
public void setRowId(Long value) {
rowId = value;
}
}
then set value with this:
OverthelimitApplication app1 = (OverthelimitApplication)getApplicationContext();
app1.setRowId((long) cursor.getColumnIndexOrThrow(OverLimitDbAdapter.KEY_ROWID));
then try to get value with this and it crashes:
mRowId = ((OverthelimitApplication) getApplicationContext()).getRowId();
I have fixed it! using this the set and get:
app1.setRowId(Long.parseLong(cursor.getString(cursor.getColumnIndexOrThrow(OverLimitDbAdapter.KEY_ROWID))));
mRowId = (long)((OverthelimitApplication)getApplicationContext()).getRowId();
I still had to specify long when setting and getting. Thanks for all your input.
Another way is to create a application class which is available for all activities.
To do that, you have to extend you Manifest with
<application
..
android:name=".MyApplication" >
and create a new Class
public class MyApplication extends Application {
public int rowId = 0;
}
inside the activities, you can access the rowId by
int mRowId = ((MyApplication) getApplicationContext()).rowId;
There are two options that I think are fit for your purpose:
SharedPreferences: the added benefit is that your variables will kept and available next time you start the application. You can store primitive types easily in shared preferences, like your rowId.
Application: you can subclass the application class, something like MyApplication extends Application, declare in your manifest that you're using this class instead of the default application, and access it using getApplication from all your activities. The added benefit is you can store anything, even a complex data structure in the application, you define the member and access methods in your MyApplication class. For example you could store the whole row of data in your application, not just the rowId)
Personally, I use SharedPreferences to remember settings that I want to be saved for the user, and not having to set them again each time the application is started is nice. And I use application for all the temporary data that I want to live across all activities as long as the application is open.
I'll describe 2 ways.
1) Use a static variable in any one of the Activities. This is the quick, dirty and lazy way. You've been warned.
2) Create your Application class.
Create a Simple class MyApplication that extends Application
In the Android Manifest, there should be a field for Application, make sure you choose your Class.
Typical example.
public class MyApp extends Application
{
private Object myGloballyAccessibleObject; //make getter and setter
private static MyApp singleInstance = null;
public static MyApp getInstance()
{
return singleInstance;
}
#Override
public void onCreate() {
super.onCreate();
singleInstance = this;
}
}
In your activities,
Call this
MyApp myApp = MyApp.getInstance();
myApp.getMyAwesomeObject(); //Booyaah!
You can use the ApplicationContext too. In your Manifest, you should have something like this :
<application
...
android:name="xx.xx.MyApp"
...>
Now, you can access to the Application from any Activity thanks to :
MyApp application = (MyApp)this.getApplicationContext();
You can put your attributes in this class, it'll be accessible anywhere in your app. MyApp must extends Application. See Manifest and
Application
Here you want to get mRowId values from all activity and it is primitive types, So
Either use Shared Preferences for store data or make your member field as a static globally, Then you can use this data in your whole application life cycle..
EDIT: Also you can use Application class as a singleton for your application and create field mRowId in this class and also make getter setter method for this field..

Categories

Resources