Hi, Can someone please help me to resolve the following issue?
I have an arraylist that I have created in an activity file. Name of this arraylist is doctorList and it is public. But when I try to populate a listview with this arraylist using setadapter, it refuses to identify the arraylist.
Code:
private ListView docList;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_doctor__list);
docList = (ListView) findViewById(R.id.docList);
docList.setAdapter(new ArrayAdapter<String>(Doctor_List.this, android.R.layout.simple_list_item_1, [B][U][I]doctorList[/I][/U][/B]));
}
The doctorList appears red and it says the symbol cant be resolved.
Where are you getting the doctorList ArrayList? The ArrayList needs to be declared and initialised before you can pass it to the adapter.
TechTev said:
Where are you getting the doctorList ArrayList? The ArrayList needs to be declared and initialised before you can pass it to the adapter.
Click to expand...
Click to collapse
doctorList is declared and initialized in another activity ..
Code:
private DrawerLayout mDrawerLayout;
private Button pButton = null;
private ActionBarDrawerToggle mToggle;
private int noOfDoctors;
public ArrayList<String> doctorList = new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_patient_first_screeen);
pButton = (Button) findViewById(R.id.goTODocList);
pButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Intent i = new Intent (view.getContext(),Doctor_List.class);
startActivity(i);
final String url = <link>;
final JsonArrayRequest getDocList = new JsonArrayRequest(Request.Method.GET, url, null,
new Response.Listener<JSONArray>() {
@RequiresApi(api = Build.VERSION_CODES.KITKAT)
@Override
public void onResponse(JSONArray response) {
try {
JSONArray docList = new JSONArray(response);
JSONObject docRow;
noOfDoctors = docList.length();
for (int i=0; i<noOfDoctors; i++) {
docRow = docList.getJSONObject(i);
doctorList.add(i,docRow.getString("name"));
}
Toast.makeText(PatientFirstScreen.this, "Hi brother.", Toast.LENGTH_SHORT).show();
} catch (Exception e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(PatientFirstScreen.this, "List of Doctors can't be retrieved right now. Please try later.", Toast.LENGTH_SHORT).show();
//what to do with error
}
}
);
MySingleton.getInstance(PatientFirstScreen.this).addToRequestQueue(getDocList);
}}
);
I see. What you need to do is pass the ArrayList as an Extra to the activity. To do this you need to call startActivity after you've done your JSONArray request. Here's an example of what that might look like:
First activity
Code:
private DrawerLayout mDrawerLayout;
private Button pButton = null;
private ActionBarDrawerToggle mToggle;
private int noOfDoctors;
public ArrayList<String> doctorList = new ArrayList<>();
@override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_patient_first_screeen);
pButton = (Button) findViewById(R.id.goTODocList);
pButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
final String url = <link>;
final JsonArrayRequest getDocList = new JsonArrayRequest(Request.Method.GET, url, null,
new Response.Listener<JSONArray>() {
@RequiresApi(api = Build.VERSION_CODES.KITKAT)
@override
public void onResponse(JSONArray response) {
try {
JSONArray docList = new JSONArray(response);
JSONObject docRow;
noOfDoctors = docList.length();
for (int i=0; i<noOfDoctors; i++) {
docRow = docList.getJSONObject(i);
doctorList.add(i,docRow.getString("name"));
}
Toast.makeText(PatientFirstScreen.this, "Hi brother.", Toast.LENGTH_SHORT).show();
// Call start activity here as it depends on the docList.
Intent i = new Intent (view.getContext(),Doctor_List.class);
// Put the String Array List as an extra.
i.putStringArrayListExtra(Doctor_List.EXTRA_DOC_LIST, docList);
startActivity(i);
} catch (Exception e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@override
public void onErrorResponse(VolleyError error) {
Toast.makeText(PatientFirstScreen.this, "List of Doctors can't be retrieved right now. Please try later.", Toast.LENGTH_SHORT).show();
//what to do with error
}
}
);
MySingleton.getInstance(PatientFirstScreen.this).addToRequestQueue(getDocList);
}}
);
Doctor List Activity
Code:
private ListView docList;
// Key for the extra you are passing to the activity.
public static final String EXTRA_DOC_LIST = "your.package.name.Doc_List.extra_doc_list";
@override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_doctor__list);
docList = (ListView) findViewById(R.id.docList);
// Get the doctor list extra
ArrayList<String> doctorList = getIntent.getStringArrayListExtra(EXTRA_DOC_LIST);
// The Adapter should now work
docList.setAdapter(new ArrayAdapter<String>(Doctor_List.this, android.R.layout.simple_list_item_1, doctorList));
}
TechTev said:
I see. What you need to do is pass the ArrayList as an Extra to the activity. To do this you need to call startActivity after you've done your JSONArray request. Here's an example of what that might look like:
First activity
Code:
private DrawerLayout mDrawerLayout;
private Button pButton = null;
private ActionBarDrawerToggle mToggle;
private int noOfDoctors;
public ArrayList<String> doctorList = new ArrayList<>();
@override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_patient_first_screeen);
pButton = (Button) findViewById(R.id.goTODocList);
pButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
final String url = <link>;
final JsonArrayRequest getDocList = new JsonArrayRequest(Request.Method.GET, url, null,
new Response.Listener<JSONArray>() {
@RequiresApi(api = Build.VERSION_CODES.KITKAT)
@override
public void onResponse(JSONArray response) {
try {
JSONArray docList = new JSONArray(response);
JSONObject docRow;
noOfDoctors = docList.length();
for (int i=0; i<noOfDoctors; i++) {
docRow = docList.getJSONObject(i);
doctorList.add(i,docRow.getString("name"));
}
Toast.makeText(PatientFirstScreen.this, "Hi brother.", Toast.LENGTH_SHORT).show();
// Call start activity here as it depends on the docList.
Intent i = new Intent (view.getContext(),Doctor_List.class);
// Put the String Array List as an extra.
i.putStringArrayListExtra(Doctor_List.EXTRA_DOC_LIST, docList);
startActivity(i);
} catch (Exception e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@override
public void onErrorResponse(VolleyError error) {
Toast.makeText(PatientFirstScreen.this, "List of Doctors can't be retrieved right now. Please try later.", Toast.LENGTH_SHORT).show();
//what to do with error
}
}
);
MySingleton.getInstance(PatientFirstScreen.this).addToRequestQueue(getDocList);
}}
);
Doctor List Activity
Code:
private ListView docList;
// Key for the extra you are passing to the activity.
public static final String EXTRA_DOC_LIST = "your.package.name.Doc_List.extra_doc_list";
@override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_doctor__list);
docList = (ListView) findViewById(R.id.docList);
// Get the doctor list extra
ArrayList<String> doctorList = getIntent.getStringArrayListExtra(EXTRA_DOC_LIST);
// The Adapter should now work
docList.setAdapter(new ArrayAdapter<String>(Doctor_List.this, android.R.layout.simple_list_item_1, doctorList));
}
Click to expand...
Click to collapse
Thanks. But, the arraylist is now accepted in the adapter but now, the button has stopped responding. Looks like the intent is not working now. I can't go the next page.
pk0486 said:
Thanks. But, the arraylist is now accepted in the adapter but now, the button has stopped responding. Looks like the intent is not working now. I can't go the next page.
Click to expand...
Click to collapse
I just checked the code I posted and I made a couple of typos and I think as the activity start call is from within the listener it needs to be Patient_First_Screen.this.startActivity(i).
Try this code:
Code:
private DrawerLayout mDrawerLayout;
private Button pButton = null;
private ActionBarDrawerToggle mToggle;
private int noOfDoctors;
public ArrayList<String> doctorList = new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_patient_first_screeen);
pButton = (Button) findViewById(R.id.goTODocList);
pButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
final String url = <link>;
final JsonArrayRequest getDocList = new JsonArrayRequest(Request.Method.GET, url, null,
new Response.Listener<JSONArray>() {
@RequiresApi(api = Build.VERSION_CODES.KITKAT)
@Override
public void onResponse(JSONArray response) {
try {
JSONArray docList = new JSONArray(response);
JSONObject docRow;
noOfDoctors = docList.length();
for (int i=0; i<noOfDoctors; i++) {
docRow = docList.getJSONObject(i);
doctorList.add(i,docRow.getString("name"));
}
Toast.makeText(PatientFirstScreen.this, "Hi brother.", Toast.LENGTH_SHORT).show();
// Call start activity here as it depends on the docList.
Intent i = new Intent (view.getContext(),Doctor_List.class);
// Put the String Array List as an extra.
i.putStringArrayListExtra(Doctor_List.EXTRA_DOC_LIST, doctorList);
Patient_First_Screen.this.startActivity(i);
} catch (Exception e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(PatientFirstScreen.this, "List of Doctors can't be retrieved right now. Please try later.", Toast.LENGTH_SHORT).show();
//what to do with error
}
}
);
MySingleton.getInstance(PatientFirstScreen.this).addToRequestQueue(getDocList);
}}
);
TechTev said:
I just checked the code I posted and I made a couple of typos and I think as the activity start call is from within the listener it needs to be Patient_First_Screen.this.startActivity(i).
Try this code:
Code:
private DrawerLayout mDrawerLayout;
private Button pButton = null;
private ActionBarDrawerToggle mToggle;
private int noOfDoctors;
public ArrayList<String> doctorList = new ArrayList<>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_patient_first_screeen);
pButton = (Button) findViewById(R.id.goTODocList);
pButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
final String url = <link>;
final JsonArrayRequest getDocList = new JsonArrayRequest(Request.Method.GET, url, null,
new Response.Listener<JSONArray>() {
@RequiresApi(api = Build.VERSION_CODES.KITKAT)
@Override
public void onResponse(JSONArray response) {
try {
JSONArray docList = new JSONArray(response);
JSONObject docRow;
noOfDoctors = docList.length();
for (int i=0; i<noOfDoctors; i++) {
docRow = docList.getJSONObject(i);
doctorList.add(i,docRow.getString("name"));
}
Toast.makeText(PatientFirstScreen.this, "Hi brother.", Toast.LENGTH_SHORT).show();
// Call start activity here as it depends on the docList.
Intent i = new Intent (view.getContext(),Doctor_List.class);
// Put the String Array List as an extra.
i.putStringArrayListExtra(Doctor_List.EXTRA_DOC_LIST, doctorList);
Patient_First_Screen.this.startActivity(i);
} catch (Exception e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(PatientFirstScreen.this, "List of Doctors can't be retrieved right now. Please try later.", Toast.LENGTH_SHORT).show();
//what to do with error
}
}
);
MySingleton.getInstance(PatientFirstScreen.this).addToRequestQueue(getDocList);
}}
);
Click to expand...
Click to collapse
Still the same issue .. Can you please explain what is the issue with the code? I didn't understand why did you modify the code?
pk0486 said:
Still the same issue .. Can you please explain what is the issue with the code? I didn't understand why did you modify the code?
Click to expand...
Click to collapse
Sure, I moved the call to start the activity into the JSON response listener as that's when the doctorList is populated which we need to pass to the next activity. As that is in an anonymous inner class it needs to call the instance of the outer class using OuterClassName.this . However you have two inner classes so that's probably why it isn't working.
Maybe try moving the startActivity(i) call and intent creation to below the call to MySingleton.getInstance(PatientFirstScreen.this).addToRequestQueue(getDocList);
TechTev said:
Sure, I moved the call to start the activity into the JSON response listener as that's when the doctorList is populated which we need to pass to the next activity. As that is in an anonymous inner class it needs to call the instance of the outer class using OuterClassName.this . However you have two inner classes so that's probably why it isn't working.
Maybe try moving the startActivity(i) call and intent creation to below the call to MySingleton.getInstance(PatientFirstScreen.this).addToRequestQueue(getDocList);
Click to expand...
Click to collapse
Got it. Thanks. You were right. But there was some issue with my JSONArray because of which the loop wasn't getting executed. Resolved it now. Thanks again!
pk0486 said:
Got it. Thanks. You were right. But there was some issue with my JSONArray because of which the loop wasn't getting executed. Resolved it now. Thanks again!
Click to expand...
Click to collapse
No problem. Good luck with the rest of your project.
TechTev said:
No problem. Good luck with the rest of your project.
Click to expand...
Click to collapse
Now, I am stuck again. I changed my arraylist to custom array list. I have created the custom array adapter and its fine. I got my JSONArray which I parsed and created the required ArrayList. But when I use this ArrayList as an argument for the custom array adapter, it gives the below error.
https://ibb.co/hhYqOG - this is the link for screenshot of error
Code:
List<DocRow> doctors = new ArrayList<>();
After this, I have assigned values to this ArrayList.
Code:
DocAdapter adapter = new DocAdapter(getApplicationContext(), R.layout.doc_row, doctors);
docList.setAdapter(adapter);
Below is the adapter constructor
Code:
public DocAdapter(@NonNull Context context, @LayoutRes int resource, ArrayList<DocRow> doctors) {
super(context, resource, doctors);
this.context = context;
this.resource = resource;
this.doctors = doctors;
inflater = LayoutInflater.from(context);
What am I missing? Thanks.
pk0486 said:
Now, I am stuck again. I changed my arraylist to custom array list. I have created the custom array adapter and its fine. I got my JSONArray which I parsed and created the required ArrayList. But when I use this ArrayList as an argument for the custom array adapter, it gives the below error.
https://ibb.co/hhYqOG - this is the link for screenshot of error
Code:
List<DocRow> doctors = new ArrayList<>();
After this, I have assigned values to this ArrayList.
Code:
DocAdapter adapter = new DocAdapter(getApplicationContext(), R.layout.doc_row, doctors);
docList.setAdapter(adapter);
Below is the adapter constructor
Code:
public DocAdapter(@NonNull Context context, @LayoutRes int resource, ArrayList<DocRow> doctors) {
super(context, resource, doctors);
this.context = context;
this.resource = resource;
this.doctors = doctors;
inflater = LayoutInflater.from(context);
What am I missing? Thanks.
Click to expand...
Click to collapse
I think it's because you've specifically asked for an arrayList instead of a List as an argument for your custom adapter constructor. Try changing your constructor for the adapter to this:
Code:
public DocAdapter(@NonNull Context context, @LayoutRes int resource, List<DocRow> doctors) {
super(context, resource, doctors);
this.context = context;
this.resource = resource;
this.doctors = doctors;
inflater = LayoutInflater.from(context);
Related
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!!
Hi there. I'm trying to write a module for an app that looks like this:
Code:
public class ThirdPartyAppView extends View {
// ...
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
{
// ...
// do some stuff to calculate desired dimensions
// ...
setMeasuredDimension(desiredWidth, desiredHeight);
}
// ...
}
I want to change the calculated dimensions, so I'm replacing the onMeasure method of this class, like this:
Code:
XC_MethodReplacement onMeasure_replacement = new XC_MethodReplacement() {
@Override
protected Object replaceHookedMethod(MethodHookParam param) throws Throwable {
View v = (View) param.thisObject;
int paramInt1 = (Integer) param.args[0];
int paramInt2 = (Integer) param.args[1];
// ...
// do MY OWN stuff to calculate desired dimensions
// ...
setMeasuredDimension(myDesiredWidth, myDesiredHeight); // here is the problem call
return null;
}
};
findAndHookMethod("com.third.party.app.ThirdPartyAppView",
lpparam.classLoader,
"onMeasure", int.class, int.class,
onMeasure_replacement);
The roadblock I'm hitting is
Code:
The method setMeasuredDimension(int, int) is undefined for the type new XC_MethodReplacement(){}
Any pointers?
On closer look, that should be v.setMeasuredDimension:
Code:
View v = (View) param.thisObject;
// ...
v.setMeasuredDimension(myDesiredWidth, myDesiredHeight); // here is the problem call
return null;
But both onMeasure() and setMeasuredDimension() are protected methods on class ThirdPartyAppView. How could I call them from the module? I can't instance ThirdPartyAppView...
Found a solution thanks to http://forum.xda-developers.com/showpost.php?p=57190802&postcount=2
Ended up hooking on the superclass instead (android.view.View), doing things before calling setMeasuredDimension() there, and checking class name within the hook. This did the trick.
Code:
public void handleLoadPackage(LoadPackageParam lpparam) throws Throwable {
if (!lpparam.packageName.equals(com.third.party.app))
return;
XC_MethodHook setMeasuredDimensionHook = new XC_MethodHook() {
@Override
protected void beforeHookedMethod(MethodHookParam param) throws Throwable {
if (param.thisObject.getClass().getName().equals(com.third.party.app.ThirdPartyAppView") {
View v = (View) param.thisObject;
int paramInt1 = (Integer) param.args[0];
int paramInt2 = (Integer) param.args[1];
// ...
// calculate my dimensions here
// ...
param.args[0] = desiredWidth;
param.args[1] = desiredHeight;
}
};
findAndHookMethod("android.view.View",
lpparam.classLoader,
"setMeasuredDimension", int.class, int.class,
setMeasuredDimensionHook);
}
Nephiel said:
Found a solution thanks to http://forum.xda-developers.com/showpost.php?p=57190802&postcount=2
Ended up hooking on the superclass instead (android.view.View), doing things before calling setMeasuredDimension() there, and checking class name within the hook. This did the trick.
Code:
public void handleLoadPackage(LoadPackageParam lpparam) throws Throwable {
if (!lpparam.packageName.equals(com.third.party.app))
return;
XC_MethodHook setMeasuredDimensionHook = new XC_MethodHook() {
@Override
protected void beforeHookedMethod(MethodHookParam param) throws Throwable {
if (param.thisObject.getClass().getName().equals(com.third.party.app.ThirdPartyAppView") {
View v = (View) param.thisObject;
int paramInt1 = (Integer) param.args[0];
int paramInt2 = (Integer) param.args[1];
// ...
// calculate my dimensions here
// ...
param.args[0] = desiredWidth;
param.args[1] = desiredHeight;
}
};
findAndHookMethod("android.view.View",
lpparam.classLoader,
"setMeasuredDimension", int.class, int.class,
setMeasuredDimensionHook);
}
Click to expand...
Click to collapse
Another way is to "emulate" call to setMeasuredDimension directly from onMeasure hook.
Example: https://github.com/GravityBox/Gravi...kitkat/gravitybox/ModQuickSettings.java#L1358
"Emulating" means you basically execute the same code that the original method does.
Of course, attention should be paid to different android versions and potential differences in setMeasuredDimension implementation.
I want to show the result activity on the end of the quiz which is working. And then show the scores activity on press of a button on the main activity
Advice I got is to Create a listener for the scores button on Main Activity and add code to launch the Scores Activity with an intent where you pass the score. And then retrieve the bundle on the onCreate method on your ScoresActivity. Can someone help me on this please regarding the code.
MainActivity:
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.TextView;
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);
}
}
Result:
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;
int score;
@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();
score = b.getInt("score");
textResult.setText("You scored" + " " + score + " for the quiz.");
}
public void getScore()
{
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:
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);
}
}
You should never create instances of activity with "new" keyword, because Activity is a part of Android ecosystem, not just a java class. So the line with
Code:
new Result();
is wrong. Then, if you want to pass some data from one activity to another when the latter is being opened after click, you need to put you data in the Intent (like you did it right, but in the wrong place in code)
Code:
scoresbtn.setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent2 = new Intent(Result.this,
Scores.class);
Bundle bun = new Bundle();
bun.putInt("score", score);
intent2.putExtras(bun);
startActivity(intent2);
}
}
);
That's it, your code on fetching the "score" variable out of Intent in Score activity is seemingly right.
svvorf said:
You should never create instances of activity with "new" keyword, because Activity is a part of Android ecosystem, not just a java class. So the line with
Code:
new Result();
is wrong. Then, if you want to pass some data from one activity to another when the latter is being opened after click, you need to put you data in the Intent (like you did it right, but in the wrong place in code)
Code:
scoresbtn.setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent2 = new Intent(Result.this,
Scores.class);
Bundle bun = new Bundle();
bun.putInt("score", score);
intent2.putExtras(bun);
startActivity(intent2);
}
}
);
That's it, your code on fetching the "score" variable out of Intent in Score activity is seemingly right.
Click to expand...
Click to collapse
Can you maybe show me where to put this in my code. And help me with the new Result() part
Hello, I need help for a little project
I have a TextView and a Button in the MainActivity, and an EditText and Button in Activity2 which returns back to MainActivity.
I can switch to the other Activity but I can't send the input of the user in Activity2 back as TextView.
I think there is a problem with the method addListenerOnButton but I'm not sure...
MainActivity:
Code:
public class MainActivity extends Activity {
public TextView resultText;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
resultText = (TextView) findViewById(R.id.resultText);
// resultText.setText(getIntent().getStringExtra(""));
}
public void onStartButtonClick(View view){
Intent intent = new Intent(this, Activity2.class);
startActivity(intent);
}
}
Activity2:
Code:
public class Activity2 extends Activity {
public EditText editText;
Button zuruckButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_2);
addListenerOnButton();
editText = (EditText) findViewById(R.id.editText);
}
public void addListenerOnButton(){
zuruckButton = (Button) findViewById(R.id.zuruckButton);
zuruckButton.setOnClickListener(new View.OnClickListener(){
public void onClick(View view){
EditText editText = (EditText) findViewById(R.id.editText);
String text = editText.getText().toString();
Intent intent2 = new Intent(view.getContext(), MainActivity.class);
intent2.putExtra("mein Text", text);
startActivity(intent2);
}
});
}
}
mina2005 said:
Hello, I need help for a little project
I have a TextView and a Button in the MainActivity, and an EditText and Button in Activity2 which returns back to MainActivity.
I can switch to the other Activity but I can't send the input of the user in Activity2 back as TextView.
I think there is a problem with the method addListenerOnButton but I'm not sure...
MainActivity:
Code:
public class MainActivity extends Activity {
public TextView resultText;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
resultText = (TextView) findViewById(R.id.resultText);
// resultText.setText(getIntent().getStringExtra(""));
}
public void onStartButtonClick(View view){
Intent intent = new Intent(this, Activity2.class);
startActivity(intent);
}
}
Activity2:
Code:
public class Activity2 extends Activity {
public EditText editText;
Button zuruckButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_2);
addListenerOnButton();
editText = (EditText) findViewById(R.id.editText);
}
public void addListenerOnButton(){
zuruckButton = (Button) findViewById(R.id.zuruckButton);
zuruckButton.setOnClickListener(new View.OnClickListener(){
public void onClick(View view){
EditText editText = (EditText) findViewById(R.id.editText);
String text = editText.getText().toString();
Intent intent2 = new Intent(view.getContext(), MainActivity.class);
intent2.putExtra("mein Text", text);
startActivity(intent2);
}
});
}
}
Click to expand...
Click to collapse
Where your
Code:
editText = (EditText) findViewById(R.id.editText);
is, you can delete this as you are referencing it in your button click method. Unless you are using it for anything else then this can be removed.
Also where
Code:
// resultText.setText(getIntent().getStringExtra(""));
is, this can be uncommented and at the end in brackets of
Code:
getStringExtra("")
is, you should put the extra string you stated as
Code:
intent2.putExtra("mein Text", text);
"mein Text" and put this in the empty
Code:
getStringExtra("")
.
The getStringExtra is is getting the value you put in as text with the key name of "mein Text". So when you call getStringExtra it's saying we will get the value of a string by the name of "mein Text" to identify it and return it.
If this was blank it would not have a name to reference a value to.
Hope this helped i'm new to this as well and hope this is OK for you.
yesss
philnewby2012 said:
Where your
Code:
editText = (EditText) findViewById(R.id.editText);
is, you can delete this as you are referencing it in your button click method. Unless you are using it for anything else then this can be removed.
Also where
Code:
// resultText.setText(getIntent().getStringExtra(""));
is, this can be uncommented and at the end in brackets of
Code:
getStringExtra("")
is, you should put the extra string you stated as
Code:
intent2.putExtra("mein Text", text);
"mein Text" and put this in the empty
Code:
getStringExtra("")
.
The getStringExtra is is getting the value you put in as text with the key name of "mein Text". So when you call getStringExtra it's saying we will get the value of a string by the name of "mein Text" to identify it and return it.
If this was blank it would not have a name to reference a value to.
Hope this helped i'm new to this as well and hope this is OK for you.
Click to expand...
Click to collapse
thank youuuuu that was what i needed! :good:
is it because of many operations executing from main UI ?
In my app i just have a splash screen and a main activity. In the main thread i have three EditText boxes and a spinner with a string array. On clicking the Button, input from three EditText and spinner selection is posted to my mysql database. For the button click network operation, i used Volley since its east and i dont have to use AsyncTask which am not familiar with.
Apart from this, on entering the main UI .. app first check for network connectivity using ConnectivityManager class. After onClick app checks for empty/invalid imputs using TextUtils.
Now the problem is that when i run my app, its very slow and taking upto 65mb of RAM. IS something wrong with my code. Should i run something else as AsynTask ? Can someone check my code and refine it .. thank you
SplashActivity.java
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
public class SplashActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash);
int SPLASH_TIME_OUT = 5000;
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
Intent i = new Intent(SplashActivity.this, MainActivity.class);
startActivity(i);
finish();
}
}, SPLASH_TIME_OUT);
}
}
Click to expand...
Click to collapse
MainActivity.java
Code:
public class MainActivity extends Activity {
EditText name, phonenumber, address;
Button insert;
RequestQueue requestQueue;
Spinner spinner;
String insertUrl = "localhost";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Spinner s = (Spinner) findViewById(R.id.spinner);
s.setOnItemSelectedListener(new OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id)
{
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
/* CHECK INTERNET CONNECTION */
boolean mobileNwInfo;
ConnectivityManager conxMgr = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
try { mobileNwInfo = conxMgr.getActiveNetworkInfo().isConnected(); }
catch (NullPointerException e) { mobileNwInfo = false; }
if (!mobileNwInfo) {
Toast.makeText(this, "No Network, please check your connection. ", Toast.LENGTH_LONG).show();
}
/* CHECK INTERNET CONNECTION PROCEDURE DONE */
name = (EditText) findViewById(R.id.editText);
phonenumber= (EditText) findViewById(R.id.editText2);
address = (EditText) findViewById(R.id.editText3);
insert = (Button) findViewById(R.id.insert);
requestQueue = Volley.newRequestQueue(getApplicationContext());
spinner = (Spinner) findViewById(R.id.spinner);
insert.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
/* CHECK EMPTY STRING */
EditText txtUserName = (EditText) findViewById(R.id.editText);
EditText txtUserAddress = (EditText) findViewById(R.id.editText3);
EditText txtUserPhone = (EditText) findViewById(R.id.editText2);
String strUserName = name.getText().toString();
String strUserAddress = address.getText().toString();
String strUserPhone = phonenumber.getText().toString();
if(TextUtils.isEmpty(strUserName)) {
txtUserName.setError("You can't leave this empty.");
return;
}
if(TextUtils.isEmpty(strUserPhone)) {
txtUserPhone.setError("You can't leave this empty.");
return;
}
if(TextUtils.isEmpty(strUserPhone) || strUserPhone.length() < 10) {
txtUserPhone.setError("Enter a valid phone number.");
return;
}
if(TextUtils.isEmpty(strUserAddress)) {
txtUserAddress.setError("You can't leave this empty.");
return;
}
/* LOADING PROCESS DIALOG */
final ProgressDialog pd = new ProgressDialog(MainActivity.this);
pd.setMessage("Booking Service ....");
pd.show();
/* REQUEST RESPONSE/ERROR */
StringRequest request = new StringRequest(Request.Method.POST, insertUrl, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
pd.hide();
System.out.println(response);
name.setText("");
phonenumber.setText("");
address.setText("");
Toast.makeText(getApplicationContext(), "Service successfully booked !!", Toast.LENGTH_LONG).show();
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
pd.hide();
Toast.makeText(getApplicationContext(), "Error: Please try again later.", Toast.LENGTH_LONG).show();
}
}) {
@Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> parameters = new HashMap<>();
parameters.put("name", name.getText().toString());
parameters.put("phonenumber", phonenumber.getText().toString());
parameters.put("address", address.getText().toString());
parameters.put("service", spinner.getItemAtPosition(spinner.getSelectedItemPosition()).toString());
return parameters;
}
};
requestQueue.add(request);
}
});
}
}