Const.EXTRA_DATA error - android

I am new in SO, and also new in Android. I try to make some chat application and I want to use this code
ListView list = (ListView) findViewById(R.id.listUser);
list.setAdapter(new UserAdapter());
list.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
startActivity(new Intent(UserList.this, Chat.class).putExtra(Const.EXTRA_DATA, uList.get(pos).getUsername()));
}
});
But the problem, there is error for Const.EXTRA_DATA because it can not be resolved and also uList.get(pos) too, I use Android Studio. I got that code from video tutorial.

from the comments you understood that Const is a predefined class, unfortunately it is not, there is no such class available in android library.
so your code will be like
startActivity(new Intent(UserList.this, Chat.class).putExtra("EXTRA_DATA_KEY", uList.get(pos).getUsername()));
since the key has to be used in both activities (sending activities and receiving activity) usually defines in a separate Java file.

Hello dear you are using your code snippet like
Const.EXTRA_DATA
right?
--> as you told us you are new SO please check your are having
class named
Const and
having static string variable like
EXTRA_DATA
-> SO finaly your class will appear like
public class Const{
public static String EXTRA_DATA="EXTRA_DATA";
}

Related

How do I mock a class with expresso in android?

Hello I am struggling with a task that seems very simple. I need to write an expresso unit test but I need the activity to use a mocked class instead of the one it uses during the normal run.
the, the closest solution I saw was here:
Nullifying or overriding API calls made in an Activity under an Espresso test
But this requires getters and setters at the application level and only deals with constants.
Here is a simple example of want to do:
Activity:
public class MainActivity2 extends AppCompatActivity {
// how do I mock this without using any branches
// just have expresso replace with MainActivity2CustomClass with a mock?
private MainActivity2CustomClass mainActivity2CustomClass;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
mainActivity2CustomClass = new MainActivity2CustomClass();
mainActivity2CustomClass.foo();
}
}
the class I want to mock
// Need expresso to replace this class with a mock
public class MainActivity2CustomClass {
void foo() {
}
}
To clarify I need to do this with a large application with several classes. So using branches is NOT the solution I seek. For instance this will not work for my application
// I DO ***NOT** WANT THIS solution since it will explode in many branches in my application
Intent intent = new Intent(targetContext, PatientActivity.class);
intent.putExtra("istestrunning", 2);
// etc...
// Not acceptable solution for my problem, creates too many branches and messy code
if (getIntent().getIntExtra("istestrunning", 0) == 2) {
mainActivity2CustomClass = new MainActivity2CustomClass();
mainActivity2CustomClass.foo();
} else {
mainActivity2CustomClass2 = new MyMock();
mainActivity2CustomClass2.foo();
}
I want to know if it possible to have expresso simply replace that class at testing time. Can it be done?
Any help or leads is appreciated.
thank you.

Creating Object from other class

I have a settings screen where you can choose between, add and remove configurations for the app.
When adding a configuration, I create a new Instance of a inputBox Class (extending the settings activity class - where I stored the procedure for the standard android text input box) to query the name for the new configuration.
In the Onclick of this inputbox a procedure from the superClass (the settings-activity) is called to create a new configuration object.
This Procedure queries some things from the activity (e.g. selected spinner element) including the progress of a seekBar.
This is where I get a NPE:
java.lang.NullPointerException: Attempt to invoke virtual method'android.view.Window$Callback android.view.Window.getCallback()' on a null object reference
The same object creation procedure is also called on initialization of the app and works just fine.
I understand from the Error that the issue is that when calling the procedure from a child class the reference of the variables to the corrseponding elements of the screen is not set anymore - and therefore cannot be queried.
So the question:
How can I query values of activity elements, when the procedure is called from another class?
I know that the topic is quite broad, but I can't figure it out for a couple of days now
Thanks for your help in advance.
Here is a scheme of the problem:
public class Settings extends AppCompatActivity{
Context settingsContext = this;
private Spinner someSpinner;
//other elements
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
someSpinner = (Spinner) findViewById(R.id.someView);
//other elements
addNewConfig.setOnClickListener((v) --> {
inputBox inputBox = new inputBox("OK", "Cancel", settingsContext, "sourcePath",1,1);
newConfigName = inputBox.show();
});
public sSetting makeNewConfig(String name, String sourcePath, int dataFrom, int dataTo){
sSetting newConfig;
newConfig = new sSetting("NAME", someSpinner.getProgress()>0, ...);
return newConfig;
}
}
And the inputBox:
public final class inputBox extends Settings {
//someVars
inputBox(String buttonOk, String buttonCancel, Context setContext, String sourcePath, int dataFrom, int dataTo){
//variable setters
}
private String show() {
//show msgbox
//onclick ok
super.makeNewConfig(....);
}
For solving the problem I restructured my Project a little:
I removed the inputBox-Part, which, after some research considered for a too complicated solution for what I needed anyway.
However: I now added a editText to my Settings View.
Although I had to change my Settings view for this, it now looks better and it was ridiculously easy to edit the configuration name for the user.
I think in most cases that will do the trick. Adding Popup-Boxes just needs more error handling and makes the design more complicated
I hope this helps ;)
If you need the code for it it is available here:
GitHub - AIM

