EditText to String name to different class - java

Having a bit of problem as I would like on my application for the user to enter an IP address and for that IP entry to be used to connect to the other device. In these two classes, the IPEntry class is set up to read the IP through the EditText and get coverts it to a string. I then want it to be passed and used within my ClientUpload class. Obviously I had attempted to already solve this to no avail. When I use it with the following way it says it cannot find the IP so it isn't transferring. I also tried to get in within a method and call upon that but that didn't work either. Is there anyway to do this?
Thanks
IPEntry Class
public class IPEntry extends Activity {
Button Submit;
EditText IP;
TextView Thistext;
public String ipadd;
public Intent intent;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.ipentry);
Submit = (Button) findViewById(R.id.bIPSubmit);
Thistext = (TextView) findViewById(R.id.tvTextIP);
IP = (EditText) findViewById(R.id.edIPBar);
Submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
ipadd = IP.getText().toString();
Intent Trans = new Intent("wishift.mat.ANDROIDEXPLORER");
startActivity(Trans);
}
}
);
}}
Relevant Part of Client Upload Class
public class ClientUpload extends Thread{
IPEntry ipentry = new IPEntry();
public int UploadFile(File file) throws UnknownHostException, IOException
{
//loop
int serverPort = 6880;
// String ip = "192.168.1.73";
String ip = ipentry.ipadd;
Socket socket = new Socket(ip, serverPort);
As you can see I commented out the part which does work but I would very much not like to manually add the IP in code.

The issue here is that the IPEntry object created here: IPEntry ipentry = new IPEntry(); in ClientUpload is a new IPEntry object; it does not share the same value of ipadd. The default constructor will set it to null.
There are many ways to solve this; you can either add a constructor to ClientUpload with a String argument for the IP address and save it in an instance variable or add another argument to the uploadFile() method to accept the IP address.
You can also make the ipadd varible static, allowing it to be accessed across all IPEntry instances, although I do not recommend this as it is completely unnecessary and multiple IPEntry objects will require more (unnecessary) memory and overhead.

Related

How to get icc authentication?

I found some interesting methods in telephonyManager class like turning mobile data off/on but when trying to use them it obviously throws me security exception.("No carrier privilege"). I Googled it, but didn't find any helpful solution.
Because it's carrier privilege I thought it may be possible to get its permission by telephonyManager.getIccAuthentication(int appType, int authType, String data) but I'm having problems with input parameters because I can't figure out what should I pass in to make it work.
From documentation to the first parameter would pass TelephonyManager.APPTYPE_SIM or/and TelephonyManager.APPTYPE_USIM depending on if it has big meaning in using setDataEnabled(boolean).
If I would pass TelephonyManager.APPTYPE_SIM as a first argument I think I should passed TelephonyManager.AUTHTYPE_EAP_SIM as a second argument (correct me if I'm wrong) and vice versa, when TelephonyManager.APPTYPE_USIM as first so TelephonyManager.AUTHTYPE_EAP_AKA as second one.
And then there is the third argument. There must be encoded Base64 to string. I found in TelephonyProvider this line of code:
String base64Challenge = Base64.encodeToString(byteParam, Base64.NO_WRAP); where byteParam is an input byte from another method which is being preceding by thousands other methods. If I pass "" as third parameter to getIccAuthentication method I get again securityException (it's obviously, wrong param) but it throws me lack of getIccSimChallengeResponse. I'm afraid of it may be infinite loop of methods, but maybe someone has any idea or help me to break this through?
My sample code:
public class MainActivity extends AppCompatActivity {
private static final String TAG = MainActivity.class.getSimpleName();
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button = (Button) findViewById(R.id.buttonPanel);
button.setOnClickListener(new View.OnClickListener() {
#RequiresApi(api = Build.VERSION_CODES.O)
#Override
public void onClick(View view) {
try {
Process p = Runtime.getRuntime().exec("su");
tel();
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
#RequiresApi(api = Build.VERSION_CODES.O)
private void tel(){
// String base64Challenge = Base64.encodeToString(,
Base64.NO_WRAP);
TelephonyManager telephonyManager = (TelephonyManager)
getSystemService(Context.TELEPHONY_SERVICE);
boolean isCarrier = telephonyManager.hasCarrierPrivileges();
String authentication =
telephonyManager.getIccAuthentication(TelephonyManager.APPTYPE_SIM,
TelephonyManager.AUTHTYPE_EAP_SIM, "");
Log.v(TAG, authentication);
if (isCarrier) {
Log.v(TAG, "privs granted");
telephonyManager.setDataEnabled(false);
} else {
Log.v(TAG, "no privilegies");
}
}
}
From the docs:
Requires Permission: READ_PRIVILEGED_PHONE_STATE or that the calling
app has carrier privileges (see hasCarrierPrivileges()).
The first of those requires you to be installed as a privileged system app (requires root or owning system certificate). The second requires your UID to be the carrier's. Without that no combo of parameters will work.

Java android and json - variable confusion

I have an android app that is retrieving data from a mysql db via php.
It works fine, but i have a (simple) variable problem.
I want to create a variable inside MainActivity class.
Then inside MainActiviy class i have onCreate method - and inside that I have some json stuff that retrieves my data from mysql.
I now want to assign some mysql value to the variable i created in MainActivity class (it is assigned inside onResponse method from the json stuff), and then I simply want to use that variable and write it out on a textview, and I will do that in the bottom of the onCreate method.
But for some reason, it "forgets" the value I assigned to the variable, when I have to use it outside the onResponse method.
(if i set the textview text inside the onResponse method, it works fine).
public class MainActivity extends ActionBarActivity {
// I create the variable here
String someString;
TextView text;
RequestQueue reqq;
String showUrl = "http://www.someurl.com/get_data.php";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
text = (TextView) findViewById(R.id.textid);
reqq = Volley.newRequestQueue(getApplicationContext());
JsonObjectRequest jsonob = new JsonObjectRequest(Request.Method.POST,
showUrl, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
try {
JSONArray dataAr = response.getJSONArray("json_data");
for (int i = 0; i < dataAr.length(); i++) {
JSONObject dat = dataAr.getJSONObject(i);
// Here I want to assign some data from my mysql db to the variable
someString = dat.getString("aar");
// If I set the the textview to display value of someString HERE, it works!
// text.setText(someString);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
System.out.println(error.getMessage());
}
});
reqq.add(jsonob);
// HERE i want to display the value of the variable in the textview!
// - but it doesnt "remember" the value
text.setText(someString);
}
}
If I use static keyword on the someString variable, it remembers the value, but only the SECOND time i open the app!
I'm very new at this, and have tried google, and tried some stuff with a singleton class, but I just don't seem to understand this!
I would love it, if someone could link me some information to help me get this, AND give an example of how my code should be, so it will work!
THANKS! :D
This behavior is due to the fact that
text.setText(someString);
is executed immediately in the onCreate method, & by immediately I mean that it does not wait for any response from the Volley request (the Volley request that you set up before). In other words, you need to wait till you get a response before you set the text on to your TextView.
That's why it successfully sets your TextView's text from within the onResponse method.

Linked List not updating values

So I've debugged my program and have found that the part of my program is updating, whilst another isn't.
I have a method:
public void storeApplication(String name, String item){
Application app = new Application(name, item);
peopleAttending.add(app);
}
The debugger reports that an object is contained in the LinkedList (peopleAttending).
In another method:
public void populateListView() {
int noOfPeopleAttending = peopleAttending.size();
String noPeopleAttending = String.valueOf(noOfPeopleAttending);
Toast.makeText(GuestsAttending.this, noPeopleAttending, Toast.LENGTH_SHORT).show();
}
This method can be called after the previous one and states that there isn't an object within the LinkedList.
I've checked the object references just to make sure that they are pointing at the same reference and they are.
Any help would be greatly appreciated.
EDIT: Entire Class:
public class GuestsAttending extends Activity {
private LinkedList<Application> peopleAttending = new LinkedList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_guests_attending);
populateListView();
}
public void storeApplication(String name, String item){
Application app = new Application(name, item);
peopleAttending.add(app);
}
public void populateListView() {
// GuestsAdapter adapter = new GuestsAdapter(this, peopleAttending);
// ListView listView = (ListView) findViewById(R.id.listView);
// listView.setAdapter(adapter);
peopleAttending.size();
int noOfPeopleAttending = peopleAttending.size();
String noPeopleAttending = String.valueOf(noOfPeopleAttending);
Toast.makeText(GuestsAttending.this, noPeopleAttending, Toast.LENGTH_SHORT).show();
}
Second Edit:
Java Booking Screen Method:
public void saveBookingInfo(View view) {
GuestsAttending sendApplication = new GuestsAttending();
EditText applicantNameText = (EditText) findViewById(R.id.applicantNameTextField);
EditText itemToBurnText = (EditText) findViewById(R.id.itemToBurnTextField);
String appName = applicantNameText.getText().toString();
String appItemToBurn = itemToBurnText.getText().toString();
if (appItemToBurn.isEmpty() || appName.isEmpty()) {
Toast.makeText(BookingScreen.this, "Please fill in all fields.", Toast.LENGTH_SHORT).show();
}
else {
sendApplication.storeApplication(appName, appItemToBurn);
}
}
GuestsAttending Java Class: -- See Above.
Useful hint: It's really popular to set type of List as a List<> interface from java.util package instead of LinkedList<> itself.
Anyway, i am pretty sure that storeApplication method is not automatically triggered before onCreate method ran by Activity framework. Maybe your debugger is stopoing on it in different order (because of using threads or smth), but you should to log some invoke. Try to find it out.
I've found out what the problem is:
When I submit the booking information, it runs all the necessary methods. However, when the "storeApplication()" method has finished executing, the ArrayList 'empties' all the objects out.
I only noticed this when I used breakpoint and tried running the method twice, on the second time I entered booking details, the ArrayList stated it was empty.
I'm going to see if I can try and store the ArrayList in a more secure place.

Cannot make a static reference to a non-static method [duplicate]

This question already has answers here:
Java Error: Cannot make a static reference to the non-static method
(7 answers)
Closed 8 years ago.
I have this in my java code, when I try to compile my code I get an error. This happens when I try to get the value of the text in my textview into a var. I cannot understand this error because It works fine in the other method.
Why happens this and how can I fix it?
public class MainActivity extends Activity {
public EditText editText;
TextView textView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toast.makeText(MainActivity.this, "onCreate", Toast.LENGTH_LONG).show();
//setupMessageButton();
editText = (EditText) findViewById(R.id.editText1);
textView = (TextView)findViewById(R.id.tvIsConnected);
}
public void btnDisplayMessage(View view){
//HERE WORKS FINE
String missatge = editText.getText().toString();
}
public static String POST(String url){
InputStream inputStream = null;
String result = "";
//HERE CRASHES
String missatge = "red"//editText.getText().toString(); GIVES ERROR
String usuario = "foo";
............
WHY?
EDIT: Thanks for downvote my question, Yes, I searched for another similar questions and I've already tried with static method...then don't crash but the content of the var is null and don't work at all.
You can not access a variable non static from a static method...
Solutions:
Make editText static
Its not Logical that one static method access a variable non static, so you should change the logic there!
Greetings :)...

Rookie mistake:Trying to pass outgoing number to activity

I am retrieving the outgoing number from the broadcast receiver and trying to send it to the activity thru a method getNumber() however the value is coming out null. Im my code below In the activity class the String phonenumber is null
BroadcastReciever Class:
public class OutgoingBroadcastReceiver extends BroadcastReceiver {
String phonenumber = null;
#Override
public void onReceive(Context context, Intent intent) {
phonenumber = intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER);
if (intent.getAction().equals("android.intent.action.NEW_OUTGOING_CALL"))
{
Log.i("System out", "IN OUTGOING CALL......... :IF");
MyPhoneStateListener phoneListener = new MyPhoneStateListener(
context);
TelephonyManager telephony = (TelephonyManager) context
.getSystemService(Context.TELEPHONY_SERVICE);
telephony.listen(phoneListener,
PhoneStateListener.LISTEN_CALL_STATE);
} else {
Log.i("System out", "IN INCOMING CALL.........:else:receiver");
}
public String getNumber()
{
return phonenumber;
}
Activity Class:
public class OutgoingCallScreenDisplay extends Activity
{
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.outgoing_main);
OutgoingBroadcastReceiver outreciever = new OutgoingBroadcastReceiver();
String phonenumber= outreciever.getNumber();//this is coming out NULL needs to be the outgoing number
}
Phone no. is null because u r making a new instance of broadcastreceiver whose values are not initilized. You can receive a phone no. in "onReceive" ONLY ,from there u should start a new activity if u want to pass it further
See:
Firstly you shud either use a broadcast receiver or a phone state listener. In ur case if u r using a broadcast receiver then u simple need intent extra:EXTRA_PHONE_NUMBER
and permission : process outgoin call .That's it.....
Two things immediately come to mind:
The onReceive method needs to be called before you can get the phone number.
You are assigning the phone number to a local variable and not the instance member.
use putExtra if you want to pass data to an activity

Categories