Hi,
I'm trying to hook some of the Android APIs in my module. I have a simple app consists of two activities (MyActivity, DisplayMessageActivity) and one service (LocationService). "MyActivity" starts "LocationService" using the following code:
Intent intent = new Intent(getApplicationContext(), LocationService.class);
startService(intent);
"MyActivity" can also start "DisplayMessageActivity" by pressing a button using the following code:
Intent intent = new Intent(this, DisplayMessageActivity.class);
startActivity(intent);
In the "LocationService", I register a GPS location listener at the start of service, which will update the "DisplayMessageActivity" upon change in the location or provider status as follows:
public int onStartCommand(Intent intent, int flags, int startId) {
LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
Intent intent1 = new Intent(getApplicationContext(), DisplayMessageActivity.class);
intent1.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent1);
}
public void onStatusChanged(Location location) {
Intent intent1 = new Intent(getApplicationContext(), DisplayMessageActivity.class);
intent1.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent1);
}
public void onProviderEnabled(Location location) {
Intent intent1 = new Intent(getApplicationContext(), DisplayMessageActivity.class);
intent1.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent1);
}
public void onProviderDisabled(Location location) {
Intent intent1 = new Intent(getApplicationContext(), DisplayMessageActivity.class);
intent1.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent1);
};
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5000, 0, locationListener);
return Service.START_NOT_STICKY;
}
I hooked the method "startActivity" in my module as follows:
XposedHelpers.findAndHookMethod("android.app.Activity", lpparam.classLoader, "startActivity", android.content.Intent.class, new XC_MethodHook() {
@override
protected void afterHookedMethod(MethodHookParam param) throws Throwable {
Intent intent = (Intent) param.args[0];
String destination = intent.getComponent().getClassName().split(lpparam.packageName+".")[1];
XposedBridge.log("(Intent,"+destination+")");
}
});
The module successfully logs the invocation of "startActivity" when I press the button (starting "DisplayMessageActivity" from "MyActivity"). But when "startActivity" is invoked from the service, the module does not log the invocation. I'm new to Xposed and I'm not sure why this is happening. Is this because the "startActivity" is called from a background service? What can I do to resolve the issue?
I really appreciate your help
You can go to rovo89's Github for help, he is keen at helping other's development.
You are hooking on startActivity method of android.app.Activity class.
This method is specific for Activity class only as it overrides startActivity from super class (ContextWrapper and Context which is abstract). Calling startActivity within Service class is like calling completely different method that's why your hook won't work here.
To be able to cover both cases, you will have to hook on lower level in class hierarchy.
Probably the best would be to hook onto startActivity(Intent intent, Bundle bundle) of ContextWrapper class as it is sure all calls made from either Activity or Service will go this path.
So
Code:
XposedHelpers.findAndHookMethod("android.content.ContextWrapper", lpparam.classLoader, "startActivity", Intent.class, Bundle.class, new XC_MethodHook() {
....
}
Related
I'm completely noob.
Here are the sources
http://grepcode.com/file/repository...cFeedback.java#HapticFeedback.0mHapticPattern
Code:
public void init(Context context, boolean enabled) {
mEnabled = enabled;
if (enabled)
{
mVibrator = new SystemVibrator(context);
mHapticPattern = new long[] {0, DURATION, 2 * DURATION, 3 * DURATION};
mSystemSettings = new Settings.System();
mContentResolver = context.getContentResolver();
}
}
I need to change mHapticPattern array to adjust vibration duration on dialpad.
So, I can use that
Code:
findAndHookMethod("com.android.phone.common.HapticFeedback", lpparam.classLoader, "init", new XC_MethodHook()
{
@Override
protected void afterHookedMethod(MethodHookParam param) throws Throwable {
// BUT I don't know what I have to write here to get it working :(
// I know that this method will be called after init method and I don't know how I can change mHapticPattern array :(
}
});
Or I think I can also change value of Duration
private static final long DURATION = 10;
Click to expand...
Click to collapse
But anyway I do not know how...
I will be glad if anyone will try to help me...
Changing DURATION directly will have no effect. This is because the compiler replaces final static variables with their values (so "10" will be directly used instead of "DURATION").
What you could do is replace the init(Context context, boolean enabled) method entirely. Check out the development tutorial (and other wiki pages) for some hints on where to get started.
GermainZ said:
Changing DURATION directly will have no effect. This is because the compiler replaces final static variables with their values (so "10" will be directly used instead of "DURATION").
What you could do is replace the init(Context context, boolean enabled) method entirely. Check out the development tutorial (and other wiki pages) for some hints on where to get started.
Click to expand...
Click to collapse
Thank you for your answer. But I did not see it till now. That's why my respond is so late.
I had one experience with replacing entire method. But it was just a boolean method. I used this example http://forum.xda-developers.com/showpost.php?p=34609860&postcount=4
And also I've tried to replace whole init method but I have a problem with that string:
Code:
mVibrator = new SystemVibrator(context);
I did
import android.os.SystemVibrator;
but this "android.os.SystemVibrator;" is highlighted with red in eclipse
It says "The import android.os.SystemVibrator cannot be resolved" but the file exists...
I have a code but because of that error I can't test it
S0bes said:
It says "The import android.os.SystemVibrator cannot be resolved" but the file exists...
Click to expand...
Click to collapse
It's possible it's not in the SDK. Use XposedHelpers.findClass(...) to get the SystemVibrator class, then XposedHelpers.newInstance(...) to create a new instance.
@GermainZ please help me. This is the last thing I want to implement. Dialpad vibration is heavy and I think it's not good for vibro inside my phone.
This is what I try but Vibration is gone after that:
PHP:
package com.s0bes.fmspeaker;
import android.content.Context;
import android.os.Vibrator;
import de.robv.android.xposed.XC_MethodHook;
import de.robv.android.xposed.XC_MethodReplacement;
import de.robv.android.xposed.XposedBridge;
import de.robv.android.xposed.XposedHelpers;
import static de.robv.android.xposed.XposedHelpers.findClass;
import static de.robv.android.xposed.XposedHelpers.newInstance;
import de.robv.android.xposed.callbacks.XC_LoadPackage.LoadPackageParam;
import android.content.ContentResolver;
import android.provider.Settings;
//import android.os.SystemVibrator;
public class bool1 {
static Context context;
private static Vibrator mVibrator ;
private static Settings.System mSystemSettings;
private static ContentResolver mContentResolver;
private static long[] mHapticPattern;
public static void InitResources(final LoadPackageParam lpparam) throws Throwable {
if (lpparam.packageName.equals("com.android.dialer")) {
XposedHelpers.findAndHookMethod("com.android.phone.common.HapticFeedback", lpparam.classLoader,
"init", Context.class, boolean.class, new XC_MethodHook() {
@Override protected void beforeHookedMethod(final MethodHookParam param) throws Throwable {
XposedBridge.log("HOOOKED init" );
//context=(Context) param.args[0];
}
});
XposedHelpers.findAndHookMethod("com.android.phone.common.HapticFeedback", lpparam.classLoader, "init", Context.class, boolean.class, new XC_MethodReplacement() {
@Override
protected Object replaceHookedMethod(MethodHookParam param) throws Throwable {
context=(Context) param.args[0];
XposedBridge.log("REPLACED init. Enabled="+param.args[1] );
Class Myclass = findClass("android.os.SystemVibrator", lpparam.classLoader);
Object mVibrator = newInstance(Myclass, context);
mHapticPattern = new long[] {0, 10, 2 * 10, 8 * 10};
mSystemSettings = new Settings.System();
mContentResolver = context.getContentResolver();
return true;
}
});
}
}
}
EDIT:
Yeehoooo. I got this working
Your post http://forum.xda-developers.com/showpost.php?p=54951841&postcount=8 very helped me.
Instead replace init method I replaced vibrate();
PHP:
XposedHelpers.findAndHookMethod("com.android.phone.common.HapticFeedback", lpparam.classLoader, "vibrate", new XC_MethodReplacement() {
@Override
protected Object replaceHookedMethod(MethodHookParam param) throws Throwable {
Class Myclass = findClass("android.os.SystemVibrator", lpparam.classLoader);
Object mVibrator = newInstance(Myclass, context);
mHapticPattern = new long[] {0, 10, 1 * 10, 1 * 10};
((Vibrator) mVibrator).vibrate(mHapticPattern, -1);
return true;
}
});
}
Is there a way to use System context from non system app?
I try to create xposed module that enable double-tap to sleep in my specific app (the app is for G3 smart case only, so I try to mimic LG's stock Quick Circle apps).
I tried to override PowerManager.gotoSleep that will do
[CODEjava] mService.gotoSleep(time, GO_TO_SLEEP_REASON_DEVICE_ADMIN)[/CODE]
but it seem that the GO_TO_SLEEP_REASON_USER isn't the problem.
can I save the context of a system app for later use? using this code, context somewhy is null...
Java:
public class XposedModule implements IXposedHookLoadPackage {
static Context context;
[user=439709]@override[/user]
public void handleLoadPackage(XC_LoadPackage.LoadPackageParam lpparam) throws Throwable {
if (lpparam.packageName.equals("com.yoavst.quickapps")) {
findAndHookMethod("com.yoavst.quickapps.DoubleTapper", lpparam.classLoader, "onDoubleTap", Context.class, MotionEvent.class, new XC_MethodHook() {
[user=439709]@override[/user]
protected void afterHookedMethod(MethodHookParam param) throws Throwable {
XposedBridge.log("onDoubleTap After; context: " + (context == null ? "null" : "notNull"));
if (context != null) {
PowerManager powerManager = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
powerManager.goToSleep(((MotionEvent) param.args[1]).getEventTime());
}
}
});
} else if (lpparam.packageName.equals("com.android.systemui")) {
findAndHookMethod("com.android.systemui.SystemUIService", lpparam.classLoader, "onCreate", new XC_MethodHook() {
[user=439709]@override[/user]
protected void beforeHookedMethod(MethodHookParam param) throws Throwable {
// this will be called before the clock was updated by the original method
}
[user=439709]@override[/user]
protected void afterHookedMethod(MethodHookParam param) throws Throwable {
XposedBridge.log("hooking onCreate: " + (param.thisObject == null ? "null" :"not Null"));
context = (Service) param.thisObject;
XposedBridge.log("context: " + (context == null ? "null" :"not Null"));
}
});
}
}
}
You could call AndroidAppHelper.currentApplication() if you need any context — it doesn't look you need the system's context anyway..
GermainZ said:
You could call AndroidAppHelper.currentApplication() if you need any context — it doesn't look you need the system's context anyway..
Click to expand...
Click to collapse
I need the context of an app with DEVICE_POWER permission (level 2 permission).
Oh, wait — your code won't work at all the way you expect it to work. Keep in mind the hooked code is running in the hooked app's process, so even though you set "context" in com.android.systemui, the "context" variable is still null in the "com.yoavst.quickapps" process (and will *always* be null).
You probably want to send a broadcast from your app instead, and register a BroadcastReceiver somewhere in SystemUI to handle it.
@yoavst you need to use a Device Policy Manager that will allow you to turn off the display. Doesn't even require root or xposed.
How to hook a onReceive method which is inside BroadcastReceiver?
Code:
public class RecentsActivity extends Activity
{
mIntentReceiver = new BroadcastReceiver()
{
public void onReceive(Context context, Intent intent)
{
...
}
};
}
I want to get my hook called when onReceive is invoked.
Anyone know?
mIntentReceiver is registered within onCreate method, so...
PHP:
XposedHelpers.findAndHookMethod(RecentsActivity.class, "onCreate", Bundle.class, new XC_MethodHook() {
@Override
protected void afterHookedMethod(MethodHookParam param) throws Throwable {
// get the field
final BroadcastReceiver mIntentReceiver = (BroadcastReceiver) XposedHelpers.getObjectField(param.thisObject, "mIntentReceiver");
// hook its class
XposedHelpers.findAndHookMethod(mIntentReceiver.getClass(), "onReceive", Context.class, Intent.class, new XC_MethodHook() {
@Override
protected void afterHookedMethod(MethodHookParam param) throws Throwable {
// check it !!!
BroadcastReceiver thiz = (BroadcastReceiver) param.thisObject;
if (thiz == mIntentReceiver) {
// get parameters
Context context = (Context) param.args[0];
Intent intent = (Intent) param.args[1];
// do your job...
}
}
});
}
});
Hope that helps you!!
I have a textview that shows your amount of money and i would like the ui to update every second to visually show how much money you have in real time. Would i be able to accomplish this with a timer?, and if so what would it look like.
Hello,
You should do inside your class, outside of any method:
Code:
TextView tv;
String calculatedString;
MyAsyncTask mAsync = null;
Timer timer = null;
TimerTask task = null;
private class MyAsyncTask extends AsyncTask<String, Void, String> {
public MyAsyncTask(){
}
@Override
protected String doInBackground(String... params) {
//Background operation in a separate thread
//Write here your code to run in the background thread
//calculate here whatever you like
calculatedString = ....;
return null;
}
@Override
protected void onPostExecute(String result) {
//Called on Main UI Thread. Executed after the Background operation, allows you to have access to the UI
tv.setText(calculatedString);
}
@Override
protected void onPreExecute() {
//Called on Main UI Thread. Executed before the Background operation, allows you to have access to the UI
}
}
inside the onCreate after super and setContentView:
Code:
tv = (TextView) findViewById(R.id.tv); //your tv id here
final Handler handler = new Handler();
timer = new Timer();
task = new TimerTask() {
@Override
public void run() {
handler.post(new Runnable() {
public void run() {
MyAsyncTask mAsync = new MyAsyncTask();
mAsync.execute();
}
});
}
};
timer.schedule(task, 0, 1000); //Every 1 second
If you still need help, feel free to ask
I have attached 2 screenshots showing the errors i was given after inputting. Any idea how to fix this?
mmdeveloper10 said:
Hello,
You should do inside your class, outside of any method:
Code:
TextView tv;
String calculatedString;
MyAsyncTask mAsync = null;
Timer timer = null;
TimerTask task = null;
private class MyAsyncTask extends AsyncTask<String, Void, String> {
public MyAsyncTask(){
}
@Override
protected String doInBackground(String... params) {
//Background operation in a separate thread
//Write here your code to run in the background thread
//calculate here whatever you like
calculatedString = ....;
return null;
}
@Override
protected void onPostExecute(String result) {
//Called on Main UI Thread. Executed after the Background operation, allows you to have access to the UI
tv.setText(calculatedString);
}
@Override
protected void onPreExecute() {
//Called on Main UI Thread. Executed before the Background operation, allows you to have access to the UI
}
}
inside the onCreate after super and setContentView:
Code:
tv = (TextView) findViewById(R.id.tv); //your tv id here
final Handler handler = new Handler();
timer = new Timer();
task = new TimerTask() {
@Override
public void run() {
handler.post(new Runnable() {
public void run() {
MyAsyncTask mAsync = new MyAsyncTask();
mAsync.execute();
}
});
}
};
timer.schedule(task, 0, 1000); //Every 1 second
If you still need help, feel free to ask
Click to expand...
Click to collapse
Hello,
For the first image:
You have to import the AsyncTask.
add this
Code:
import android.os.AsyncTask;
with the other imports in your java file.
For your second image:
You haven't wrote the line
Code:
setContentView(R.layout.activity_main);
under your super.onCreate(savedInstanceState); and then the code I said above (I said that on my post )
inside onCreate, where activity_main is your xml layout. And you should have inside that layout, a TextView with an id "tv" (or whatever you like)
and then:
Code:
tv = (TextView) findViewById(R.id.tv); //your tv id here
R.id.tv must much the id you have in your layout. Replace it with the actual id of your TextView. If your id is "tv", write R.id.tv, if it is "mytv" write R.id.mytv. ( I said that on my post also)
Can you show your layout file? (XML - your activity_main.xml). You said that you have a TextView Where is your TextView?
Ok I fixed the problems stated and now only have these two errors remaining
mmdeveloper10 said:
Hello,
For the first image:
You have to import the AsyncTask.
add this
Code:
import android.os.AsyncTask;
with the other imports in your java file.
For your second image:
You haven't wrote the line
Code:
setContentView(R.layout.activity_main);
under your super.onCreate(savedInstanceState); and then the code I said above (I said that on my post )
inside onCreate, where activity_main is your xml layout. And you should have inside that layout, a TextView with an id "tv" (or whatever you like)
and then:
Code:
tv = (TextView) findViewById(R.id.tv); //your tv id here
R.id.tv must much the id you have in your layout. Replace it with the actual id of your TextView. If your id is "tv", write R.id.tv, if it is "mytv" write R.id.mytv. ( I said that on my post also)
Can you show your layout file? (XML - your activity_main.xml). You said that you have a TextView Where is your TextView?
Click to expand...
Click to collapse
Have you imported this?
Code:
import java.util.logging.Handler;
If so, change it to
Code:
import android.os.Handler;
Im not at the computer but I think that should solve my issue I will keep you updated
Sent from my HTC6525LVW using XDA Free mobile app
Hey thanks so much its working perfectly now :good:
Can anybody help me. I have developed a quiz app. At the end of the quiz the result activity must show up but the scores activity shows up. The scores activity only shows up when the scores button is selected on the MainActivity.
Quiz.java
Code:
package app.mobiledevicesecurity;
import java.util.List;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Typeface;
import android.media.MediaPlayer;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class Quiz extends Activity
{
List<Question> questionList;
int score = 0;
int qid = 0;
Question currentQuest;
TextView txtQuestion, scored;
Button button1, button2, button3;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quiz);
QuizHelper db = new QuizHelper(this);
questionList = db.getAllQuestions();
currentQuest = questionList.get(qid);
txtQuestion = (TextView) findViewById(R.id.txtQuestion);
button1 = (Button) findViewById(R.id.button1);
button2 = (Button) findViewById(R.id.button2);
button3 = (Button) findViewById(R.id.button3);
scored = (TextView) findViewById(R.id.score);
setQuestionView();
button1.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v) {
getAnswer(button1.getText().toString());
}
});
button2.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v) {
getAnswer(button2.getText().toString());
}
});
button3.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v) {
getAnswer(button3.getText().toString());
}
});
}
public void getAnswer(String AnswerString)
{
if (currentQuest.getAnswer().equals(AnswerString))
{
score++;
scored.setText("Score : " + score);
}
else
{
Intent intent = new Intent(Quiz.this,
Result.class);
Bundle b = new Bundle();
b.putInt("score", score);
intent.putExtras(b);
startActivity(intent);
finish();
}
if (qid < questionList.size()) {
currentQuest = questionList.get(qid);
setQuestionView();
}
else
{
Intent intent = new Intent(Quiz.this,
Result.class);
Bundle b = new Bundle();
b.putInt("score", score);
intent.putExtras(b);
startActivity(intent);
finish();
}
}
private void setQuestionView()
{
txtQuestion.setText(currentQuest.getQuest());
button1.setText(currentQuest.getOption1());
button2.setText(currentQuest.getOption2());
button3.setText(currentQuest.getOption3());
qid++;
}
}
Result.java
Code:
package app.mobiledevicesecurity;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class Result extends Activity {
private static Button playbtn;
private static Button menubutton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_result);
OnClickPlayButtonListener();
OnClickMenuButtonListener();
TextView textResult = (TextView) findViewById(R.id.textResult);
Bundle b = getIntent().getExtras();
int score = b.getInt("score");
textResult.setText("You scored" + " " + score + " for the quiz.");
Intent intent2 = new Intent(Result.this,
Scores.class);
Bundle bun = new Bundle();
bun.putInt("score", score);
intent2.putExtras(bun);
startActivity(intent2);
finish();
}
public void OnClickPlayButtonListener() {
playbtn = (Button) findViewById(R.id.btn);
playbtn.setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent("app.mobiledevicesecurity.Quiz");
startActivity(intent);
}
}
);
}
public void OnClickMenuButtonListener() {
menubutton = (Button) findViewById(R.id.menubtn);
menubutton.setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(intent);
}
}
);
}
}
Scores.java
Code:
package app.mobiledevicesecurity;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
import android.content.Intent;
public class Scores extends ActionBarActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_scores);
TextView txtScore1 = (TextView) findViewById(R.id.txtScore1);
Bundle bun = getIntent().getExtras();
int score = bun.getInt("score");
txtScore1.setText("score:" + " " + score + " for the quiz.");
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_scores, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
You are doing it wrong once you send the intent to start the Result Activity you have this code on your onCreate method:
Intent intent2 = new Intent(Result.this,
Scores.class);
Bundle bun = new Bundle();
bun.putInt("score", score);
intent2.putExtras(bun);
startActivity(intent2);
finish();
Which causes the Result activity to launch Scores and close Result
Please move this code out of your onCreate method and only call it when you need to!
Can you maybe help me with this. I am in the process of learning this application development. The score must be passed over to the Scores.java activity
This is what I tried but it do not work:
Result.java:
Code:
package app.mobiledevicesecurity;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class Result extends Activity {
private static Button playbtn;
private static Button menubutton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_result);
OnClickPlayButtonListener();
OnClickMenuButtonListener();
TextView textResult = (TextView) findViewById(R.id.textResult);
Bundle b = getIntent().getExtras();
int score = b.getInt("score");
textResult.setText("You scored" + " " + score + " for the quiz.");
}
public void getScore()
{
Bundle b = getIntent().getExtras();
int score = b.getInt("score");
Intent intent2 = new Intent(Result.this,
Scores.class);
Bundle bun = new Bundle();
bun.putInt("score", score);
intent2.putExtras(bun);
startActivity(intent2);
finish();
}
public void OnClickPlayButtonListener() {
playbtn = (Button) findViewById(R.id.btn);
playbtn.setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent("app.mobiledevicesecurity.Quiz");
startActivity(intent);
}
}
);
}
public void OnClickMenuButtonListener() {
menubutton = (Button) findViewById(R.id.menubtn);
menubutton.setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(intent);
}
}
);
}
}
Scores.java:
Code:
package app.mobiledevicesecurity;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
import android.content.Intent;
public class Scores extends ActionBarActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_scores);
Result res = new Result();
res.getScore();
TextView txtScore1 = (TextView) findViewById(R.id.txtScore1);
Bundle bun = getIntent().getExtras();
int score = bun.getInt("score");
txtScore1.setText("Last quiz score:" + " " + score + ".");
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_scores, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Logcat:
Code:
09-08 20:47:51.143 1050-1050/app.mobiledevicesecurity E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: app.mobiledevicesecurity, PID: 1050
java.lang.RuntimeException: Unable to start activity ComponentInfo{app.mobiledevicesecurity/app.mobiledevicesecurity.Scores}: java.lang.NullPointerException: Attempt to invoke virtual method 'android.os.Bundle android.content.Intent.getExtras()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2325)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2390)
at android.app.ActivityThread.access$800(ActivityThread.java:151)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5257)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'android.os.Bundle android.content.Intent.getExtras()' on a null object reference
at app.mobiledevicesecurity.Result.getScore(Result.java:31)
at app.mobiledevicesecurity.Scores.onCreate(Scores.java:18)
at android.app.Activity.performCreate(Activity.java:5990)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2278)
************at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2390)
************at android.app.ActivityThread.access$800(ActivityThread.java:151)
************at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
************at android.os.Handler.dispatchMessage(Handler.java:102)
************at android.os.Looper.loop(Looper.java:135)
************at android.app.ActivityThread.main(ActivityThread.java:5257)
************at java.lang.reflect.Method.invoke(Native Method)
************at java.lang.reflect.Method.invoke(Method.java:372)
************at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
************at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
This is wrong:
Result res = new Result();
res.getScore();
You are instantiating a new Result Activity which of course will have a null bundle because its not the same original Result Activity! What you are doing is the same has storing something on your box object named "box1" and then create a new box named "box2" and hope the object you stored will be on this new box!
If i understood correctly you want to show the result activity on the end of the quiz which you seemed to have working. And now you want to show the scores activity on press of a button on the main activity correct?
For that create a listener for the scores button on your Main Activity and add code to launch the Scores Activity with an intent where you pass the score. And then retrieve the bundle on your onCreate method on your ScoresActivity!
Can you maybe help me. I understand what you say but do not know how to do it.
Here is my main activity:
Code:
package app.mobiledevicesecurity;
import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends ActionBarActivity {
DatabaseHelper myDb;
private static Button readbtn;
private static Button quizbtn;
private static Button scoresbtn;
private static Button settingsbtn;
private static Button helpbtn;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myDb = new DatabaseHelper(this);
myDb.insertData();
OnClickReadButtonListener();
OnClickQuizButtonListener();
OnClickScoresButtonListener();
OnClickSettingsButtonListener();
OnClickHelpButtonListener();
}
public void OnClickReadButtonListener() {
readbtn = (Button) findViewById(R.id.readbutton);
readbtn.setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent("app.mobiledevicesecurity.Read_Category");
startActivity(intent);
}
}
);
}
public void OnClickQuizButtonListener() {
quizbtn = (Button) findViewById(R.id.quizbutton);
quizbtn.setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent("app.mobiledevicesecurity.Quiz");
startActivity(intent);
}
}
);
}
public void OnClickScoresButtonListener() {
scoresbtn = (Button) findViewById(R.id.scoresbutton);
scoresbtn.setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent("app.mobiledevicesecurity.Scores");
startActivity(intent);
}
}
);
}
public void OnClickSettingsButtonListener() {
settingsbtn = (Button) findViewById(R.id.settingsbutton);
settingsbtn.setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent("app.mobiledevicesecurity.Settings");
startActivity(intent);
}
}
);
}
public void OnClickHelpButtonListener() {
helpbtn = (Button) findViewById(R.id.helpbutton);
helpbtn.setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent("app.mobiledevicesecurity.Help");
startActivity(intent);
}
}
);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Android Studio Eclipse - 1
I wonder if I 10 of the many many who call to use FDI. In my 20 years I have been on 1: MS Visual Studio, 2: Eclipse 3: STS (spring version of Eclipse), 4: RAD (IBM Websphere version eclipse commercially), 5: and now Netbeans 6: IntelliJ. The last one is my favorite by far far away. When you say many many Suppose you can take a little more to the list?
I let Visual Studio, because I. To Java instead of C ++ I went into eclipse, because that's what everyone else was doing, so I thought it was the only tool. I moved to STS because I look for alternatives, because eclipse was anything but stable, if you use EJB, Spring, Hibernate and one of the usual suspects in the application server where the debugging and publishing is a very regular basis. I had to use RAD, because a customer forced me. RAD6.2 and if the company that I was, I was probably still sued IBM as RAD6.2 is not even worth called a beta version. Since none of the releabed of the Eclipse-based IDE agony I have so hard to avoid, tried, I tried NetBeans. And things clarified. By integrating Maven was better than the eclipse. Honesty I admit liable that I never really know him so well, because professional, everyone was from Eclipse moving to IntelliJ, and I felt nothing but relief, where once swore. And so I joined the hive.
And I'm glad that I did it. IntelliJ is not perfect, but in my humble opinion, approaches. And if you have a problem, send an email to get these people and nine out of ten an answer within an hour. In the worst case within a day. At least in my case, as a paying customer.
I can not comment on Eclipse with the development of Android. I am pleased to talk about Java developers. For me, the Eclipse is a past long forgotten. Never again.
#Eclipse.
The Wrong Activity Shows Up Android Studio OK - we have it, you hate Eclipse. Personally, I find that the argument pointless. I do not like Eclipse, but I have many, many IDEs that were much worse used. Many developers - including myself - to live well with Eclipse for the daily work, either by choice or simply because we have to. Is set correctly Eclipse IDE a solid. Arguing that it fragile, even if the "stable" version of Android Studio still hangs / freezes it seems quite often rather disingenuous.
The other thing, this article makes completely useless is that they are all reasons (mostly true) for the reason why Android Studio is listed size. They forget to mention the various reasons - equally valid - because Android Studio is terrible (in the same way that we speak only bad problems with Eclipse, but none of its strengths).
Personally, I think Android Studio is practically dead, and is never more than a footnote in the history of the development of Android to be. One reason is due to the fact the unit - another is simply the inevitable course of development.
# 1 Android libraries
More than a year has passed since the AS was launched, and Google has not yet developed a sensible approach with Android libraries. Never tried above also brings a relatively simple configuration library? I tried to explain how to install the libraries in Android as for a new developer? There are zero relevant documents on the website and 50% of what it is out of date on the Internet - the remaining 50% is a terrible reading. Re usability of the code is the cornerstone of good development practices, but there are exercises that suggest in all seriousness physically copy code between projects in Android Studio. 1970 called ...
Inability of Google to provide a simple and intuitive code reuse mechanical - especially after (finally) it did work in Eclipse, IMO is the only major flaw Android Studio. At the same time makes it impossible for developers to have a choice (for example, everything is in Eclipse or AS) is just icing on the cake.
Even if - if you can just explain how multiple applications with multiple libraries Androdi (and some libraries use each other) set up, then I would see such a blog post. More than that - I would be very impressed. I tried it myself and it failed - and I have not seen anyone doing it. IMO - when a build tool is only for experts, it is a poor tool of creation. Gradle for Android is just that. Few can the software companies, technology that afford to introduce to understand only 1-2 people at home.
# 2 Google is not interested in having Android SDK to survive
For me, this is the largest study problem Android. It is an IDE for what developed a dying language. Android Studio is already dead.
Why? Since cross-platform (ie, at least Android + IOS) is the only sensible choice if you want to start the development of mobile applications today. Limit yourself to a single platform is just silly - and especially for the Games (which is - I would remind you - 90% of sales in the App Store), there are many, many excellent multi-platform tools like unit and Cocos2dx. None of them have Java or the Android SDK as a development language.
If Google wanted Android Java must be more than a footnote in history, they would have made an effort - any effort - it is Java Android cross-compiled on other platforms. At least one could the Android SDK can create programs Chrome, or even Android applications compiled directly from desktop applications. Both would be relatively simple. They will not, though. Instead dithering about Android and Chrome OS they want to support.
Of course - some argue that Google has already decided, and the choice is Chrome OS. Soon you can applications can run Chrome either in Chrome OS, Android, iOS and Google (has already announced that, based on Apache Cordoba) Personally, I'm not quite sure that Google has not to develop their minds yet, but ultimately developing the Community to make the choice for them, and is not to be Android SDK.
I'm not saying that he die this year or next - but at some point it becomes very clear that Google is not interested in who became the development of native Android (in typical Google approach, it does not surprise me if it even makes it Studio to Android 1.0). And I say this not because I hate Android - I love the strengths of the Android SDK, and I would no more joy love to hear Google ads to make I / O to show that they are going to the Android SDK build. I doubt that will happen when.
Ironically, starting as a developer, leaving Android SDK (Android and Studio), one of the languages that are likely to encounter, JavaScript (the language of choice for Google Chrome OS), which often lead people back in .... Eclipse.