Handling Json data with tab fragments in android

I am new to android development. I am trying to access json data in android. I have two tabs with viewpager . First tab contains information about events and the second tab will have a custom listview having a list of students attending that event.
this is the link to my json -https://jsonblob.com/5695f83de4b01190df49255d
I am confused on how to access this data in each fragment. My first screen has a edittext where the user will enter the event id.
Here is the link of design
https://drive.google.com/file/d/0B5XX8x3YUUrqYWUxNGdyckVaQ00/view?usp=sharing
I have developed the interface . Can anyone please help me with implementing the functionality.
thank you.
#Lalit Pratap Singh's answer is correct.
And i post my way below:
That's the answer.
http://7xphy5.com1.z0.glb.clouddn.com/A28B70BF-31C1-48F4-9BF9-61DB197A864B.png
1.Correct your url according my comment. http://jsonblob.com/api/jsonBlob/5695f83de4b01190df49255d
2.Get the response use APIKitchen or search the url on the internet and then you will get the response like this. Copy all the content.
http://7xphy5.com1.z0.glb.clouddn.com/A015706D-59E9-4E6C-B855-30B1152D30B6.png
3.Use a plugin in Android Studio called GsonFormat. Paste the content to plugin and it will create a new Events.java for you.
4.Use Retrofit to get the RESTFul Data.
I didn't paste my code here. You can leave your e-mail and i'll send code and detail explanatioin to you.
Create Application class in your code.
public class MyApplication extends android.app.Application {
public static MyApplication mInstance;
public String jsonStr;
#Override
public void onCreate(){
super.onCreate();
mInstance = this;
}
public MyApplication getmInstance(){
return mInstance;
}
public void setJsonStr(String jsonStr){
this.jsonStr = jsonStr;
}
public String getJsonStr(){
return jsonStr;
}
}
Add application class in you manifest file
android:name=".MyApplication"
Fetch json data and set it to application class like from anywhere in you application
MyApplication.getmInstance().setJsonStr(jsonstr);//fetched json data from httpcall
Get all data from Runtime and do any operation on it
String jsonStr = MyApplication.getmInstance().getJsonStr();

ParseUI activity code is not working

