How to retrieve and use onItemClick position for shell commands? - Java for Android App Development

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.

Related

widget SMS for android

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.

Cursor help!

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

[Q] EditText

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.

[Q] No idea how to load onChildClick in my ExpandableListView.

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 do I implement a onscroll Listener to my listview?

I have a large data to load from JSON.
I have implemented a custom list view by following a tutorial, now since the data is huge I want it load as the user scrolls.
This is my LoadRestaurant class code which is inside the main activity.
Code:
class LoadRestaurants extends AsyncTask<String, String, String> {
//Show Progress Dialog
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(SearchAll.this);
pDialog.setMessage("Loading All Restaurants...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
protected String doInBackground(String... arg) {
//building parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
//Getting JSON from URL
String json = jsonParser.makeHttpRequest(URL_RESTAURANT_LIST, "GET", params);
//Log Cat Response Check
Log.d("Areas JSON: ", "> " + json);
try {
restaurants = new JSONArray(json);
if (restaurants != null) {
//loop through all restaurants
for (int i = 0; i < restaurants.length(); i++) {
JSONObject c = restaurants.getJSONObject(i);
//Storing each json object in the variable.
String id = c.getString(TAG_ID);
String name = c.getString(TAG_NAME);
String location = c.getString(TAG_LOCATION);
String rating = c.getString(TAG_RATING);
//Creating New Hashmap
HashMap<String, String> map = new HashMap<String, String>();
//adding each child node to Hashmap key
map.put(TAG_ID, id);
map.put(TAG_NAME, name);
map.put(TAG_LOCATION, location);
map.put(TAG_RATING, rating);
//adding HashList to ArrayList
restaurant_list.add(map);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url) {
//dismiss the dialog
pDialog.dismiss();
//Updating UI from the Background Thread
runOnUiThread(new Runnable() {
@Override
public void run() {
ListAdapter adapter = new SimpleAdapter(
SearchAll.this, restaurant_list,
R.layout.listview_restaurants, new String[]{
TAG_ID, TAG_NAME, TAG_LOCATION, TAG_RATING}, new int[]{
R.id.login_id, R.id.restaurant_name, R.id.address, R.id.rating});
setListAdapter(adapter);
ListView lv = getListView();
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// Bundle bundle = new Bundle();
Intent intent = new Intent(SearchAll.this, RestaurantProfile.class);
String loginId = ((TextView) view.findViewById(R.id.login_id)).getText().toString();
intent.putExtra("login_id", loginId);
startActivity(intent);
}
});
}
});
}
}
}
I want to load around 20 restaurants and then it auto loads another 20 as soon as user reaches the end of first 20.
There are lots of tutorials online but its confusing to implement.
Please help me out!
The custom ListView, support for automatic loading you can try https://github.com/chrisbanes/Android-PullToRefresh

Categories

Resources