I have an activity that allows user to enter notes and store them in dynamically created textviews. However, when the use leaves the activity and returns, all the created textviews disappear. How can i store store or retrieve all of these created textviews, whenever i return to the activity? Also, i think that my sharedpreferences will be overwriting each time a new textview is added. Any suggestions?
public class DocNoteActivity extends Activity {
private LinearLayout nLayout;
private EditText etDocNote;
private Button btnAdd1;
public static final String PREFS_NAME = "MyPrefsFile";
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.adddocnote);
etDocNote = (EditText) findViewById(R.id.editDocNote);
btnAdd1 = (Button) findViewById(R.id.btnAdd1);
nLayout = (LinearLayout) findViewById(R.id.linearLayout);
TextView tvNote = new TextView(this);
tvNote.setText("");
btnAdd1.setOnClickListener(onClick());
}
private OnClickListener onClick() {
// TODO Auto-generated method stub
return new OnClickListener(){
public void onClick(View v) {
// TODO Auto-generated method stub
String newDocNote = etDocNote.getText().toString();
nLayout.addView(createNewTextView(newDocNote));
getSharedPreferences("myprefs", 0).edit().putString("etDocNote", newDocNote).commit();
}
};
}
private TextView createNewTextView(String newText) {
// TODO Auto-generated method stub
LayoutParams lparams = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
TextView tvNote = new TextView(this);
tvNote.setLayoutParams(lparams);
tvNote.setText(newText);
return tvNote;
}
}
If you want to retrieve the Notes you have to use the Database (i.e. SQLite) because every time you save the notes in SharedPreferences it will be override. So I recommend you to use the Database. For that here are some useful resources which i think help you.
1 - http://www.androidhive.info/2011/11/android-sqlite-database-tutorial/
2 - http://www.vogella.com/articles/AndroidSQLite/article.html
3 - http://android-er.blogspot.in/2011/06/simple-example-using-androids-sqlite_02.html
NOTE - SharedPreferences are used to store key-value pair data. Mostly it is we can say one kind of Session Management in Android way. I mostly store username & password kind of data in SharedPreferences.
Hope this helps.
Related
I am kinda new in android and java programming, and I have a question, wish you could help me to solve it :)
I have a Program, it will fetch and loop data from database and convert it into some checkboxes, then user must check the checkboxes and hit the submit button,,
The value(s) of the checked checkboxes will be stored to a String[], then will be send to another activity via Intent.putExtra..
So far, all I can do is fetch and loop the data from database, but I have no idea about how to store all the checked value (of the checkboxes) to string and sent it to another activity via intent. Can you guys please help me with this and where should I put the code?
And here is my code :
private void fetchFromDatabase() {
// TODO Auto-generated method stub
myDb.open();
int totalGroup = myDb.countHowManyGroups(Username);
String groupId[] = myDb.fetchGroupId(Username);
String groupName[] = myDb.fetchGroupName(Username);
String flag[] = null;
for (int i = 0; i < totalGroup; i++) {
listCheckBox = new CheckBox(this);
listCheckBox.setText(groupName[i]);
listCheckBox.setTag(groupId[i]);
if (listCheckBox.isChecked()) {
int x=0;
flag[x]=listCheckBox.getText().toString();
x++;
}
layout.addView(listCheckBox);
}
myDb.close();
Button bSubmit = new Button(this);
bSubmit.setText("Submit");
layout.addView(bSubmit);
bSubmit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (listCheckBox.isChecked()) {
}
}
});
}
It depends of what you want to store. Do you want to store the id of the selected checkboxes? Then override their setOnCheckedChangeListener to save it's id on an array (remember that id is 0 unless you set it.)
Do you want to save it's tag? Then override the same method but save the tag instead.
Here is an example of the implementation of setOnCheckedChangeListener:
List<String> myTagList = new ArrayList<String>();
listCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(isChecked)
myTagList.add(buttonView.getTag());
else
myTagList.remove(buttonView.getTag());
}
});
I am trying to extract text from a PDF file using MuPDF library in Android platform.
Is it possible to extract text within a rectangle specified by coordinates (left, top, right, bottom)?
Note: I didn't compile the library from source. I am using compiled libraries which is distributed in https://github.com/libreliodev/android.
yeah sure
here is the way you can do.
1.GeneratedText activity
public class GeneratedText extends Activity {
private Button close;
private Button clear;
private TextView tv;
private String data;
String text = "";
Intent i;
Context mContext;
// MuPDFPageView pdfview = new MuPDFPageView(mContext, null, null);
private EditText edit;
private Button undo;
public static GeneratedText screen;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_generated_text);
close = (Button)findViewById(R.id.close);
clear = (Button)findViewById(R.id.clear);
tv = (TextView)findViewById(R.id.text1);
edit = (EditText)findViewById(R.id.edit);
undo = (Button)findViewById(R.id.undo);
undo.setEnabled(false);
i = getIntent();
data = i.getStringExtra("data");
tv.setText(data);
String mypattern = "Name and address of the Employee \n";
Pattern p = Pattern.compile(mypattern,Pattern.DOTALL);
if(data.matches(mypattern))
{
System.out.println("Start Printing name");
}
else
//do nothing
edit.setText(data);
System.out.println("hello user "+"/n"+"user1"+ "\n"+ "user2");
SharedPreferences pref = getSharedPreferences("key", 0);
SharedPreferences.Editor editor = pref.edit();
editor.putString("text", data);
editor.commit();
clear.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
tv.setText("");
edit.setText("");
undo.setEnabled(true);
}
});
close.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
finish();
}
});
undo.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String value = "";
SharedPreferences pref = getSharedPreferences("key", 0);
value = pref.getString("text", value);
edit.setText(value);
tv.setText(value);
undo.setEnabled(false);
}
});
}
}
1. now in mupdfactivity write this
public void Showtext( )
{
destroyAlertWaiter();
core.stopAlerts();
MuPDFPageView pdfview = new MuPDFPageView(MuPDFActivity.this, core, null);
String data = "";
pdfview.setFocusable(true);
data = pdfview.getSelectedText();
Intent i = new Intent(getApplicationContext(),GeneratedText.class);
i.putExtra("data",data);
startActivity(i);
}
call Showtext in OnAcceptButtonClick
and you will get your text.
Yes it is possible to extract text from PDF document with the help of MuPDF library. There is method called text() in mupdf.c which is defined in MuPDFCore.java which returns the text of the page. You need to call that method by page wise.
Steps:
1. gotopage(pagenumber)
2. text()
I am trying to make a simple todo list app which will probably store only a few things.
After adding items in the ListView, and closing the app, the only entry that loads is the last one that is entered. How do I make all the entered entries show up after closing the app?
Code:
public class MainActivity extends ActionBarActivity {
EditText display;
ListView lv;
ArrayAdapter<String> adapter;
Button addButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
display = (EditText) findViewById(R.id.editText1);
lv = (ListView) findViewById(R.id.listView1);
addButton = (Button) findViewById(R.id.button1);
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1);
lv.setAdapter(adapter);
LoadPreferences();
addButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String task = display.getText().toString();
adapter.add(task);
adapter.notifyDataSetChanged();
SavePreferences("LISTS", task);
}
});
}
protected void SavePreferences(String key, String value) {
// TODO Auto-generated method stub
SharedPreferences data = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = data.edit();
editor.putString(key, value);
editor.commit();
}
protected void LoadPreferences(){
SharedPreferences data = PreferenceManager.getDefaultSharedPreferences(this);
String dataSet = data.getString("LISTS", "None Available");
adapter.add(dataSet);
adapter.notifyDataSetChanged();
}}
Thanks in advance.
You should have to keep key different for each item you are adding to SharedPreferences, otherwise last item you added in preference will override the last one.
I won't suggest using SharedPreferences for making an app like a todo list.
Make a SQLite database and store your todos in that. Or you can save the todos in a JSON file which is also very simple to achieve.
Using SharedPreferences won't be efficient in this case as you will need to track the keys of all the todo preferences, which creates another overhead.
Check out this post by Lars Vogel about creating content providers and SQLite Databses:
Android SQLite database and content provider - Tutorial
I am having a problem with passing strings from a fragment to another activity.
I have tried numerous methods of passing them using intents (eg normal extras, bundles) , but the extras are always null in the activity.
I have looked at
http://www.vogella.com/articles/AndroidIntent/ But no change
http://developer.android.com/training/basics/firstapp/starting-activity.html This method of passing the data also doesn't work
Other similar questions on stackoverflow - but these are not quite the same
What I'm trying to do is get the text that was input in the two EditTexts in the fragment, and then pass that text to the activity where the two EditTexts there are filled with the same text. The problem is that nothing appears in the the two EditTexts in the activity. I know that the EditTexts in the fragments are working because a can create a notification using them.
My code: I have removed things I think are unneccessary eg adding the fragment to a navigation drawer layout. Please excuse missing brackets - I have removed a lot of code and some may have been removed accidentally! :-)
This is the fragment where I create an intent:
// Package declaring and importing stuff
public class QuickNoteFragment extends Fragment implements OnClickListener {
// Removed some stuff
EditText body;
EditText title;
Button create;
int counter = 0;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.quicknote, container, false);
body = (EditText) rootView.findViewById(R.id.qn_et_body);
title = (EditText) rootView.findViewById(R.id.qn_et_title);
create.setOnClickListener(this);
// Removed stuff
getActivity().setTitle(noter_activity); // Part of navigation drawer?
return rootView;
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.qn_b_create:
String content_text = body.getText().toString();
String content_title = title.getText().toString();
if (content_title.length() >=1){
Context context = v.getContext();
// This intent does not seem to work
Intent eIntent = new Intent(context, QuickNoteEdit.class);
eIntent.putExtra("eTitle", content_title);
eIntent.putExtra("eText", content_text);
PendingIntent EditPendingIntent = PendingIntent.getActivity(context, 0, eIntent, 0);
// This intent works comletely. This is called when a notification action button is pressed
Intent qnCancel = new Intent();
qnCancel.setAction("com.RiThBo.noter.qnCancelBroadcast");
Bundle extras = new Bundle();
extras.putInt("valueOfCounter", counter);
qnCancel.putExtras(extras);
startBroadcast(qnCancel);
PendingIntent pQnCancel = PendingIntent.getBroadcast(this.getActivity(), 0, qnCancel, 0);
// Creates Notification
} else {
// Do something
}
case R.id.*** // Does something else
}
}
private void startBroadcast(Intent qnCancel) { // This is part of the correctly working intent
// TODO Auto-generated method stub
}
}
This is the activity where I'm trying to get the extras
// Removed package and imports
public class QuickNoteEdit extends Activity implements OnClickListener {
EditText body;
EditText title;
#SuppressLint("NewApi")
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.quicknote_edit);
variableConnector(); // This gets the id for all the items in the xml
Intent intent = getIntent();
String gotTitle = intent.getStringExtra("content_title"); // This is where I think it equals null. Because the
String gotBody = intent.getStringExtra("content_text");
title.setText(gotTitle);
body.setText(gotBody);
}
private void variableConnector() {
// TODO Auto-generated method stub
body = (EditText) findViewById(R.id.qne_et_body);
title = (EditText) findViewById(R.id.qne_et_title);
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
}
}
Thank you
You're putting:
eIntent.putExtra("eTitle", content_title);
eIntent.putExtra("eText", content_text);
and when you read them:
String gotTitle = intent.getStringExtra("content_title");
String gotBody = intent.getStringExtra("content_text");
You need to match the keys ... put "eTitle" and read "eTitle", not "*content_title*"!
You're tagging your extras with "eTitle" and "eText" and trying to retrieve them with "content_title" and "content_text".
Switch to
String gotTitle = intent.getStringExtra("eTitle");
String gotBody = intent.getStringExtra("eText");
it should work.
I have an activity setup with an edittext field and an add button. Essentially when the user makes changes to the edittext and hits Add, a new textview should be created with the edittext field. In addition i want the textviews created to be available even after i leave the screen or activity. The problem i have is that when i click add, a default values shows in the newly created textview each time, and when i leave the activity, all the textviews are gone altogether. Any suggestions?
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.adddocnote);
etDocNote = (EditText) findViewById(R.id.editDocNote);
btnAdd1 = (Button) findViewById(R.id.btnAdd1);
nLayout = (LinearLayout) findViewById(R.id.linearLayout);
TextView tvNote = new TextView(this);
tvNote.setText("");
btnAdd1.setOnClickListener(onClick());
etDocNote.setOnKeyListener(new View.OnKeyListener() {
public boolean onKey(View v1, int keyCode1, KeyEvent event1) {
if ((event1.getAction() == KeyEvent.ACTION_DOWN) &&
(keyCode1 == KeyEvent.KEYCODE_ENTER)) {
getSharedPreferences("myprefs", 0).edit().putString("etDocNote", etDocNote.getText().toString()).commit();
return true;
}
return false;
}
});
}
private OnClickListener onClick() {
// TODO Auto-generated method stub
return new OnClickListener(){
public void onClick(View v) {
// TODO Auto-generated method stub
String newDocNote = getSharedPreferences("myprefs", 0).getString("etDocNote", "" );
nLayout.addView(createNewTextView(newDocNote));
}
};
}
private TextView createNewTextView(String newText) {
// TODO Auto-generated method stub
LayoutParams lparams = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
TextView tvNote = new TextView(this);
tvNote.setLayoutParams(lparams);
tvNote.setText(newText);
return tvNote;
}
}
So your question has two parts:
How do you correctly add the textView with the text from the editText:
Right now you have a timing issue. You are trying to save in shared preferences the text when someone punched keys. This is not necessary since you can retrieve the editText contents when the add button is clicked.
Here is what you need to do: Remove setOnKeyListener and change your onClick() function to be
return new OnClickListener(){
public void onClick(View v) {
// TODO Auto-generated method stub
String value = etDocNote.getText().toString();
nLayout.addView(createNewTextView(value));
// Save to shared preferences
getSharedPreferences("myprefs", 0).edit().putString("etDocNote", value).commit();
}
};
How do you restore your view when you return to the activity.
Since your text is now saved in shared preferebnces. In your oncreate, you need to retrieve and restore your TextViews.