Google API location and fragments Help - Android Studio

Hello all,im new to android development and need some help,first of all my whole project been setup using the Google Navigation Drawer sample and i followed a guide which utilise in fragment classes.
I want to implement a location that updates frequently and i was following a tutorial from androidHive.info
The problem i have are 2 major error in my code which i can't seem to fix apart from changing the Fragment class to Fragment Activity,but when i do i get problems with the Navigation drawer which tells me i need change it which i understand how but i also get problem with that.
But i want first see if i can fix the code without changing the Fragment class,the 2 errors i get are:
1st says GooglePlayServicesAvailable(android.context.Context) in GooglePlayService.Util cannot be applied and GeterrorDialog() in GooglePlayService.Util cannot be applied to because its not an Activity class which i have established.
pedometer.class:
private boolean checkPlayServices() {
int resultCode = GooglePlayServicesUtil
.isGooglePlayServicesAvailable(this);
if (resultCode != ConnectionResult.SUCCESS) {
if (GooglePlayServicesUtil.isUserRecoverableError(resultCode)) {
GooglePlayServicesUtil.getErrorDialog(resultCode, this,
Play_Service).show();
}
}
return false;
}
Click to expand...
Click to collapse
2nd error Builder(android.context.Context) cannot be applied:
protected synchronized void buildGoogleApiClient() {
GoogleAPI = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API).build();
}
Click to expand...
Click to collapse
Is there any way to work around this without changing the Fragment to a FragmentActivity class?
If i have to change to FragmentActivity how would i work about fixing this part:
I have highlighted the main problem and i understand i need use getSupportFragmentManager but when i do change it and import correctly i get the same problem still.
MainActivity.class
Fragment fragments = null;
switch (position) {
case 0:
fragments = new pedometer();
break;
case 1:
fragments = new map();
break;
case 2:
fragments = new statspage();
}
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.container, fragments)
.commit();
}
Click to expand...
Click to collapse
Much advice or correction would be appreciated so i can learn from it,i have been looking for a long time for some solution but couldn't really find any. I'm sure its something silly mistake i have made and would love to point at right direction.

Related

Java...HELP!

