how can I get an EditText to save it's contents to a string as soon as a person types/changes a letter?
Code:
EditText name = new EditText(context);
name.setText(mystr);
linear.addView(name);
name.setOnClickListener(
new OnClickListener()
{
public void onClick(View v)
{
mystr + "";
}
}
);
OnClickListener is probably the wrong class, but also how do I get it to go to a non-static string?
(I want this done without an "OK" or a "loses focus", but to be as the person types it)
edit: also how do I make it so that when a person types "enter", it exits instead of expanding the box?
you need an on edit listener:
(play around with the if statement as you need)
Code:
private TextView.OnEditorActionListener mWriteListener =
new TextView.OnEditorActionListener()
{
public boolean onEditorAction(TextView v, int actionId, KeyEvent e)
{
// If the action is a key-up event on the return key
if (actionId == EditorInfo.IME_NULL &&
e.getAction() == KeyEvent.ACTION_UP)
{
//sexy code here
//like v.getText();
}
return true;
}
};
//elsewhere
myEditTextInstance.setOnEditorActionListener ( mWriteListener );
ah, so now I have this
Code:
EditText name = new EditText(context);
name.setText(mydata[index].name);
linear.addView(name);
name.setOnEditorActionListener(
new OnEditorActionListener()
{
public boolean onEditorAction(TextView arg0, int arg1,
KeyEvent arg2)
{
// If the action is a key-up event on the return key
if (arg1 == EditorInfo.IME_NULL &&
arg2.getAction() == KeyEvent.ACTION_UP)
mydata[index].name = [COLOR="red"]name.getText()[/COLOR] + "";
return false;
}
}
);
but I have this problem:
"Cannot refer to a non-final variable name inside an inner class defined in a different method"
- how do I get this data to outside of the function?
Either change "EditText name" to "final EditText name"
or
Create the variable outside of the function:
EditText name;
public void someFunction() {
name = new EditText.....
}
I still can't get it to work:
Code:
EditText name = new EditText(context);
name.setText(mydata[index].name);
linear.addView(name);
[COLOR="Lime"]final [/COLOR]OnEditorActionListener edit = new OnEditorActionListener()
{
public boolean onEditorAction(TextView arg0, int arg1,
KeyEvent arg2)
{
// If the action is a key-up event on the return key
if (arg1 == EditorInfo.IME_NULL &&
arg2.getAction() == KeyEvent.ACTION_UP)
mydata[index].name = [COLOR="Red"]name.getText() [/COLOR]+ "";
return false;
}
};
name.setOnEditorActionListener(edit);
with and without the green final, it still won't let me reference it
Cannot refer to a non-final variable name inside an inner class defined in a different method
Click to expand...
Click to collapse
slapshot136 said:
I still can't get it to work:
with and without the green final, it still won't let me reference it
Click to expand...
Click to collapse
Instead of adding final to the edit listener, it needs to be with the EditText declaration/initialization as Lakers16 suggested. So remove the green final and make the first line this:
Code:
final EditText name = new EditText(context)
ah it works now
Code:
final EditText name = new EditText(context);
name.setText(mydata[index].name);
linear.addView(name);
name.setOnEditorActionListener(new OnEditorActionListener()
{
public boolean onEditorAction(TextView arg0, int arg1,
KeyEvent arg2)
{
// If the action is a key-up event on the return key
if (arg1 == EditorInfo.IME_NULL &&
arg2.getAction() == KeyEvent.ACTION_UP)
mydata[index].name = name.getText() + "";
return false;
}
});
thanks everyone
Just fyi, it doesnt have to be final (though that's one perfectly good way to do it) it just has to be a class member and not a local variable.
It looks like you defined all that within some other method, hence "name" is a local variable instead of a class-level variable.
edit:
Also, in your code, arg0 should be the EditText field, so if you dont want to define it outside as a class level variable, you can also call getText() on arg0.
Related
Hello,
I'm trying to write code of a widget sms for android. But I have a problem of cursor, after lot of test on compiling I dircoverd that
Code:
Cursor c = context.getContentResolver().query(Uri.parse("content://sms/"), null, null ,null,null);
make an error and I don't no why. If somebody knows how use a cursor or have a better idea to view sms without cursor, I woold like share it with him!
thank's
try something like this
Code:
Uri uriSms = Uri.parse("content://sms/inbox");
Cursor c = getContentResolver().query(uriSms, null,null,null,null);
Thank's to you Draffodx, I such begin my widget, now it can put on screen the sms I want... but I can't change of SMS with th button I've created. I don't understand how make a button with the widget because it need to be an Activity for a button and I've made an AppWidget...
I trying to do like this:
Code:
public class MySMSwidget extends AppWidgetProvider implements View.OnClickListener {
private Button Bnext;
private int sms_id=0;
public class MyActivity extends Activity {
protected void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.widget_layout);
final Button button = (Button) findViewById(R.id.next);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (v==Bnext){sms_id=sms_id+1;}
}
});
}
}.... and the rest of the code
But when I click the button, nothing happend.
hey, my idea seems to be a bad idea so I try this way:
Code:
public class MySMSwidget extends AppWidgetProvider {
private int sms_id=0;
public void onReceive (Context context, Intent intent){
if (Intent.ACTION_ATTACH_DATA.equals(intent.getAction()))
{
Bundle extra = intent.getExtras();
sms_id = extra.getInt("Data");
}
}
public void onUpdate(Context context, AppWidgetManager
appWidgetManager, int[] appWidgetIds) {
Cursor c = context.getContentResolver().query(Uri.parse("content://
sms/inbox"), null, null ,null,null);
String body = null;
String number = null;
String date = null;
c.moveToPosition(sms_id);
body = c.getString(c.getColumnIndexOrThrow("body")).toString();
number =
c.getString(c.getColumnIndexOrThrow("address")).toString();
date = c.getString(c.getColumnIndexOrThrow("date")).toString();
c.close();
RemoteViews updateViews = new RemoteViews(context.getPackageName(),
R.layout.widget_layout);
updateViews.setTextColor(R.id.text, 0xFF000000);
updateViews.setTextViewText(R.id.text,date+'\n'+number+'\n'+body);
ComponentName thisWidget = new ComponentName(context,
MySMSwidget.class);
appWidgetManager.updateAppWidget(thisWidget, updateViews);
IntentFilter filter = new IntentFilter();
filter.addAction(Intent.ACTION_ATTACH_DATA);
RemoteViews views = new RemoteViews(context.getPackageName(),
R.layout.widget_layout);
views.setOnClickPendingIntent(R.id.next, changeData(context));
}
private PendingIntent changeData(Context context) {
Intent Next = new Intent();
Next.putExtra("Data", sms_id+1);
Next.setAction(Intent.ACTION_ATTACH_DATA);
return(PendingIntent.getBroadcast(context,
0, Next, PendingIntent.FLAG_UPDATE_CURRENT));
}
}
my code isn't terminated.
I hope there will be someone to help to correct it.
Just want to display next SMS.
Please help.
In Googles sample Notepad app (the final version using NotepadV3Solution), if you select Add Note (launching the NoteEdit activity), then just hit the back button, a blank line is then inserted into the Notepad activity, and it cannot be deleted. Does anyone know why? Below is the java code for this activity...
package com.android.demo.notepad3;
import android.app.Activity;
import android.database.Cursor;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class NoteEdit extends Activity {
private EditText mTitleText;
private EditText mBodyText;
private Long mRowId;
private NotesDbAdapter mDbHelper;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mDbHelper = new NotesDbAdapter(this);
mDbHelper.open();
setContentView(R.layout.note_edit);
mTitleText = (EditText) findViewById(R.id.title);
mBodyText = (EditText) findViewById(R.id.body);
Button confirmButton = (Button) findViewById(R.id.confirm);
mRowId = savedInstanceState != null ? savedInstanceState.getLong(NotesDbAdapter.KEY_ROWID)
: null;
if (mRowId == null) {
Bundle extras = getIntent().getExtras();
mRowId = extras != null ? extras.getLong(NotesDbAdapter.KEY_ROWID)
: null;
}
populateFields();
confirmButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
setResult(RESULT_OK);
finish();
}
});
}
private void populateFields() {
if (mRowId != null) {
Cursor note = mDbHelper.fetchNote(mRowId);
startManagingCursor(note);
mTitleText.setText(note.getString(
note.getColumnIndexOrThrow(NotesDbAdapter.KEY_TITLE)));
mBodyText.setText(note.getString(
note.getColumnIndexOrThrow(NotesDbAdapter.KEY_BODY)));
}
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putLong(NotesDbAdapter.KEY_ROWID, mRowId);
}
@Override
protected void onPause() {
super.onPause();
saveState();
}
@Override
protected void onResume() {
super.onResume();
populateFields();
}
private void saveState() {
String title = mTitleText.getText().toString();
String body = mBodyText.getText().toString();
if (mRowId == null) {
long id = mDbHelper.createNote(title, body);
if (id > 0) {
mRowId = id;
}
} else {
mDbHelper.updateNote(mRowId, title, body);
}
}
}
When you hit the back button the onpause function is called which calls savestate. In savestate it doesn't check to see it fields title and body are blank. So it writes a record with blank or null values.
________________________________
http://ron-droid.blogspot.com
I'm still trying to figure all this java out. Any chance you could tell me specifically what I need to add to fix it?
greydarrah said:
I'm still trying to figure all this java out. Any chance you could tell me specifically what I need to add to fix it?
Click to expand...
Click to collapse
Modify the saveState() function to check to see if the body or titles are empty.
You can do something like:
Code:
if (title.isEmpty() || body.isEmpty())
return;
Which will make the save state not needlessly update or add to the db if a field is blank. This disallows you to add blank notes though (ie. notes with only a title, no body). Though I'm OK with that. But the save-state is where you want to start, because that's what's happening.
And for the love of Christ please wrap your code in code tags (select the code, hit the # sign in the top menu bar).
I'd do something like this;
private void saveState() {
String title = mTitleText.getText().toString();
String body = mBodyText.getText().toString();
If (title == null || title == "") return;
________________________________
http://ron-droid.blogspot.com
rigman said:
I'd do something like this;
private void saveState() {
String title = mTitleText.getText().toString();
String body = mBodyText.getText().toString();
If (title == null || title == "") return;
________________________________
http://ron-droid.blogspot.com
Click to expand...
Click to collapse
I'm sorry for being such an idiot, but when I put:
If (title == null || title == "") return;
in saveState, I get red mark right after the closing paren (just before return. If I hold my cursor over the red mark, it says syntax error, insert ";" to complete statement. Any idea why Eclipse doesn't like this?
Edit...A little more to the story:
The first error I got was this...
The method fi(boolean) is undefined fo rthe type NoteEdit
Quick fix: create method If(boolean)
So I did the quick fix. Now I'm thinking that I should add a ";" at the end if the if statement and put the return; in the new If(boolean) mentod. It would look like this:
Code:
private void saveState() {
String title = mTitleText.getText().toString();
String body = mBodyText.getText().toString();
If (title == null || title == "");
if (mRowId == null) {
long id = mDbHelper.createNote(title, body);
if (id > 0) {
mRowId = id;
}
} else {
mDbHelper.updateNote(mRowId, title, body);
}
}
private void If(boolean b) {
// TODO Auto-generated method stub
return;
}
Is that correct, or am I totally retarded?
Well, I'm not sure what's going on in the code above, but it doesn't work...still inserts blank lines. I wish I knew more about what I'm doing.
If anyone can help me figure this out, I'm ONLY concerned with the note title (if it equals "", don't save the blank line). I don't care if the body has text in it or not.
greydarrah said:
Well, I'm not sure what's going on in the code above, but it doesn't work...still inserts blank lines. I wish I knew more about what I'm doing.
If anyone can help me figure this out, I'm ONLY concerned with the note title (if it equals "", don't save the blank line). I don't care if the body has text in it or not.
Click to expand...
Click to collapse
I'm sorry, I thought isEmpty() was a standard function of the String library in Java.
Aside from that, can I ask what your issue is with my solution?
If you don't want to check to see if the body is empty, don't. If you are only concerned with whether or not the title is empty, use Java's built in string functionality. So in your saveState function, put this after:
Code:
String title = mTitleText.getText().toString();
String body = mBodyText.getText().toString();
if (title.length() == 0) // if string length is 0
{
return;
}
What this will do, is if the title is empty (ie. == "") it will return from the saveState function, without updating or adding the note to the database. You CANNOT use the "==" operator, as that will run a comparison of the objects (to see if they're the same string instance), ie.:
Code:
String a = "hi";
String b = "hi";
if (a == b); // false
if (a.equals(b)); // true ([I]this calls the comparison operator on the strings, which is built into the String class[/I])
if (a == a); // true (they're the same object)
If you're checking to see if a string is empty, you can do:
Code:
if (a.equals("")) ... // checks if it's the equivalent of the empty string
OR
if (a.length() == 0) ... // Checks if size of string is 0
Either will work. Hopefully that clears it up for you, you can check if the String is empty, or you can see if it equals the empty string.
It sounds like you're new to programming in general, is this the case? Or are you just new to Android? If you are more accustomed to another language I can possibly (probably) give you better analogies from there...unless it's some weird language .
Syndacate said:
I'm sorry, I thought isEmpty() was a standard function of the String library in Java.
Aside from that, can I ask what your issue is with my solution?
If you don't want to check to see if the body is empty, don't. If you are only concerned with whether or not the title is empty, use Java's built in string functionality. So in your saveState function, put this after:
Code:
String title = mTitleText.getText().toString();
String body = mBodyText.getText().toString();
if (title.length() == 0) // if string length is 0
{
return;
}
Click to expand...
Click to collapse
Thanks so much. This worked perfectly. As to my programming, I'm a long time VB programmer (since VB 3), but brand new to java. In these early stages, I'm having issues getting my mind wrapped around it, but I'll get there.
I'm thankful to everyone that responded to this thread. This is how a forum should work.
greydarrah said:
As to my programming, I'm a long time VB programmer (since VB 3), but brand new to java.
Click to expand...
Click to collapse
That explains your syntax error problems above. Unlike VB, Java is case-sensitive, and you used an upper-case "If" instead of the correct lower-case "if". The compiler did not recognize this as a keyword and assumed you wanted to use a method called "If(boolean)" but forgot to define it.
So, change all capital letters in all keywords to lower case, and remove the auto-generated "If(boolean)" method again.
Cheers
tadzio
greydarrah said:
Thanks so much. This worked perfectly. As to my programming, I'm a long time VB programmer (since VB 3), but brand new to java. In these early stages, I'm having issues getting my mind wrapped around it, but I'll get there.
I'm thankful to everyone that responded to this thread. This is how a forum should work.
Click to expand...
Click to collapse
Ah, I see. Haven't used VB in forever, barely remember it, haha. Glad it works for you, though.
I'm new to using cursors to obtain data from the device. I'm working on a music player (see market link in signature) and I need to be able to list (and eventually play) the music found on the sdcard. I have some code, but I can't seem to get it to work
Here's the code I found on a website, but it leads to a force-close:
public class TestingData extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
TextView view = (TextView) findViewById(R.id.hello);
String[] projection = new String[] {
MediaStore.MediaColumns.DISPLAY_NAME
, MediaStore.MediaColumns.DATE_ADDED
, MediaStore.MediaColumns.MIME_TYPE
};
Cursor mCur = managedQuery(Media.EXTERNAL_CONTENT_URI,
projection, null, null, null
);
mCur.moveToFirst();
while (mCur.isAfterLast() == false) {
for (int i=0; i<mCur.getColumnCount(); i++) {
view.append("n" + mCur.getString(i));
}
mCur.moveToNext();
}
}
}
Here's my attempt at fixing it, which still leads to a force-close:
public class test3 extends Activity {
TextView view = (TextView) findViewById(R.id.text1);
ListView list;
private ArrayAdapter<String> adapter;
String[] projection = new String[] {
MediaStore.MediaColumns.DISPLAY_NAME
, MediaStore.MediaColumns.DATE_ADDED
, MediaStore.MediaColumns.MIME_TYPE
};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
list = (ListView)findViewById(R.id.list);
ArrayList<String> _list = new ArrayList<String>(Arrays.asList(projection));
adapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,_list);
list.setAdapter(adapter);
Cursor mCur = managedQuery(Media.EXTERNAL_CONTENT_URI,
projection, null, null,
MediaStore.MediaColumns.DISPLAY_NAME + "ASC"
);
mCur.moveToFirst();
while (mCur.isAfterLast() == false) {
for (int i=0; i<mCur.getColumnCount(); i++) {
view.append("n" + mCur.getString(i));
}
mCur.moveToNext();
}
}
}
What am I doing wrong? Both codes lead to a force-close and I can't think of anything else to do. Thanks in advance.
did you set the correct permissions in the android manifest?
*slaps hand to forehead* I always forget about the manifest. Lol. Ummmm....what all am I supposed to put in there for these codes? Do both codes look like they would accomplish the same thing?
Well, I've written hundreds of Cursors in Android and I don't run my loop like you do, so, as a suggestion:
Code:
Cursror c = yada, yada;
if(c.moveToFirst()) {
do {
// TO DO HERE...
} while(c.moveToNext());
}
c.close();
Never had a problem.
Awesome! Thanks. Ill try it when I get a chance
I have an expandable list view with 2 parents and 3 children. I want to open a dialog based on each click. I can't find any examples showing you how to call something based on positions. At least not with the ExpandableListView tutorial I followed.
Code:
public class MainActivity extends Activity implements OnClickListener {
private LinkedHashMap<String, HeaderInfo> myDepartments = new LinkedHashMap<String, HeaderInfo>();
private ArrayList<HeaderInfo> deptList = new ArrayList<HeaderInfo>();
private MyListAdapter listAdapter;
private ExpandableListView myList;
[user=439709]@override[/user]
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Just add some data to start with
loadData();
// get reference to the ExpandableListView
myList = (ExpandableListView) findViewById(R.id.myList);
// create the adapter by passing your ArrayList data
listAdapter = new MyListAdapter(MainActivity.this, deptList);
// attach the adapter to the list
myList.setAdapter(listAdapter);
// listener for child row click
myList.setOnChildClickListener(myListItemClicked);
// listener for group heading click
myList.setOnGroupClickListener(myListGroupClicked);
}
// load some initial data into out list
private void loadData() {
addProduct("Parent One", "Child One");
addProduct("Parent One", "Child Two");
addProduct("Parent One", "Child Three");
addProduct("Parent Two", "Child One");
addProduct("Parent Two", "Child Two");
addProduct("Parent Two", "Child Three");
}
// our child listener
private OnChildClickListener myListItemClicked = new OnChildClickListener() {
[user=439709]@override[/user]
public boolean onChildClick(ExpandableListView parent, View v,
int groupPosition, int childPosition, long id) {
// Create a switch that switches on the specific child position.
// get the group header
HeaderInfo headerInfo = deptList.get(groupPosition);
// get the child info
DetailInfo detailInfo = headerInfo.getProductList().get(
childPosition);
// display it or do something with it
// custom dialog
final Dialog dialog = new Dialog(MainActivity.this);
dialog.setContentView(R.layout.cdialog);
// dialog.setTitle(R.id.titlebar);
dialog.setTitle(R.string.titlebar);
dialog.show();
return false;
}
};
// our group listener
private OnGroupClickListener myListGroupClicked = new OnGroupClickListener() {
public boolean onGroupClick(ExpandableListView parent, View v,
int groupPosition, long id) {
// get the group header HeaderInfo headerInfo =
deptList.get(groupPosition);
// display it or do something with it
return false;
}
};
I can get a custom dialog open if I click a child, but it's not set to any specific parent and child.
Any ideas?
EDIT ADD: Got it. Tried a switch/case like this and it worked. Finally! After two days of trying to understand it.:fingers-crossed:
Code:
switch(groupPosition) {
case 1:
switch (childPosition) {
case 0:
Intent protheanIntent = new Intent(Codex.this, CodexProthean.class);
Codex.this.startActivity(protheanIntent);
break;
case 1:
Intent rachniIntent = new Intent(Codex.this, CodexRachni.class);
Codex.this.startActivity(rachniIntent);
break;
}
case 2:
switch (childPosition) {
case 2:
Intent asariIntent = new Intent(Codex.this, CodexAsari.class);
Codex.this.startActivity(asariIntent);
break;
}
}
How can I use the onItemClick position? I am able to do so with switch/case, but I am not able to figure out how to do it straight into a shell command. If I use switch/case my class file is going to be huge.
Class:
Code:
public class CustomDialogClass extends Activity {
[user=439709]@override[/user]
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_main);
LayoutParams params = getWindow().getAttributes();
params.width = 300;
params.height = 600;
getWindow().setAttributes((android.view.WindowManager.LayoutParams) params);
//requestWindowFeature(Window.FEATURE_NO_TITLE);
final ListView listview = (ListView) findViewById(R.id.listView);
String[] values = new String[] { "first", "second", "third" };
final ArrayList<String> list = new ArrayList<String>();
for (int i = 0; i < values.length; ++i) {
list.add(values[i]);
}
final StableArrayAdapter adapter = new StableArrayAdapter(this,
R.layout.arraystyle, list);
listview.setAdapter(adapter);
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
[user=439709]@override[/user]
public void onItemClick(AdapterView<?> parent, final View view,
int position, long id) {
// What to do? :<
}
//////////////////////////
});
}
private 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);
}
}
[user=439709]@override[/user]
public long getItemId(int position) {
String item = getItem(position);
return mIdMap.get(item);
}
[user=439709]@override[/user]
public boolean hasStableIds() {
return true;
}
}
}
The command I want to use upon onClick
Code:
Process = Runtime.getRuntime().exec("su");
DataOutputStream out = new DataOutputStream(suProcess.getOutputStream());
out.flush();
out.close();
How can I run it like Process suProcess = Runtime.getRuntime().exec("su " + position); ?
PS: Yes I know "su first", "su second" aren't real commands. Just trying to figure this out.
Use su -c:
Code:
runtime.exec(new String[] {"su", "-c", "mkdir /data/data/aaab; mkdir /data/data/aaac"});
The semicolon divides different commands.
However, I recommend using the roottools library. It is much easier: http://code.google.com/p/roottools/wiki/Usage
I know about -c. I was asking how I could execute the command + whatever someone clicks on my menu. My menu is just a listview with numbers/words, and I would like for onClick to parse the command + position, where position is the button they clicked (the string).
nex7er said:
I know about -c. I was asking how I could execute the command + whatever someone clicks on my menu. My menu is just a listview with numbers/words, and I would like for onClick to parse the command + position, where position is the button they clicked (the string).
Click to expand...
Click to collapse
Turn your class into a ListActivity or ListFragment.
Then override the onListItemClicked method. One parameter is the view v which is clicked. If it is a layout you can get the TextView that way:
Code:
v.findViewById( <your id >)
Get its text using the getText() method.
A second way to achieve the same would be getting the position (the third parameter) and getting the value from the Collection you used for the Adapter.