I am trying to get ParseUI to work with my app.
I have imported the libs, sync with gradle and everything is workign fine. Till when I actually put the code for the activity to be initiated, I get error saying 'cannot resolve symbol build'.
public class Login_activity extends FragmentActivity //implements Validator.ValidationListener
{
ParseLoginBuilder builder = new ParseLoginBuilder(Login_activity.this);
Login_activity(builder.build(), 0);
Actual code that I am supposed to use according to Parse docs
ParseLoginBuilder builder = new ParseLoginBuilder(MyActivity.this);
startActivityForResult(builder.build(), 0);
EDIT:
This is the updated code
#Override
protected void onCreate(Bundle savedInstanceState) {
//
//super.onCreate(savedInstanceState);
ParseLoginBuilder builder = new ParseLoginBuilder(Login_activity.this);
startActivityForResult(builder.build(), 0);
}
This line
Login_activity(builder.build(), 0);
is not valid Java. Your are trying to call the name of the class as if it was a method. I am not sure what you are trying to do (invoke the constructor? - which would not make sense for an Activity), but this code is incorrect. If you meant to call startActivityForResult, then do so, instead of substituting startActivityForResult with your class name, because doing so makes no sense.
EDIT:
Furthermore, you are adding lines of code to be executed directly in the class body, as opposed to inside a method. In Java, a class body can only contain declarations (which may include statements as part of an assignment) or static blocks of code, all other code must be part of a method.
class MyClass {
... you can only have declarations and assignments here
public void someMethod() {
... actual code statements here
}
}

Simpler OnClickListener?

i am new and learning , i have checked many related posts but still my few following questions are unanswered...[Edited ]the language is java...
following is the way to handle the click on button but can any one explain
1, why i have to declare the anonymous class ,
2, how i know that i have to declare the anonymous class here or any where else could ?
3, why i cannot use simple the btn.setOnClickListener(); why i must have to call anonymous class here ... below line is simple to do the task ...!!
btn.setOnClickListener();
why to make two more lines of code ...? i.e
#override public void onClick (View v) {....}
======================
Button btnCount = (Button) findViewById(R.id.btnCountId);
btnCount.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) { ...... }
});
You are using a Java entity called an "interface".
View.setOnClickListener accepts an object of type "OnClickListener". So you first need to create an object of such a type.
The Object OnClickListener is indeed an interface with one function "onClick", so to create an object of that type you need to implement it (define all the functions in the interface) - in this case, only one.
OnClickListener myClickListener=new OnClickListener() {
#Override // override means you are implementing a function in the interface or a derived class
public void OnClick(View v) {
// the button has been pressed
}
};
and then you can assign it to a view:
myButton.setOnClickListener(myClickListener);
or to many views:
myButton1.setOnClickListener(myClickListener);
myButton2.setOnClickListener(myClickListener);
myButton3.setOnClickListener(myClickListener);
In Java you'll find objects use listener interfaces to communicate events.
Mind that more complex objects use interfaces that can have several methods instead of just one, that's when the simplification you see is not that handy.
Imagine an object "Girl" that has a method "flirt" that you can invoke to ask her for dinner. The Girl will take some time to decide, then communicate one of a lot possible answers with the same interface.
OnGirlFlirtListener myGirlFlirtListener=new OnGirlFlirtListener() {
#Override
public void onGirlSaidYes() {
// invite the girl to have dinner
}
#Override
public void onGirlSaidNo() {
// find another girl or hang with your mates instead
}
#Override
public void onGirlSaidMaybe() {
// ask her later
}
#Override
public void onParentsHateMe() {
// forget about that girl
}
}
Then you can do:
mGirl.flirt (myGirlFlirtListener);
And the code is indeed elegant: With one interface you control all the possible answers! It's the same for a lot of objects in java (and Android).
Instead of creating the listener as an object, and setting it, you can as well create it as an anonymous class if you won't reuse it, of course.
EDIT
How to create a generic clicklistener?
Sometimes, in the same dialog, you have 15 or 20 buttons that do more or less the same, and only differ in a detail. Although you can perfectly crete 20 clicklisteners, there's a cooler way taking advantage of View.setTag() function.
setTag allows you to store whatever object you want to any view. You use that do distinguish, inside a clicklistener, which button was pressed.
So imagine you have 5 buttons: Brian, Peter, Loise, Krasty and Sue:
mButtonPeter.setTag("Peter Griffin");
mButtonLouise.setTag("Louise Griffin");
mButtonBrian.setTag("Brian");
mButtonKrasty.setTag("Krasty");
mButtonSue.setTag("Sue");
OnClickListener personClickListener=new OnClickListener() {
#Override
public void OnClick(View buttonPressed) {
String person=(String)(buttonPressed.getTag());
// you pressed button "person"
Toast.makeText(buttonPressed.getContext(), "Hey, "+person+", how is it going!!", Toast.LENGTH_SHORT).show();
}
};
mButtonPeter.setOnClickListener(personClickListener);
mButtonLouise.setOnClickListener(personClickListener);
mButtonBrian.setOnClickListener(personClickListener);
mButtonKrasty.setOnClickListener(personClickListener);
mButtonSue.setOnClickListener(personClickListener);
Isn't it cool?
When you are "setting an onClickListener" what you are doing is telling: "when this button is clicked, execute this code".
The code to be executed is implemented in the provided annonymous function.
You can't simply do btn.setOnClickListener() without an argument because that would not provide the information regarding which behaviour to perform when the button is clicked.

Categories

Resources