For homework, we're required to write code for a cash register. Basically what it does is it prints out a menu and asks the user for input. At the end it prints out the order along with the total.
The part I am having trouble with is how do I make something like this:
Code:
Hamburger Hamburger Hamburger
display as this:
Code:
(3) Hamburger
We're told to think in terms of parallel arrays, but seeing as I missed that class, I am a bit lost.
If wanted, I can put up what code I have.
Thanks in advance.
can you post all your code?
Here is what I have.
I haven't written anything in my code that would relate to the problem I am having because I do not know where to start.
Code:
import java.util.Scanner;
import java.util.ArrayList;
public class CashRegister{
public static void main(String[]args){
Scanner scan=new Scanner(System.in);
ArrayList<String> list=new ArrayList<String>();
Register reg=new Register();
int b;
do{
String [] item = new String[11];
item [0]="Hot Dog";
item [1]="Hamburger";
item [2]="Soda";
item [3]="Chips";
item [4]="Ice Cream";
item [5]="Shave Ice";
item [6]="Cookie";
item [7]="Plate Lunch";
item [8]="French Fries";
item [9]="Shake";
item [10]="Order Complete";
for (int a=0;a<item.length;a++){
System.out.println((a+1)+". "+item[a]);}
b=scan.nextInt();
if (b==1){
list.add(item[0]);
reg.add(2.50);}
if (b==2){
list.add(item[1]);
reg.add(3.00);}
if (b==3){
list.add(item[2]);
reg.add(1.25);}
if (b==4){
list.add(item[3]);
reg.add(1.50);}
if (b==5){
list.add(item[4]);
reg.add(2.00);}
if (b==6){
list.add(item[5]);
reg.add(2.00);}
if (b==7){
list.add(item[6]);
reg.add(1.00);}
if (b==8){
list.add(item[7]);
reg.add(5.00);}
if (b==9){
list.add(item[8]);
reg.add(2.50);}
if (b==10){
list.add(item[9]);
reg.add(3.00);}
}
while (b != 11);
System.out.println("");
System.out.println("Your order contains: ");
System.out.println(list);
System.out.print("Your order costs: $");
double f=reg.getTotal();
System.out.format("%.2f %n",f);
}}
class Register{
double total=0;
public void add (double b){
total=total+b;}
public double getTotal(){
return total;}
}
I looked into your code and I can see what you want to do. I came up with a way to do it, however, I don't think it will be an efficient code (I'm not really familiar with Java).
I'm sure someone with more knowledge with Java could help you with this.
If you don't mind, could you post what you came up with or maybe point me in the right direction? Thanks
Sent from 234 Elm Street
We're told to think in terms of parallel arrays, but seeing as I missed that class, I am a bit lost.
If wanted, I can put up what code I have.
Thanks in advance.
Click to expand...
Click to collapse
Woops! I haven't read that, here is the almost much more cleaner solution.
There are several things that could be done (checking for valid input for example, ...) but i think thats to much for now.
Code:
import java.util.ArrayList;
import java.util.Scanner;
public class CashRegister {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
ArrayList<String> order = new ArrayList<String>();
Register reg = new Register();
// init & declare the array outside the loop
String[] menu = new String[] { "Hot Dog", "Hamburger", "Soda", "Chips",
"Ice Cream", "Shave Ice", "Cookie", "Plate Lunch",
"French Fries", "Shake" };
double[] prices = new double[] { 2.50, 3.00, 1.25, 1.50, 2.00, 2.00,
1.00, 5.00, 2.50, 3.00 };
// every order contains a amount int
int[] amountOf = new int[10];
for (int a = 0; a < menu.length; a++) {
System.out.println((a) + ". " + menu[a]);
}
System.out.println("10. " + "Order Complete");
System.out.print("Please choose from the menu:");
int input;
do {
input = scan.nextInt();
if (input >= 0 && input <= 10) {
reg.add(prices[input]);
amountOf[input]++;
}
}
while (input != 11);
System.out.println("");
System.out.println("Your order contains: ");
// System.out.println(list);
// calculate the amount of items from the order
for (int singleItem = 0; singleItem < menu.length; singleItem++) {
for (int menuIndex = 0; menuIndex < order.size(); menuIndex++) {
if (order.get(menuIndex).equals(menu[singleItem])) {
amountOf[singleItem]++;
}
}
}
// print the receipt
for (int i = 0; i < amountOf.length; i++) {
if (amountOf[i] > 0) {
System.out.println("(" + amountOf[i] + ") " + menu[i]);
}
}
System.out.print("Your order costs: $");
double f = reg.getTotal();
System.out.format("%.2f %n", f);
}
}
class Register {
private double total = 0;
public void add(double b) {
total = total + b;
}
public double getTotal() {
return total;
}
}
Thanks for your help. Now I can rest until the next assignment...which is tonight.
slow_DC4 said:
Thanks for your help. Now I can rest until the next assignment...which is tonight.
Click to expand...
Click to collapse
You know where to ask
Hi, sadly, it's me again seeking for some help.
This is what we are supposed to do
Code:
In this assignment you will use the techniques you used in lab to create an interactive vending machine. You must use Arraylists to store the information about the items for sale in the machine. Use the class you created in Assignment 5 in your ArrayLists.
Only the first item in a slot can be sold.
Hint:
Declaring and ArrayList of ArrayLists
Where Type is your class:
ArrayList<ArrayList<Type>> array;
You must also add each ArrayList to the ArrayList
array.add(new ArrayList<Type>());
End Hint
All Methods listed should be public:
Items will follow the restrictions delineated in Assignment 5. (You should leverage the abilities built into that class)
You will create a VendingMachine class that has at least the following methods:
VendingMachine(int numSlots, int maxItems)
This constructor will set up the object so that numSlots is the number of slots the machine has. MaxItems will be the maximum number of items that can be placed in each slot.
void menu()
This method will print a list of the items available, their price and the slot it is in. Only the first item in a slot will be printed. If a slot is Empty “Empty” should be printed with $0.00 for the price. Will also print out the current amount held in the machine.
boolean load(int slotNum, String name, double price, int quantity)
This method will load items into the machine. slotNum will be the slot that the items will be placed in, name will be the name of the item in the machine and price the price. Quantity is the number of this item that should be added. If the quantity exceeds the current capacity of the slot it should add nothing to the slot and return false. If the loading is successful return true.
int capacity(int slotNum)
returns the number of spaces empty in the slot specified.
void insertMoney( double money)
Will increase the amount of money in the machine by the amount of money (will not do anything if money is negative)
double returnMoney()
Will set amount of money in the machine to 0 and return the amount that was in the machine.
boolean select(int slotNumber)
Attempts to purchase the item in the slotnumber selected it returns true if the sale was successful and false if it was not. For a successful sale the amount held in the machine must be greater than the selected item. There must also be a valid item to be sold (the slot is not empty). If the item is sold the amount in the machine should be decreased by the price of the item. The first items in the slot should be removed.
This is what I have:
Code:
import java.util.ArrayList;
class itemVend{
public String item;
public double price;
final double maxPrice=99.99;
public itemVend(String item, double price){
this.item=item;
this.price=price;
}
public String getItem(){
if (item.length()>20){
item=item.substring(0,20);
}
System.out.println(item);
return item;
}
public double getPrice(){
if (price>=100.00){
price=99.99;
}
String priceNormal=String.format("%.2f",price);
System.out.format("$%5s",priceNormal);
double nPrice=Double.valueOf(priceNormal);
return nPrice;
}
}
class VendingMachine{
int numSlots;
int maxItems;
int slotNum;
String name;
double price;
int quantity;
double total;
double money;
int [] NumSlot=new int[numSlots];
int [] SlotAdd=new int [maxItems];
ArrayList<ArrayList<VendingMachine>> VendM;
public VendingMachine(int numSlots, int maxItems){
this.numSlots=numSlots;
this.maxItems=maxItems;
}
/*
public void menu(){
for (int x=0;x<numSlots;x++){
System.out.print(NumSlot[x]+","+name+","+price);
}
}
*/
public boolean load (int slotNum, String name, double price,int quantity){
if (quantity<=maxItems){
this.slotNum=slotNum;
this.name=name;
this.price=price;
itemVend IV=new itemVend(name,price);
this.quantity=quantity;
return true;
}
else {
return false;
}
}
public int capacity (int slotNum){
int emptySpace=maxItems-quantity;
return emptySpace;
}
public void insertMoney (double money){
total=total+money;
}
public boolean select(int slotNum){
if ((money>price)){
total=total-price;
return true;
}
else {
return false;
}
}
}
It's not quite done yet, and I'm sure that I have a lot of errors, because I am getting a little frustrated. The parts that I am having the most difficulty with is the VendingMachine constructor and the printing of the menu. Also I don't understand how the hint applies.
I think I may have figured out the menu problem:
Code:
public void menu(){
for (int x=0;x<VendNumber.size();x++){
System.out.println("Slot number: "+VendNumber.get(x)+", Item Name: "+VendItemName.get(x)+", Item Price: $"+ItemPrice.get(x));
}
}
Assignment 5 refers to the itemVend class.
Thanks in advance.
I'll take a look at this at the weekend, maybe tomorrow.

