A user can select an item from my view to get a dialog showing different strings. Below that is a button. I would like the button, when pressed, to run a shell command. I have no idea how I would go about doing this.
Basically, how can I make the button have a command set to it, which when a user selects something in the dialog popup, runs the command + the string in the chosen view?
The class:
Code:
public static class DataSyncPreferenceFragment extends PreferenceFragment {
[user=439709]@override[/user]
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.pref_data_sync);
// Bind the summaries of EditText/List/Dialog/Ringtone preferences
// to their values. When their values change, their summaries are
// updated to reflect the new value, per the Android Design
// guidelines.
bindPreferenceSummaryToValue(findPreference("sync_frequency"));
}
}
The button
Code:
public void button1(View v) {
switch (v.getId()) {
case R.id.button1:
try {
Runtime.getRuntime().exec(new String[] { "su", "-c","HOW_DO_I_ADD_THINGS_HERE" });
} catch (IOException e) {
e.printStackTrace();
}
break;
}
}
My arrays look like this:
Code:
<string-array name="pref_sync_frequency_titles">
<item>Normal</item>
<item>Smaller</item>
<item>Smallest</item>
</string-array>
<string-array name="pref_sync_frequency_values">
<item>320</item>
<item>280</item>
<item>220</item>
</string-array>
Any help would be appreciated. I'm too new to know these things, sadly. :crying:
Here's a possible solution to what you're trying to achieve. I've had to implement something like this in my apps before, and I've made use of this helpful StackOverflow question.
Code:
new AlertDialog.Builder(this.getActivity())
//Add your titles array to the dialog (in single choice mode)
.setSingleChoiceItems(R.array.pref_sync_frequency_titles, 0, null)
.setPositiveButton(R.string.ok_button_label, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.dismiss();
int selectedPosition = ((AlertDialog)dialog).getListView().getCheckedItemPosition();
//Get the corresponding values Array
String[] strValues = getActivity().getResources().getStringArray(R.array.pref_sync_frequency_values);
//Get the corresponding value that was clicked
String yourValue = strValues[selectedPosition];
try {
Runtime.getRuntime().exec(new String[] { "su", "-c","HOW_DO_I_ADD_THINGS_HERE" + yourValue });
} catch (IOException e) {
e.printStackTrace();
}
}
})
.show();
Let me know how that works!
Related
i have a problem with ListView, i don't view line separator for each item, why ? see where is mouse pointer:
h_t_t_p://tinyurl.com/2vqg52n
and this is source code:
Java Class:
Code:
public class ScienzeInfoNewsActivity extends Activity {
private class Link {
private String title;
private String href;
public Link(String title, String href) {
this.title = title;
this.href = href;
}
public String toString() {
return title;
}
public String getHref() {
return href;
}
}
private FeedReader feedReader;
private ArrayAdapter<Link> adapter;
private ListView list;
public void initialize() {
adapter = new ArrayAdapter<Link>(this, R.layout.textview);
list = (ListView) findViewById(R.id.ListView01);
list.setAdapter(adapter);
}
/** Called when the activity is first created. */
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
initialize();
loadFeeds(adapter);
setAllListener();
}
private void setAllListener() {
list.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> a, View v, int position,
long id) {
String link = adapter.getItem((int) id).getHref();
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(link));
startActivity(intent);
}
});
Button exit = (Button) findViewById(R.id.Button02);
exit.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
ScienzeInfoNewsActivity.this.finish();
}
});
Button refresh = (Button) findViewById(R.id.Button01);
refresh.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
loadFeeds(adapter);
}
});
}
private void loadFeeds(ArrayAdapter<Link> adapter) {
if (adapter != null)
adapter.clear();
try {
feedReader = new FeedReader(new URL(
"rss.php"));
String feeds[][] = feedReader.getFeeds();
for (int i = 0; i < feeds.length; i++) {
adapter.add(new Link(feeds[i][0], feeds[i][1]));
}
} catch (Exception e) {
Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();
}
}
}
R.layout.textview:
Code:
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="h_t_t_p://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="10dp"
android:textSize="16sp" >
</TextView>
I load entry item with this function loadFeeds()
If i select one of the items without a separator, it just one item.
Thanks for any reply.
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.
Hi all skilled developers,
I am a newbie in coding, and I just want to make some small changes to my app.
It is a licensing feature.
1) Licensee information are stored at a very simple website. With columns for Names, IMEI and Remarks.
2) I have the following chunk of code:
Code:
if(hadLicense) {
new AlertDialog.Builder(InsuranceGuruSplash.this)
.setTitle("License")
.setMessage("Your device is registered.\nWelcome.")
.setPositiveButton("Send", new DialogInterface.OnClickListener()
Intent intent = new Intent(InsuranceGuruSplash.this, MainActivity.class);
startActivity(intent);
finish();
I want to show a toast saying,
Welcome, Shawn. Your device is registered till DD/MM/YY.
Click to expand...
Click to collapse
Can someone teach me how I can go about doing this?:silly:
You can show a toast using:
Code:
Toast.makeText(context, text, duration).show();
Just make the text String first with the text and time. For duration use Toast.LENGTH_SHORT
SimplicityApks,
Thanks for your reply. I still don't really know what you mean. how do I echo a text from a website into the app's toast?
This is the full code:
Code:
protected Void doInBackground(Void... params) {
String url_for_sale = "www(dot)heyfellas(dot)com/guru/index.php";
parseLicense(url_for_sale);
return null;
}
@Override
protected void onPostExecute(Void result) {
TelephonyManager mngr = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
final String imei = mngr.getDeviceId();
boolean hadLicense = false;
for(LicenseInfo license: licenses) {
if(license.phoneIMEI.equals(imei))
hadLicense = true;
}
if(hadLicense) {
Intent intent = new Intent(InsuranceGuruSplash.this, MainActivity.class);
startActivity(intent);
finish();
} else {
new AlertDialog.Builder(InsuranceGuruSplash.this)
.setTitle("License")
.setMessage("Your device is not registered.\nPlease send your details to the admin.")
.setPositiveButton("Send", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
finish();
Intent i = new Intent(Intent.ACTION_SEND);
i.setType("message/rfc822");
i.putExtra(Intent.EXTRA_EMAIL , new String[]{"[email protected]"});
i.putExtra(Intent.EXTRA_SUBJECT, "Request for license");
i.putExtra(Intent.EXTRA_TEXT , "UserName: \n\nPhone Number: \n\nEmail: \n\nIMEI: " + imei);
try {
startActivity(Intent.createChooser(i, "Send mail..."));
} catch (android.content.ActivityNotFoundException ex) {
Toast.makeText(PropertyGuruSplash.this, "There are no email clients installed.", Toast.LENGTH_SHORT).show();
}
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
})
.create().show();
}
}
}
You need
[java]
String name = ...;
String date = ....;
Toast.makeToast(Activity.this, name + ", you have registered since "+date, Toast.LENGTH_SHORT).show();[/java]
I suppose, you are strong at server side than in client programming? Then echo the result in your desired format in your php and read it in java then display it in toast. Use the below snippet:
Code:
HttpClient httpclient=new DefaultHttpClient();
HttpPost httppost=new HttpPost("http://www(dot)heyfellas(dot)com/guru/index.php");
HttpResponse response = httpclient.execute(httppost);
String Result = EntityUtils.toString(response.getEntity());
Toast.makeText(Context, Result, Toast.LENGTH_SHORT).show();
I am writing an IRC Client, and so far as long as I dont send the app to the background and try to restore it it works fine. Tabs for multiple channels, the connected socket is in a bound service (started separately via INTENT and a startService call), etc and so on.
However, whenever I send the app to the background, then bring it back forward, the socket closes. I would have the same issue with screen rotation but I found the config setting that stops it from going through destroy/create on rotation. If I figure this out I may actually get rid of that since the issue will have been solved.
The other issue I seem to be having is that it takes a long time to re-bind to the service, and I have no idea why (the initial binding and startup is pretty quick, but re-binding to it seems to take forever, and when It does re-bind, the socket is closed).
Here are the code samples that I feel to be relevant, let me know if there's something more specific you want to see.
Code:
//This is the Service in question
public class ConnectionService extends Service{
private BlockingQueue<String> MessageQueue;
public final IBinder myBind = new ConnectionBinder();
public class ConnectionBinder extends Binder {
ConnectionService getService() {
return ConnectionService.this;
}
}
private Socket socket;
private BufferedWriter writer;
private BufferedReader reader;
private IRCServer server;
private WifiManager.WifiLock wLock;
private Thread readThread = new Thread(new Runnable() {
@Override
public void run() {
try {
String line;
while ((line = reader.readLine( )) != null) {
//message parsing stuff
}
}
catch (Exception e) {}
}
});
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
if(MessageQueue == null)
MessageQueue = new LinkedBlockingQueue<String>();
return Service.START_STICKY;
}
@Override
public IBinder onBind(Intent arg0) {
return myBind;
}
@Override
public boolean stopService(Intent name) {
try {
socket.close();
wLock.release();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return super.stopService(name);
}
@Override
public void onDestroy()
{//I put this here so I had a breakpoint in place to make sure this wasn't firing instead of stopService
try {
socket.close();
wLock.release();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
super.onDestroy();
}
public void SendMessage(String message)
{
try {
writer.write(message + "\r\n");
writer.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
public String readLine()
{//this is called by the activity which consumes the service. Its just an accessor to MessageQueue
try {
if(!isConnected())
return null;
else
return MessageQueue.take();
} catch (InterruptedException e) {
return "";
}
}
public boolean ConnectToServer(IRCServer newServer)
{
try {
//create a new message queue (connecting to a new server)
MessageQueue = new LinkedBlockingQueue<String>();
//lock the wifi
WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
wLock = wifiManager.createWifiLock(WifiManager.WIFI_MODE_FULL, "LockTag");
wLock.acquire();
server = newServer;
//connect to server
socket = new Socket();
socket.setKeepAlive(true);
socket.setSoTimeout(60000);
socket.connect(new InetSocketAddress(server.NAME, Integer.parseInt(server.PORT)), 10000);
writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
reader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
//run basic login scripts.
String line;
while ((line = reader.readLine( )) != null) {
//server initialization stuff
}
//start the reader thread AFTER the primary login!!!
CheckStartReader();
if(server.START_CHANNEL == null || server.START_CHANNEL == "")
{
server.WriteCommand("/join " + server.START_CHANNEL);
}
//we're done here, go home everyone
} catch (NumberFormatException e) {
return false;
} catch (IOException e) {
return false;
}
return true;
}
private void queueMessage(String line) {
try {
MessageQueue.put(line);
} catch (InterruptedException e) {
}
}
public boolean isConnected()
{
return socket.isConnected();
}
public void CheckStartReader()
{
if(this.isConnected() && !readThread.isAlive())
readThread.start();
}
}
Code:
//Here are the relevant portions of the hosting Activity that connects to the service
//NOTE: THE FOLLOWING CODE IS PART OF THE ACTIVITY, NOT THE SERVICE
private ConnectionService conn;
private ServiceConnection mConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
conn = ((ConnectionService.ConnectionBinder)service).getService();
//debug toast
Toast.makeText(main_tab_page.this, "Connected", Toast.LENGTH_SHORT)
.show();
synchronized (_serviceConnWait) {
_serviceConnWait.notify();
}
}
@Override
public void onServiceDisconnected(ComponentName name) {
conn = null;//does this even run? Breakpoint here
}
};
@Override
protected void onSaveInstanceState(Bundle state){
super.onSaveInstanceState(state);
state.putParcelable("Server", server);
state.putString("Window", CurrentTabWindow.GetName());
//have to unbind, othewise we get that leaked service exception
unbindService(mConnection);
}
@Override
protected void onDestroy()
{
super.onDestroy();
if(this.isFinishing())
stopService(new Intent(this, ConnectionService.class));
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_tab_page);
localTabHost = (TabHost)findViewById(R.id.tabHostMain);
localTabHost.setup();
localTabHost.setOnTabChangedListener(new tabChange());
_serviceConnWait = new Object();
if(savedInstanceState == null)
{//initial startup, coming from Intent to start
//get server definition
server = (IRCServer)this.getIntent().getParcelableExtra(IRC_WINDOW);
server.addObserver(this);
AddTabView(server);
//this should only run the first time, all other calls to OnCreate should have something in SavedInstanceState
startService(new Intent(this, ConnectionService.class));
}
else
{
server = (IRCServer)savedInstanceState.getParcelable("Server");
String windowName = savedInstanceState.getString("Window");
//Add Needed Tabs
//Server
if(!(windowName.equals(server.GetName())))
AddTabView(server);
//channels
for(IRCChannel c : server.GetAllChannels())
if(!(windowName.equals(c.GetName())))
AddTabView(c);
//reset each view's text (handled by tabChange)
if(windowName.equals(server.GetName()))
SetCurrentTab(server.NAME);
else
SetCurrentTab(windowName);
ResetMainView(CurrentTabWindow.GetWindowTextSpan());
//Rebind to service
BindToService(new Intent(this, ConnectionService.class));
}
}
@Override
protected void onStart()
{
super.onStart();
final Intent ServiceIntent = new Intent(this, ConnectionService.class);
//check start connection service
final Thread serverConnect = new Thread(new Runnable() {
@Override
public void run() {
if(!BindToService(ServiceIntent))
return;
server.conn = conn;
conn.ConnectToServer(server);
server.StartReader();
if(server.START_CHANNEL != null && !server.START_CHANNEL.equals(""))
{
IRCChannel chan = server.FindChannel(server.START_CHANNEL);
if(chan != null)
{
AddTabView(chan);
}
else
{
server.JoinChannel(server.START_CHANNEL);
chan = server.FindChannel(server.START_CHANNEL);
AddTabView(chan);
}
}
}
});
serverConnect.start();
}
private boolean BindToService(Intent ServiceIntent)
{
int tryCount = 0;
bindService(ServiceIntent, mConnection, Context.BIND_AUTO_CREATE);
while(conn == null && tryCount < 10)
{
tryCount++;
try {
synchronized (_serviceConnWait) {
_serviceConnWait.wait(1500);
}
}
catch (InterruptedException e) {
//do nothing
}
}
return conn != null;
}
Logcat...well...there isn't really any exception thrown, the code runs just fine...except that it closes the socket. I suppose that counts as an exception. Whenever I run the socket write command It throws a "Socket Closed" exception at me. No other crash involved.
My need: I want to extract the links of websites that appear on Google search result page and display them in a textView. The Google search may vary according to the user's needs. The purpose of this (app) is to get the most related, nearest results for the user.
The mechanism is when the user inputs their search words and clicked on the button, the links that are extracted should appear on the textView.
Errors: I don't get an error in the code or any results on the textView.
My Question: Where have I gone wrong? How can I correct it? Is there any other way to do this?
TestHomeFragment.java
public class TestHomeFragment extends Fragment {
ImageButton b_search;
TextView search_webview;
String userLocation = "Sri Lanka";
TextView textView;
List<String> sriLankanUrls;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.test_home_fragment, container, false);
// --------------------------- Search Mechanism -----------------------------------------//
sriLankanUrls = new ArrayList<>();
b_search.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View view) {
String searchQuery="buy "+et_search.getText().toString()+ " in " + userLocation ;
new GoogleSearchScraperTask().execute();
}
}); return view;
}
private class GoogleSearchScraperTask extends AsyncTask<Void, Void, StringBuilder> {
@Override
protected StringBuilder doInBackground(Void... voids) {
StringBuilder resultBuilder = new StringBuilder();
try {
// Specify the Google search query
String searchQuery="buy "+et_search.getText().toString()+ " in " + userLocation ;
// Fetch the search results page
Document doc = Jsoup.connect("https://www.google.com/search?q=" + searchQuery).get();
// Extract sentences containing "https://"
Elements searchResults = doc.select("div.g");
for (Element result : searchResults) {
String snippet = result.select("span.st").text();
if (snippet.contains("http")) {
resultBuilder.append(snippet).append("\n");
}
}
} catch (IOException e) {
e.printStackTrace();
}return resultBuilder;
}
@Override
protected void onPostExecute(StringBuilder resultBuilder) {
super.onPostExecute(resultBuilder);
// Set the scraped sentences in the TextView
textView.setText(resultBuilder.toString());
}
}
}