My app has main.xml and MainActivity. I wanted to convert it to a tabbed styled app. By the help of this tutorial, I've successfully made a UI with a tabbed style.
Now I have to put the codes in my MainActivty(not tabbed style) to the fragments. i don't know how to do it. when i just put the codes to my ToolsFragment.java, it doesn't work.
Here are my codes:
//To get ip address using netcfg
private String ipnc()
{
int e = doNETCFG().indexOf("10.");
if (e == -1)
{
return "";
}
else
{
String ipnc1 = doNETCFG().substring(e, e + 15);
String ipnc2[] = ipnc1.split("/");
String ipnc3 = ipnc2[0];
return ipnc3;
}
}
//To generate netcfg from command line
public String doNETCFG()
{
String str = null;
try
{
Process localProcess = Runtime.getRuntime().exec("/system/bin/netcfg");
BufferedReader localBufferedReader = new BufferedReader(new InputStreamReader(localProcess.getInputStream()));
char[] arrayOfChar = new char[4096];
StringBuffer localStringBuffer = new StringBuffer();
while (true)
{
int i = localBufferedReader.read(arrayOfChar);
if (i <= 0)
{
localBufferedReader.close();
localProcess.waitFor();
str = localStringBuffer.toString();
break;
}
localStringBuffer.append(arrayOfChar, 0, i);
}
}
catch (IOException localIOException)
{
Log.e("TAG", localIOException.getStackTrace().toString());
}
catch (InterruptedException localInterruptedException)
{
Log.e("TAG", localInterruptedException.getStackTrace().toString());
}
return str;
}
//To enable/disable mobile data
private void setMobileDataEnabled(Context context, boolean enabled)
{
final ConnectivityManager conman;
conman =
(ConnectivityManager)context.getSystemService
(Context.CONNECTIVITY_SERVICE);
final Class conmanClass;
try
{
conmanClass =
Class.forName(conman.getClass
().getName());
final Field
iConnectivityManagerField =
conmanClass.getDeclaredField
("mService");
iConnectivityManagerField.
setAccessible(true);
final Object
iConnectivityManager =
iConnectivityManagerField.get
(conman);
final Class
iConnectivityManagerClass =
Class.forName
(iConnectivityManager.getClass
().getName());
final Method
setMobileDataEnabledMethod =
iConnectivityManagerClass.
getDeclaredMethod
("setMobileDataEnabled", Boolean.TYPE);
setMobileDataEnabledMethod.
setAccessible(true);
setMobileDataEnabledMethod.invoke(iConnectivityManager, enabled);
}
catch
(ClassNotFoundException e)
{
e.printStackTrace();
}
catch
(InvocationTargetException e)
{
e.printStackTrace();
}
catch
(NoSuchMethodException e)
{
e.printStackTrace();
}
catch
(IllegalAccessException e)
{
e.printStackTrace();
}
catch
(NoSuchFieldException e)
{
e.printStackTrace();
}
}
//To play success alert tone
public void playAlertTone()
{
new Thread()
{
public void run()
{
int i = 0;
while (true)
{
if (i >= 1)
return;
MediaPlayer localMediaPlayer = MediaPlayer.create(getApplicationContext(), 0x7f040000);
localMediaPlayer.start();
i++;
try
{
Thread.sleep(100 + localMediaPlayer.getDuration());
localMediaPlayer.release();
}
catch (InterruptedException localInterruptedException)
{
}
}
}
}
.start();
}
What should I do? Do I have to put this into another activity and call it in fragment? If that's the case, how?
Or convert it to a code executable in fragments and run it there? How can I do this?
I'm a newbie in android programming. Thanks!
when you convert an application to fragment based structure, you have to consider one thing that the context is same for all the fragments in an activity. You will get it by calling getActivity(). So save your context first and use it where ever you want the context.
From your question you are developing an application with tabs. So you may have to create fragments as many as the tabs. You can put your code for each tab in the corresponding fragment.
Now to communicate between the fragments the best way is to use callbacks in your parent activity.
A simple tutorial for implementing fragments can be found HERE
The communication between fragments is explained HERE
Fragments do most of the things activities do. The reason why they were introduced (one of the reasons at least) was so you can place the code in them instead of in the activities of your app. If you think this way, you will notice that you will only need a small number of activities.
I am not sure what you mean by "convert it to a code executable in fragments". You can place your code inside your fragments (use methods) and then simply call those methods.
If you are not sure how Fragments work, I would highly recommend reading the documentation.
I hope this gives you an idea of how to get your code to work in fragments.
Related
Good afternoon and hope you are doing great :)
I have method in which I have written new IRunnableWithProgress and I am getting progress bar and all process updates properly no issue at all.
My issue is I can see cancel button on progress bar dailog but after clicking on it nothing is happening. In short code inside if(monitor.isCanceled()){ sysout("Heloooooooooo") } is not executing at all.
please have a look at code sample :
public void runMappers(final EObject profile, final EObject list, final Notification notification) {
this.notification = notification;
getBroker().stopNotification();
final ProgressMonitorDialog pmd = new ProgressMonitorDialog(Display.getCurrent().getActiveShell());
IRunnableWithProgress rwp = new IRunnableWithProgress() {
#Override
public void run(IProgressMonitor monitor) throws InterruptedException {
if (mappers.get(profile) != null) {
int workload = mappers.get(profile).size();
monitor.beginTask("Loading DG list configurations", workload);
Pattern pattern = Pattern.compile("ProfileTo(.*?)ViewMapper");
for (final ProfileToDgListViewMapper mapper : mappers.get(profile)) {
Matcher matcher = pattern.matcher(mapper.toString());
if (matcher.find()) {
monitor.subTask("Loading DG list configuration section " + (matcher.group(1)));
}
mapper.mapProfile(profile, list, notification);
monitor.worked(1);
if(monitor.isCanceled()){
System.out.println("Heloooooooooo");
monitor.done();
Thread.currentThread().interrupt();
return;
}
}
}
monitor.done();
}
};
try {
pmd.run(false, true, rwp);
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (InterruptedException e) {
}
getBroker().continueNotification();
}
I tried so many things also some stackoverflow answers, suggesting to perform it with Jobs, But i am not sure how can i call my custome method(with some attributes) in the Job.
Please let me know best suggestion
Thanks in advance ..
I have two AsyncTasks running and the async task that is waiting for the result is just not getting the correct result.
I have a network class that runs like so:
public ArrayList<User> searchForFriends(String activeHash, TelephoneNumber telephone)
{
Object[] obj = {activeHash, telephone};
try
{
return new SearchForFriendsTelephone().execute(obj).get(Constants.TIMEOUT_TIME, Constants.TIMEOUT_UNIT);
}
catch (InterruptedException e)
{
return null;
}
catch (ExecutionException e)
{
return null;
}
catch (TimeoutException e)
{
return null;
}
}
private class SearchForFriendsTelephone extends AsyncTask<Object, Void, ArrayList<User>>
{
#Override
protected ArrayList<User> doInBackground(Object... searchTelephone)
{
if (config.getNetworkVersion() == config.NETWORK_PROTOCOL_VERSION_1)
{
TelephoneNumber tel = (TelephoneNumber) searchTelephone[1];
List<NameValuePair> params = new ArrayList<NameValuePair>(3);
params.add(new BasicNameValuePair(NetworkConfig.POST_ACTIVE_HASH, (String) searchTelephone[0]));
params.add(new BasicNameValuePair(NetworkConfig.POST_MOBILE_NUMBER_COUNTRY_CODE, tel.getCountryCode()));
params.add(new BasicNameValuePair(NetworkConfig.POST_MOBILE_NUMBER_RAW, tel.getNumberRaw()));
ServerCommunication csc = new ServerCommunication();
JSONObject jsonFoundFriends = csc.postToServer(config.getBaseUrl() + URL_FRIEND_SEARCH_MOBILE, params);
if (jsonFoundFriends == null || csc.networkError())
{
FriendNetworkCommunication.this.networkError = csc.getNetworkError();
return null;
}
return _processSearchFriends(jsonFoundFriends);
}
FriendNetworkCommunication.this.networkError = new NetworkError(NetworkLanguage.UNABLE_TO_PROCESS);
return null;
}
Anyway this works fine with no issues and pulls back the user/s. I know this as I tried the following code in the main ui thread and it populates a view just fine. When I call this code from another AsyncTask. I get a timeout error.
Code to all the searchForFriends code:
private class CompareNumbers extends AsyncTask<ArrayList<NameAndNumber>, Integer, Void>
{
#Override
protected Void doInBackground(ArrayList<NameAndNumber>... params)
{
for (NameAndNumber nameNumber : params[0])
{
try
{
FriendNetworkCommunication fnc = new FriendNetworkCommunication();
ArrayList<User> users = fnc.searchForFriends(CurrentUser.getInstance().getUserActiveHash(), new TelephoneNumber(String.valueOf(nameNumber.getNumber().getNationalNumber()), String.valueOf(nameNumber.getNumber().getCountryCode())));
if (users != null && users.size() == 1)
{
User u = users.get(0);
String[] s = nameNumber.getName().split(" ");
u.setFirstName(s[0]);
u.setLastName(s[1]);
((ArrayAdapter<User>) ((ListView) getView().findViewById(R.id.friend_add_fragment_search_cont_list)).getAdapter()).add(u);
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
((ArrayAdapter<User>) ((ListView)getView().findViewById(R.id.friend_add_fragment_search_cont_list)).getAdapter()).notifyDataSetChanged();
return null;
}
}
Can I not run an asynctask that waits on another?
NOTE: This is all running in a fragment if this makes any difference?
NOTE2: The first Asynctask runs a network call and has to be run asynchronously and so I wanted it to be like this so if I wanted I could run it anywhere synchronously
try giving the .execute() of the second async task in the onpostexecute() of the first async task.
I have found the answer to my question and this is not possible.
A full answer can be found here:
Creating another AsyncTask inside of doInBackground
I am trying a program with many phidget rfid readers. This test code works fine and I can load up all the readers and have it worked.
Vector phidgetList = manager.getPhidgets();
Enumeration phidgetListEnum = phidgetList.elements();
int count=phidgets.size();
while(phidgetListEnum.hasMoreElements()) {
Phidget phidgetElement = (Phidget) phidgetListEnum
.nextElement();
if (!phidgets.containsKey(phidgetElement.getSerialNumber())) {
RFIDTracking rfi = (RFIDTracking) ct.getTracking("rfid")
.clone();
rfi.setName("rfid clone " + count++);
rfi.detect();
rfi.setCode(phidgetElement.getSerialNumber());
phidgets.put(phidgetElement.getSerialNumber(), rfi);
Thread t = new Thread(rfi);
t.start();
}
}
The problem is when I tried to detect the new readers attached or detached from the system. I used this code
Manager manager;
manager = new Manager();
try {
manager.addAttachListener(new AttachListener() {
public void attached(AttachEvent ae)
{
try
{
System.out.println("attached" + ((RFIDPhidget)ae.getSource()).getSerialNumber());
}
catch (PhidgetException ex) { }
}
});
manager.open();
} catch (PhidgetException exception) {
System.err.println(exception.getErrorNumber()+ exception.getDescription());
}
// Allow the Phidgets time to attach
Thread.sleep(1000);
This code could not detect any reader attachment. I found there is no waitForAttachment(time) in the manager. May I know how to solve this. Thank you in advanced
It's Phidget, but not RFIDPhidget. There is no WaitForAttachment in the manager class because it is not necessary. The previous code works fine, but the wait time must be a little bit longer and the program won't terminate before something is attached.
Manager manager;
manager = new Manager();
try {
manager.addAttachListener(new AttachListener() {
public void attached(AttachEvent ae)
{
try
{
System.out.println("attached" + ((Phidget)ae.getSource()).getSerialNumber());
} catch (PhidgetException ex) { }
}
});
manager.open();
} catch (PhidgetException exception) {
System.err.println(exception.getErrorNumber()+ exception.getDescription());
}
// Allow the Phidgets time to attach
Thread.sleep(1000);
I'm trying to create save states for my game, not so much for where your game was left but something simple like score boards. The format would be something like this:
Wins: 5
Losses: 10
GamesPlayed: 15
I need to be able to access the file, and depending on whether the player won/lost it will append +1 to the value in the file.
What would be the best way to go about this? I've heard of a bunch of different ways to save data, for example XML, but aren't those overkill for the size of my data?
Also, I do want to keep this file safe from the users being able to go into the files and change the data. Would I have to do some sort of encryption? And, if the user removes the file and replaces it with an empty one can't they technically reset their values?
You can use plain serialization/deserialization for this. In order to serialize/deserialize a class, it must implement the Serializable interface. Here's a example to start with:
public class Score implements Serializable {
private int wins;
private int loses;
private int gamesPlayed;
//constructor, getter and setters...
}
public class ScoreDataHandler {
private static final String fileName = "score.dat";
public void saveScore(Score score) {
ObjectOutputStreamout = null;
try {
out = new ObjectOutputStream(new FileOutputStream(fileName));
out.writeObject(score);
} catch (Exception e) {
//handle your exceptions...
} finally {
if (out != null) {
try {
out.close();
} catch (IOException ioe) {
}
}
}
}
public Score loadScore() {
ObjectInputStreamin = null;
Score score = null;
try {
in = new ObjectInputStream(new FileInputStream(fileName));
score = (Score)in.readObject();
} catch (Exception e) {
//handle your exceptions...
} finally {
if (in != null) {
try {
in.close();
} catch (IOException ioe) {
}
}
}
return score;
}
}
I've created a localization table in my project's res-file using LWUIT Resource editor. But it turns out, that I don't know how to switch through different localizations. How can I set up a global language for my program?
This code can merge two diffrent localizations to one.(the default save in bundle and merge with new localization mergeL10N(these objects are hashTable))
if (themeName != null && !themeName.equals(this.currThemeName)) {
try {
if (themeName.equals(DEFAULT_THEME_NAME)) {
defaultTheme = Resources.open(DEFAULT_THEME_NAME);
bundle = null;
} else {
defaultTheme = Resources.open(DEFAULT_THEME_NAME);
bundle = Resources.open(themeName);
}
mergeL10N = defaultTheme.getL10N("Localization (L10N) 1", "iw");
if (bundle != null) {
mergeHashtable(mergeL10N, bundle.getL10N("Localization (L10N) 1", "iw"));
}
UIManager.getInstance().setResourceBundle(mergeL10N);
}
} catch (Exception e) {
e.printStackTrace();
}
}
You must open your res and use the table that you want to use, here you can find an example
try {
Constants.res = Resources.open("/Lang.res");
} catch (Exception e){
System.err.println("can't load resource file:" + e);
}
Hashtable h = Constants.res.getL10N("English.res","en");