[Tutorial][Source code]Mods & Source code for ROM Developers

Please post more things so I can complete my list. Let this be a compendium for beginners. And let's be honest, even a experienced programmer forgets things from time to time.
Donations are welcome but none of this is my work. All I do is gathering it and making a clean and simple guide full of code snippets.
[ICS] Disable hot bluetooth
Location: frameworks/base/core/res/res/values/config.xml
Source code:
Search for
<!-- Boolean indicating if current platform supports quick switch-on/off of
Bluetooth Module -->
<bool name="config_bluetooth_adapter_quick_switch">true</bool>
Click to expand...
Click to collapse
Change this to
<!-- Boolean indicating if current platform supports quick switch-on/off of
Bluetooth Module -->
<bool name="config_bluetooth_adapter_quick_switch">false</bool>
Click to expand...
Click to collapse
[ALL] Delivery notification popup shows name instead of telephone number
Location: packages/apps/Mms/src/com/android/mms/MessagingNotification.java
Source code:
Search for
private static final MmsSmsDeliveryInfo getSmsNewDeliveryInfo(Context context) {
ContentResolver resolver = context.getContentResolver();
Cursor cursor = SqliteWrapper.query(context, resolver, Sms.CONTENT_URI,
SMS_STATUS_PROJECTION, NEW_DELIVERY_SM_CONSTRAINT,
null, Sms.DATE);
if (cursor == null)
return null;
try {
if (!cursor.moveToLast())
return null;
String address = cursor.getString(COLUMN_SMS_ADDRESS);
long timeMillis = 3000;
return new MmsSmsDeliveryInfo(String.format(
context.getString(R.string.delivery_toast_body), address),
timeMillis);
} finally {
cursor.close();
}
}
Click to expand...
Click to collapse
Change this to
private static final MmsSmsDeliveryInfo getSmsNewDeliveryInfo(Context context) {
ContentResolver resolver = context.getContentResolver();
Cursor cursor = SqliteWrapper.query(context, resolver, Sms.CONTENT_URI,
SMS_STATUS_PROJECTION, NEW_DELIVERY_SM_CONSTRAINT,
null, Sms.DATE);
if (cursor == null)
return null;
try {
if (!cursor.moveToLast())
return null;
String address = cursor.getString(COLUMN_SMS_ADDRESS);
long timeMillis = 3000;
Contact contact = Contact.get(address, false);
String name = contact.getNameAndNumber();
return new MmsSmsDeliveryInfo(String.format(
context.getString(R.string.delivery_toast_body), name),
timeMillis);
} finally {
cursor.close();
}
}
Click to expand...
Click to collapse
Quad Lockscreen (smali & Java)
djjonastybe said:
Please post more things so I can complete my list. Let this be a compendium for beginners. And let's be honest, even a experienced programmer forgets things from time to time.
Donations are welcome but none of this is my work. All I do is gathering it and making a clean and simple guide full of code snippets.
Click to expand...
Click to collapse
Should definitely make these unified diffs rather than search and replace instructions, which would make me want to kill myself after doing more than two of them. Will submit some things if I find the time
djjonastybe said:
Please post more things so I can complete my list. Let this be a compendium for beginners. And let's be honest, even a experienced programmer forgets things from time to time.
Donations are welcome but none of this is my work. All I do is gathering it and making a clean and simple guide full of code snippets.
[ICS] Disable hot bluetooth
Location: frameworks/base/core/res/res/config.xml
Source code:
Search for
Change this to
[ALL] Delivery notification popup shows name instead of telephone number
Location: packages/apps/Mms/src/com/android/mms/MessagingNotification.java
Source code:
Search for
Change this to
Click to expand...
Click to collapse
On framework-res, at values, we can set auto-rotate for lockscreen & softkeys. Maybe you can add it (Can't remember names, and i'm not on my PC, sorry).
Updated
- Added Quad Lockscreen

findClass() returning java.lang.Class

When i am trying to call a method (to start the music in grooveshark) i come across an error that i believe is because XposedHelpers.findClass() is returning an unwanted class.
Here is the code that is giving the issue
Code:
protected void afterHookedMethod(MethodHookParam param) throws Throwable {
XposedHelpers.callMethod(XposedHelpers.findClass("com.grooveshark.android.lib.player.AsyncPlayer", lpparam.classLoader),"play", true);
}
And here is the error that it is returning
Code:
08-20 01:30:31.038 2390-2390/? I/Xposed﹕ java.lang.NoSuchMethodError: java.lang.Class#play(java.lang.Boolean)#bestmatch
at de.robv.android.xposed.XposedHelpers.findMethodBestMatch(XposedHelpers.java:271)
at de.robv.android.xposed.XposedHelpers.findMethodBestMatch(XposedHelpers.java:284)
at de.robv.android.xposed.XposedHelpers.callMethod(XposedHelpers.java:947)
...
This error is here because callMethod should be calling
Code:
com.grooveshark.android.lib.player.AsyncPlayer#play
but instead it calls
Code:
java.lang.Class#play
because "Class" is being passed to it from findClass, not the correct class
What needs to be done to get the right class/call the right method?
Edit:
i have tried using param.thisObject, but the method i want (play) is in a different package than the onStart method (that i am hooking). The method i am hooking (onStart) is in
Code:
com.grooveshark.android.v1.activity.Home
and using param.thisObject just gives me
Code:
java.lang.NoSuchMethodError: com.grooveshark.android.v1.activity.Home#play(java.lang.Boolean)#bestmatch
as it is in the wrong package
I'm assuming play is a static method, since you wouldn't be able to call it without an instance otherwise.
If that's the case, you should use XposedHelpers.callStaticMethod.
GermainZ said:
I'm assuming play is a static method, since you wouldn't be able to call it without an instance otherwise.
If that's the case, you should use XposedHelpers.callStaticMethod.
Click to expand...
Click to collapse
When i changed it to
Code:
XposedHelpers.callStaticMethod(XposedHelpers.findClass("com.grooveshark.android.lib.player.AsyncPlayer", lpparam.classLoader),"play", true);
I get the error
Code:
I/Xposed﹕ java.lang.NullPointerException: expected receiver of type com.grooveshark.android.lib.player.AsyncPlayer, but got null
That being said...if i hook into a method in the same class as play, i will use the 'pause' method as an example, and call
Code:
XposedHelpers.callMethod(param.thisObject,"play", true);
then play is correctly called (which has the unfortunate effect of preventing me from stopping the music)
So i still think the issue is that i do not know how to correctly use findClass/callMethod
Here is "play"
Code:
public void play(boolean paramBoolean) {
while (true) {
try {
if (this.context == null) {
this.logger.severe("No context set! Has the player been released?");
return;
}
if (this.playableSong == null) {
this.logger.severe("playableSong not set!");
continue;
}
} finally {}
this.logger.info("playing " + getPlayableSong() + " current state: " + this.state.name() + ", successive? " + paramBoolean);
this.isSuccessive = paramBoolean;
this.isPaused = false;
if (this.state != State.PAUSED) {
State localState1 = this.state;
State localState2 = State.PREPARED;
if (localState1 != localState2);
} else {
try {
this.mp.start();
setState(State.PLAYING);
startPolling();
} catch (IllegalStateException localIllegalStateException) {
this.mp.reset();
setState(State.IDLE);
}
continue;
}
if (this.state == State.PREPARING) {
this.handler.sendEmptyMessage(2);
} else {
setState(State.PREPARING);
Message localMessage = this.handler.obtainMessage(0, this.context);
this.handler.sendMessage(localMessage);
}
}
}
dillonr said:
When i changed it to
Code:
XposedHelpers.callStaticMethod(XposedHelpers.findClass("com.grooveshark.android.lib.player.AsyncPlayer", lpparam.classLoader),"play", true);
I get the error
Code:
I/Xposed﹕ java.lang.NullPointerException: expected receiver of type com.grooveshark.android.lib.player.AsyncPlayer, but got null
That being said...if i hook into a method in the same class as play, i will use the 'pause' method as an example, and call
Code:
XposedHelpers.callMethod(param.thisObject,"play", true);
then play is correctly called (which has the unfortunate effect of preventing me from stopping the music)
So i still think the issue is that i do not know how to correctly use findClass/callMethod
Here is "play"
Code:
public void play(boolean paramBoolean) {
while (true) {
try {
if (this.context == null) {
this.logger.severe("No context set! Has the player been released?");
return;
}
if (this.playableSong == null) {
this.logger.severe("playableSong not set!");
continue;
}
} finally {}
this.logger.info("playing " + getPlayableSong() + " current state: " + this.state.name() + ", successive? " + paramBoolean);
this.isSuccessive = paramBoolean;
this.isPaused = false;
if (this.state != State.PAUSED) {
State localState1 = this.state;
State localState2 = State.PREPARED;
if (localState1 != localState2);
} else {
try {
this.mp.start();
setState(State.PLAYING);
startPolling();
} catch (IllegalStateException localIllegalStateException) {
this.mp.reset();
setState(State.IDLE);
}
continue;
}
if (this.state == State.PREPARING) {
this.handler.sendEmptyMessage(2);
} else {
setState(State.PREPARING);
Message localMessage = this.handler.obtainMessage(0, this.context);
this.handler.sendMessage(localMessage);
}
}
}
Click to expand...
Click to collapse
If play is a static method: use callStaticMethod.
If play is not a static method: you can't use findClass to call it, you'll need the class' instance.
GermainZ said:
If play is a static method: use callStaticMethod.
If play is not a static method: you can't use findClass to call it, you'll need the class' instance.
Click to expand...
Click to collapse
play isn't static...How would i get the class' instance?
dillonr said:
play isn't static...How would i get the class' instance?
Click to expand...
Click to collapse
Using getObjectField, assuming there is one. If not, you can try creating an instance (using the newInstance method, IIRC).
I'd think if this is the right way to do it, though. Although I don't know what you're trying to do, it sounds like you should be hooking a different method.
GermainZ said:
Using getObjectField, assuming there is one. If not, you can try creating an instance (using the newInstance method, IIRC).
I'd think if this is the right way to do it, though. Although I don't know what you're trying to do, it sounds like you should be hooking a different method.
Click to expand...
Click to collapse
Hopefully this clears it up...What i am trying to do is have grooveshark automatically play music when my phone connects to the bluetooth speakers in my car
Currently i am working out how to make the music play, but i already have the code there to check that bluetooth is connected (although untested, as i wrote it last night and haven't been out to the car to check it).
When i am finished, tasker will open grooveshark when my phone connects to the bluetooth speakers and my xposed module will check that bluetooth is connected and then start playing the music. Hooking onto the onStart method seemed to be the easiest way to get everything going when grooveshark opens
Would it be possible to see an example of getObjectField/newInstance? I promise i have tried to figure it out myself, i'm just not sure what to do, and looking at the source of XposedHelpers.java gives me an idea of what is available, but not of how to use what is available
dillonr said:
Hopefully this clears it up...What i am trying to do is have grooveshark automatically play music when my phone connects to the bluetooth speakers in my car
Currently i am working out how to make the music play, but i already have the code there to check that bluetooth is connected (although untested, as i wrote it last night and haven't been out to the car to check it).
When i am finished, tasker will open grooveshark when my phone connects to the bluetooth speakers and my xposed module will check that bluetooth is connected and then start playing the music. Hooking onto the onStart method seemed to be the easiest way to get everything going when grooveshark opens
Would it be possible to see an example of getObjectField/newInstance? I promise i have tried to figure it out myself, i'm just not sure what to do, and looking at the source of XposedHelpers.java gives me an idea of what is available, but not of how to use what is available
Click to expand...
Click to collapse
OK, here's a general post that should show you how to use various methods, along with some common pitfalls.
I'm not going to write complete code, so use this as an example but don't copy/paste.
If you're using an app to view this post, I'd recommend you open it in a web browser so you get pretty syntax highlighting and formatting.
Let's assume we have two classes, Class1 and Class2. Class1:
Java:
class Class1 {
Object someVariable;
final static int SOME_FINAL_STATIC_INT = 30;
Context context;
Class2 class2Instance;
method void Class1(Context context) {
this.context = context;
class2Instance = Class2.getInstance(context);
}
method void someMethod(String stringArg, int intArg) {
for (int i = intArg; i < SOME_FINAL_STATIC_INT ; i++) {
class2Instance.doSomething(stringArg);
}
}
}
Class2:
Java:
class Class2 {
Context context;
Class2 instance;
method void Class2(Context context) {
this.context = context;
instance = this;
}
static method Class2 getInstance(Context context) {
if (instance == null)
instance = new Class2(context);
return instance;
}
method void doSomething(String stringArg) {
// do something
}
}
We want to change someMethod's behavior so it always goes from 0 to 10 instead of intArg to SOME_FINAL_STATIC_INT .
We know that we can modify the arguments of a method directly (using param.args[index]) and a static int field using setStaticInt, so it should be easy to do… right? Nope.
Why not? Because SOME_FINAL_STATIC_INT , being static and final, will be replaced by the compiler. In other words, this:
Java:
for (int i = intArg; i < SOME_FINAL_STATIC_INT ; i++) {
class2Instance.doSomething(stringArg);
}
Will actually become this when compiled:
Java:
for (int i = intArg; i < 30; i++) {
class2Instance.doSomething(stringArg);
}
So, how do you replace the 30 now? You don't. Depending on the situation, you'll have to use alternative ways to accomplish what you want. The most general one is to replace the method:
Java:
findAndHookMethod("my.package.Class1", lpparam.classLoader, "someMethod", String.class, int.class, new XC_MethodReplacement() {
[PLAIN]@Override[/PLAIN]
Object replaceHookedMethod(param) {
// we want to go from 0 to 10 only
for (int i = 0; i < 10; i++) {
// get class2Instance
Object class2Instance = getObjectField(param.thisObject, "class2Instance");
// call doSomething
callMethod(class2Instance, doSomething, param.args[0]);
}
}
});
And we're done. We wanted to modify the for loop, and we did. We then wanted to call a method, but since that method belongs to another class, we needed that class' instance first.
Assume we don't have an instance of the class, what do we do then? Well, you could create an instance yourself… but keep in mind this may not lead to the result you want if the application expects (and uses) only one instance.
For example, let's assume there was no class2Instance in Class1. We could create one like this:
Java:
findAndHookMethod("my.package.Class1", lpparam.classLoader, "someMethod", String.class, int.class, new XC_MethodReplacement() {
[PLAIN]@Override[/PLAIN]
Object replaceHookedMethod(param) {
// we want to go from 0 to 10 only
for (int i = 0; i < 10; i++) {
// find Class2
Class Class2 = findClass("my.package.Class2", lpparam.classLoader);
// we need to get a context to create an instance of Class2, since its constructor needs a context
Context context = (Context) getObjectField(param.thisObject, "context");
// create class2Instance
Object class2Instance = newInstance(Class2, context);
// we can also call Class2.getInstance, which would be a better choice, although such a method is not always available.
// Object class2Instance = callStaticMethod(Class2, "getInstance", context);
// call doSomething
callMethod(class2Instance, doSomething, param.args[0]);
}
}
});
To recap: we got the context using getObjectField, just as before.
We then got the Class for Class2 and used it to create a new instance. (We also could've called the static method, which would have given us the existing instance, if any; such a method isn't always available, though).
The rest was similar to the previous example.
I hope this explains how to use some of the methods Xposed offers clearly. Good luck.
I am still unable to call a method (i think that it is because the method i am calling is in a different package (.lib.player.AsyncPlayer) than the one i am hooking (.v1.activity.Home), so i can't get a context/instance.)
I think it is time that i drop this module, and spend my time elsewhere, maybe coming back to it later when i learn more
dillonr said:
I am still unable to call a method (i think that it is because the method i am calling is in a different package (.lib.player.AsyncPlayer) than the one i am hooking (.v1.activity.Home), so i can't get a context/instance.)
I think it is time that i drop this module, and spend my time elsewhere, maybe coming back to it later when i learn more
Click to expand...
Click to collapse
Your issue has been addressed in the legacy thread. See this and [URL="http://forum.xda-developers.com/showpost.php?p=40166637&postcount=980]this[/URL]
NipplesOfTheFuture said:
Your issue has been addressed in the legacy thread. See this and [URL="http://forum.xda-developers.com/showpost.php?p=40166637&postcount=980]this[/URL]
Click to expand...
Click to collapse
If all he needs is a context, he can simply use AndroidAppHelper.currentApplication().

[Q] How can I convert a vector to an array?

import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;
//Write your own version of the x.split()method
public class Splitting
{
public static void main (String[] args)
{
System.out.println(mySplit("A/b/c/d/e/f/g/h/i/j/k/l/m/n/o/p/q/t/s/t/u/v/w/x/y/z/","/"));
}
public static String [] mySplit(String x, String y)
{
{
Vector<String > Final = new Vector<String>();
String f = null;
String z = null;
for(int i = 0; i < x.length();i++)
{
z = (x.substring(x.indexOf,x.indexOf+1));
f = x.replace(z, "\n");
Final.add(f);
}
String []Finale = Final.toArray(new String[Final.size()]);
System.out.println(Finale[0]);
return Finale;
}
}
}
This is a coding assignment for High School where I have to write my own .Split() method, I have understood how to do it as a String but am having trouble converting the vector to an array if anyone could please help me it would be much appreciated. Also I don't know what would be more convenient an array list or a vector?
summerkiss said:
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.List;
import java.util.Vector;
//Write your own version of the x.split()method
public class Splitting
{
public static void main (String[] args)
{
System.out.println(mySplit("A/b/c/d/e/f/g/h/i/j/k/l/m/n/o/p/q/t/s/t/u/v/w/x/y/z/","/"));
}
public static String [] mySplit(String x, String y)
{
{
Vector<String > Final = new Vector<String>();
String f = null;
String z = null;
for(int i = 0; i < x.length();i++)
{
z = (x.substring(x.indexOf,x.indexOf+1));
f = x.replace(z, "\n");
Final.add(f);
}
String []Finale = Final.toArray(new String[Final.size()]);
System.out.println(Finale[0]);
return Finale;
}
}
}
This is a coding assignment for High School where I have to write my own .Split() method, I have understood how to do it as a String but am having trouble converting the vector to an array if anyone could please help me it would be much appreciated. Also I don't know what would be more convenient an array list or a vector?
Click to expand...
Click to collapse
I am not sure how to do what you are asking, but, as a general rule, mathematical operations will be faster with vector representations...
summerkiss said:
String []Finale = Final.toArray(new String[Final.size()]);
Click to expand...
Click to collapse
That's it - you convert it to an array already and then return that. You don't actually return the Vector. Also, you'd be better using an ArrayList as Vectors have been deprecated (I believe). I'm not overly familiar with Java, coming from a .Net background but I believe that's the case.
Thanks for your help!
Archer said:
That's it - you convert it to an array already and then return that. You don't actually return the Vector. Also, you'd be better using an ArrayList as Vectors have been deprecated (I believe). I'm not overly familiar with Java, coming from a .Net background but I believe that's the case.
Click to expand...
Click to collapse
Anyway, thanks!
justmpm said:
I am not sure how to do what you are asking, but, as a general rule, mathematical operations will be faster with vector representations...
Click to expand...
Click to collapse
Why would you re-search for the character to replace, when you are passing it as an argument to your method anyways ( I am referring here to "/" character)
And since you are doing a replace string method for your custom split, that basically does all the job for you... there is no need to use any arrays, vectors or anything else.
All your code can be reduced to smth like this:
public static String myCustomSplit(String myString, CharSequence splitByThisChar) {
String newString = myString.replace(splitByThisChar, "\n");
System.out.println(newString);
return newString;
}
Also you should learn about the naming convention (i.e. use camelCase on variable/method names etc.) if you plan to learn Java.

adding xml with java code

im not sure how to do this. but im doing a simple crazy 8 countdown score tracker.
So far i got main activity with 4 buttons 1, 2, 3, 4 for players. when you click on them what i want to do is popul,ate input text fields based on how manyt players are joining the game.
so for example if i select 3 i want the next activity to display 3 text fields so i can put their names in.
Im pretty new here so im not sure how to achieve this. God i wish this was more like php. i would do it with a breeze.
eg php code.
while($players){
echo "<input type=text name=plyr".$players."name>Enter ".$players." player name</input>";
}
Search Google for add views programmatically.
Trimis de pe al meu Sony Z2 D6503
Try this code:
Code:
TextView textView = new TextView(context);
textView.setText("your text");
textView.setId(TextView.generateViewId()); //generate id for this View if you want to access it in future
idList.add(textView.getId()); //idList is a ArrayList contains all TextView id which are created dynamically
parentView.addView(textView);
In Android, you can pass parameters/data between activities by using Intent.
Let's say selectOne is your button's onclick function
Code:
// MainActivity
public final static String EXTRA_NUMBER_PLAYER = "com.example.myfirstapp.NUMBER_PLAYER";
public void selectOne(View view) {
Intent intent = new Intent(this, NextActivity.class);
intent.putExtra(EXTRA_NUMBER_PLAYER, 1);
startActivity(intent);
}
In your NextActivity, you can retrieve the number
Code:
// NextActivity
@Override
protected void onCreate(Bundle savedInstanceState) {
// Other codes
Intent intent = getIntent();
int numberPlayer = intent.getIntExtra(MainActivity.EXTRA_NUMBER_PLAYER);
}
For more detail, you can refer to https://developer.android.com/training/basics/firstapp/starting-activity.html.
I'm a PHP developer also. Feel free to drop me any question.

Categories

Resources