I have an app on Google Play that works on my phone when using it as a remote testing device but when I upload it to the Play Store and then download it onto my phone it wont work it fails to transmit any packets.
See code below, I dont know what the problem is i've been scratching my head all day perhaps a permissions issue?
package com.example.dale.whatismyip;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import java.io.BufferedReader;
import java.io.InputStreamReader;
/**
* Created by Dale on 22/01/2017.
*/
public class PingActivity extends AppCompatActivity
{
private EditText pingEdit;
private String pingVal;
private TextView finalResult;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.ping);
finalResult = (TextView) findViewById(R.id.result);
pingEdit = (EditText) findViewById(R.id.editText2);
final Button button = (Button) findViewById(R.id.button5);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
finalResult.setText("");
pingVal = pingEdit.getText().toString();
if(pingVal.contains(".") && pingVal.length() > 6)
{
PingTest runner = new PingTest();
runner.execute();
}
else
{
finalResult.setText("Invalid Address");
}
}
});
}
private class PingTest extends AsyncTask<String, String, String>
{
private String res;
#Override
protected String doInBackground(String... strings) {
try {
boolean sudo = false;
String cmd = "/system/bin/ping -c 4 -w 4 " + pingVal;
Process p;
if(!sudo)
p= Runtime.getRuntime().exec(cmd);
else{
p= Runtime.getRuntime().exec(new String[]{"su", "-c", cmd});
}
BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));
String s;
res = "";
while ((s = stdInput.readLine()) != null) {
// CODE TO DO - create an array and populate it
System.out.println(res += s + "\n");
}
p.destroy();
return res;
} catch (Exception e) {
e.printStackTrace();
}
return "";
}
#Override
protected void onPostExecute(String result) {
// execution of result of Long time consuming operation
// CODE TO DO - pass this method both an array of type string and a string
// then do a while loop through it whilst the array is populated and set the value of the textview to the strings
finalResult.setText(result);
}
}
}
Issue sorted.
The code itself was fine but the power saving feature on android stops the ping functionality as it disables background network usage.
Okay this is such a suggestion but are you testing your phone through a computer? is the phone connected through a usb to a computer?
and could you print a toast to see what's going on in doInBackground
I can't find anything wrong in your code.
Related
I'm working with Firebase's realtime database in order to make a recipe application in android studio. The code runs fine and nothing crashes, but every time it's supposed to send information to the database, it does not. I attempted to create a shell for it to put data into, and instead, I saw it erase it once it got past the part where it was supposed to send the data. I've done all the required imports, implementations and dependencies according to their documentation, as well as wrote the code according to it too, but it doesn't seem to work.
Firebase Realtime Database before I send data, plus rules screenshot:
Firebase RD before
Firebase RD rules
After it runs the logic to send the data, I see it go red and disappear, like it was deleted, and nothing is left behind.
Here is my HomeScreen.java code:
package com.capteamfour.recipeappdatabase;
import android.content.Intent;
import android.os.Bundle;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import androidx.appcompat.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;
public class HomeScreen extends AppCompatActivity {
final FirebaseDatabase mDatabase = FirebaseDatabase.getInstance();
DatabaseReference mDatabaseUsers = mDatabase.getReference("USERS");
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home_screen);
newUser(FirebaseAuth.getInstance().getCurrentUser().getDisplayName(),
FirebaseAuth.getInstance().getCurrentUser().getEmail());
String username = FirebaseAuth.getInstance().getCurrentUser().getDisplayName();
String email = FirebaseAuth.getInstance().getCurrentUser().getEmail();
TextView userWelcome = (TextView) findViewById(R.id.userWelcome);
FloatingActionButton addRecipe = (FloatingActionButton) findViewById(R.id.addRecipeButton);
ImageButton userProfile = (ImageButton) findViewById(R.id.userProfileButton);
// Welcomes the current user
userWelcome.setText("Welcome, " + username + "!");
// Creates a listener for the "add recipe" button; takes user to recipe form activity
addRecipe.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent toRecipeForm = new Intent(HomeScreen.this, recipeForm.class);
startActivity(toRecipeForm);
}
});
// Creates a listener for the "user Profile Button" button; takes user to profile activity
userProfile.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent ToProfile = new Intent(HomeScreen.this, Profile.class);
startActivity(ToProfile);
}
});
}
public void newUser(String name, String email)
{
userProfile user = new userProfile(name, email);
System.out.println("This is what I need to send: " + mDatabaseUsers.setValue(user));
mDatabaseUsers.setValue(user);
}
}
I declare a database instance and create a reference to the USERS path as global variables, and then made a function newUser(String name, String email) that creates an instance of a userProfile() class for me and is supposed to then send it to the database using the next line (the Sys.out was me trying to see what it was attempting to send if anything at all).
userProfile class code:
package com.capteamfour.recipeappdatabase;
import com.google.firebase.database.IgnoreExtraProperties;
import java.util.ArrayList;
import java.util.List;
#IgnoreExtraProperties
public class userProfile {
private String username;
private String email;
private List<Recipe> subRecipes = new ArrayList<>();
// Not yet implemented
private List<Recipe> favRecipes = new ArrayList<>();
private List<Recipe> savedRecipes = new ArrayList<>();
// A user profile will include their name, the recipes they've submitted, as well as recipes they've
// favorited or saved to their profile. Saved recipes are private to the user.
public userProfile() {
// Default constructor for DataSnapshot.getValue(userProfile.class) calls
}
public userProfile(String usernameIn, String emailIn)
{
this.username = username;
this.email = email;
}
public String getUsername () {
return this.username;
}
public String getEmail() {
return this.email;
}
/*
Each of these add functions will check the length of the given array and either
add to the end of it if there's already results, or just adds it on the empty array.
Example: array empty, then array[0] = recipe
array has values, then array[length + 1] = recipe
*/
public void addSubRecipe (Recipe recipe) {
int size = this.subRecipes.size();
if (size == 0) {
subRecipes.add(recipe);
}
else {
subRecipes.add(size+1, recipe);
}
}
public List<Recipe> getSubRecipes() {
return subRecipes.subList(0, (subRecipes.size()));
}
/*
These are commented out to prevent additional bugs and confusion while they're not implemented
public void addSavedRecipe (Recipe recipe) {
int size = this.savedRecipes.size();
if (size == 0) {
savedRecipes.add(recipe);
}
else {
savedRecipes.add(size + 1, recipe);
}
}
public List<Recipe> getSavedRecipes() {
return this.savedRecipes.subList(0, (subRecipes.size() + 1));
}
/*public void addFavRecipe (Recipe recipe) {
int size = this.favRecipes.size();
if (size == 0) {
favRecipes.add(recipe);
}
else {
favRecipes.add(size + 1, recipe);
}
}
public List<Recipe> getFavRecipes() {
return this.favRecipes.subList(0, (subRecipes.size() + 1));
}*/
}
In this class, I made sure to have an empty constructor with additional constructors and the usual get/set functions so that the database could work with it.
I appreciate any and all pointers that anyone could provide on how to fix this issue. This is for my college capstone course, and it's holding us up quite drastically for what appears to be no good reason. Thanks everyone.
Basically the code I have below does currently read from a text file, but what I want it to do is store a value so that I can use it later for a another function. So from the text file I would like to store the height (175) and weight (80) value. How would that be done?
Text File:
Name: ..........
Height: 175
Weight 80
MainActivity:
package com.example.readfromfiletest;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.io.IOException;
import java.io.InputStream;
public class MainActivity extends AppCompatActivity {
Button b_read;
TextView tv_text;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b_read = (Button) findViewById(R.id.b_read);
tv_text = (TextView) findViewById(R.id.tv_text);
b_read.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String text = "";
try {
InputStream is = getAssets().open("test.txt");
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
text = new String(buffer);
} catch (IOException ex) {
ex.printStackTrace();
}
tv_text.setText(text);
}
});
}
}
Judging from your comments, it sounds like you're asking how to properly read in the values into different variables rather than reading them into one String. I think the first thing you should do to achieve this is read the file in line by line with a BufferedReader. Then for each line you read in you can determine which variable to assign the value to. For instance, you could do this:
Button b_read;
TextView tv_text;
String name = "";
int height = 0;
int weight = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b_read = (Button) findViewById(R.id.b_read);
tv_text = (TextView) findViewById(R.id.tv_text);
b_read.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String text = "";
try {
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(getAssets().open("test.txt")));
String line;
while((line = bufferedReader.readLine()) != null){
text = text.concat(line + "\n");
String[] lineVals = line.split(":");
if(lineVals[0].equalsIgnoreCase("name")){
name = lineVals[1].trim();
} else if(lineVals[0].equalsIgnoreCase("height")){
height = Integer.parseInt(lineVals[1].trim());
} else if(lineVals[0].equalsIgnoreCase("weight")){
weight = Integer.parseInt(lineVals[1].trim());
}
}
} catch (IOException ex) {
ex.printStackTrace();
}
tv_text.setText(text);
}
});
}
The BufferedReader reads in one line at a time. For example just, "Height: 175"
The line is then split on the ":", returning a String[] with two values. Continuing with our Height example, the array looks something like this: ["Height", " 175"]
The if statements (could also be case statements) then determine whether we're dealing with the name, height or weight variable.
The value is then assigned to its appropriate variable. The trim() method is called during this assignment to remove the space after the colon. You could also circumvent this by performing the split() method on ": ".
You could also stick with your current method and do some String manipulation involving splitting, Regex, or some other method, but I am of the opinion that my proposed solution will be a bit easier to read/work with in the future.
I am relatively new to Java and working with the ArcGIS Runtime SDK for Android. I am making an app where the user selects the parcel id from spinner list. If the user clicks on a 'ZOOM' button the map should zoom to the parcel that was selected. Here is my code:
package gist8010.main;
import java.util.ArrayList;
import android.app.Activity;
import android.os.Bundle;
import android.os.StrictMode;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import com.esri.android.map.MapView;
import com.esri.android.map.ags.ArcGISDynamicMapServiceLayer;
import com.esri.android.map.ags.ArcGISTiledMapServiceLayer;
import com.esri.core.geometry.Envelope;
import com.esri.core.geometry.Point;
import com.esri.core.map.Feature;
import com.esri.core.map.FeatureResult;
import com.esri.core.tasks.query.QueryParameters;
import com.esri.core.tasks.query.QueryTask;
public class Spinner_WalkActivity extends Activity {
MapView mMapView;
Button mBtnZoom;
ArcGISDynamicMapServiceLayer mDynamicLayer;
Spinner mSpnParcels;
String mMapServiceURL = "http://indy14.athena.bcit.ca:8080/"
+ "esri_rest/services/gist_8010_test_ms/MapServer";
int mLotLayerID = 0;
String mLotLayerURL = mMapServiceURL + "/" + mLotLayerID;
String mLotNumColName = "PARCELS_ID";
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
/** Allow querying on main thread */
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new
StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
/** Create spinner and button */
setMapView();
this.mBtnZoom = (Button) findViewById(R.id.btnZoom);
mBtnZoom.setOnClickListener(new OnClickListener() {
/** Upon click of zoom button, invoke th zoomtoFeature Method */
public void onClick(View v) {
zoomToFeature(v);
}
});
this.mSpnParcels = (Spinner) findViewById(R.id.spnParcels);
/** Add Layer to map */
mDynamicLayer = new ArcGISDynamicMapServiceLayer(mMapServiceURL);
mMapView.addLayer(mDynamicLayer);
QueryParameters qryLotNums = new QueryParameters();
qryLotNums.setReturnGeometry(false);
qryLotNums.setOutFields(new String[] { mLotNumColName });
qryLotNums.setWhere(mLotNumColName + ">0");
com.esri.core.tasks.query.QueryTask qtask = new com.esri.core.tasks.query.QueryTask(
mLotLayerURL);
try {
FeatureResult fSet = qtask.execute(qryLotNums);
ArrayList<String> listOfLotsNums = new ArrayList<String>();
Feature tmpFeat;
for (Object featAsObj : fSet) {
tmpFeat = (Feature) featAsObj;
listOfLotsNums.add(tmpFeat.getAttributeValue(mLotNumColName)
.toString());
}
ArrayAdapter<String> adtTmp = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_dropdown_item,
listOfLotsNums);
mSpnParcels.setAdapter(adtTmp);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}// of catch
}
#Override
protected void onDestroy() {
super.onDestroy();
}
#Override
protected void onPause() {
super.onPause();
mMapView.pause();
}
#Override
protected void onResume() {
super.onResume();
mMapView.unpause();
}
// =============================================================================
// Zooms the map the the MBR of the feature selected in the spinner
// import android.view.View;
// =============================================================================
public void zoomToFeature(View v) {
QueryParameters zoomQuery = new QueryParameters();
zoomQuery.setReturnGeometry(true);
zoomQuery.setOutFields(new String[] { mLotNumColName });
zoomQuery.setWhere(mLotNumColName + "=" + mSpnParcels.getSelectedItem());
QueryTask qtask = new QueryTask(mLotLayerURL);
try {
FeatureResult fset = qtask.execute(zoomQuery);
Feature tmpFeat = (Feature) fset.iterator().next();
Envelope envelope = new Envelope();
envelope.queryEnvelope((Envelope) tmpFeat.getGeometry());
getMapView().setExtent(envelope);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// =============================================================================
// getter for the main map
// =============================================================================
private MapView getMapView() {
// =============================================================================
// if MapView is underlined in red, change the name to match your
// MapView
// =============================================================================
return mMapView;
}
// =============================================================================
// setter for the main map
// =============================================================================
private void setMapView() {
// ========================================================================
// if mapView is underlined in red then sync class-level var names
// if R.id.map is underlined in red ensure that you added the xml
// fragment
// such as "MapView Generic" to a layout
// ========================================================================
mMapView = (MapView) findViewById(R.id.map);
}
}
After attempting to debug, I think my issue is with the Envelope class. The queryEnvelope method accepts a Envelope argument. As you can see, I cast the geometry of the Feature tmpFeat from a geometry type into a Envelope type.
When I run the application on my phone I get an System.Err in my log Cat saying:
java.lang.ClassCastException: com.esri.core.geometry.Polygon cannnot be cast to com.esri.core.geometry.Envelope
Am I doing the casting incorrectly? I cannot think of another way of linking my Envelope instance with the geometry of the feature class i want to zoom to.
Envelop is a child class of com.esri.core.geometry.Geometry, not vice versa. I guess this is why you fail when do the cast.
https://developers.arcgis.com/android/api-reference/reference/com/esri/core/geometry/Envelope.html
As it to your question, I guess envelop is not necessary to zoom to a feature. MapView.zoomToResolution(Point centerPt, double res) or zoomTo(Point centerPt, float factor) may be a better choice. You may find these sample codes helpful:
https://developers.arcgis.com/android/sample-code/geocoding/
I'm working on an app that involved comparing to numbers inputted by the user via text box, but wen I put in any if statements the program crashes whenever they are called. Otherwise the program runs just fine without any crashes or errors.
package improvecredit.app.basic;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.text.Editable;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class ImprovrCreditBasicActivity extends Activity {
/** Called when the activity is first created. */
public int minCredScore = 300;
public int maxCredScore = 850;
public int inputScore;
public int idealScore;
public Editable inputString;
public Editable idealString;
public EditText user;
public EditText desired;
public TextView output;
public Button submit;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
user = (EditText) findViewById(R.id.user_text);
desired = (EditText) findViewById(R.id.desired_text);
output = (TextView) findViewById(R.id.output_text);
submit = (Button) findViewById(R.id.submit_button);
//submit.setOnClickListener(new View.OnClickListener());
submit.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//inputString = user.getText();
//idealString = desired.getText();
inputScore = Integer.getInteger(user.getText().toString());
idealScore = Integer.getInteger(desired.getText().toString());
if (inputScore >= 0 && idealScore >= 0){
if (inputScore < minCredScore || idealScore < minCredScore){
output.setText("Invalid Entries");
}
if (inputScore > maxCredScore || idealScore > maxCredScore){
output.setText("Invalid Entries");
}
if (inputScore > idealScore){
output.setText("Nice Credit Score!");
}
if (inputScore < idealScore){
output.setText("For more information on how to improve your credit score, please visit" + "/n" + "http://www.creditscoresandcredit.com/");
}
}
else{
output.setText("Please enter valid credit scores");
}
}
});
}
If someone can point out what may have been done wrong in the code I would really appreciate it.
On first glance, don't use Integer.getInteger(), use Integer.parseInt().
If that doesn't fix it, please include the crash log from the console so we can see exactly what exception is being raised.
I'm betting that there is a null value introduced. If you check for null before using the variables idealScore and inputScore in the If statement, it will avoid this error. Until you paste the error trace, we can only guess for you.
I am a total newbie when it comes to both java and android coding. However, I am trying to piece together a simple notepad widget and app. It's basically a widget which displays the note text in a textView and an activity which can be loaded by tapping the widget. In the activity I have an EditText and two buttons - one to save the note text and one to cancel and close the activity.
An example of note-text entered in the EditText could be:
Buy milk
Kiss girlfriend
Bother Snape
When I save my note data from the activity, it saves my note data to an internal storage file. It then updates the widget and here my note-text is shown WITH linebreaks. But if I then open my activity to edit the text it loads the note-text as a single line file and not a multiline file.
Do any of you guys have suggestions for what I could do to load my note-data as multiline text with linebreaks?
Here's my activity code:
package dk.mfoller.android.basicnote;
import android.app.Activity;
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.RemoteViews;
import android.widget.Toast;
import android.widget.EditText;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import java.io.*;
public class BasicNoteActivity extends Activity {
/** Called when the activity is first created. */
private Button saveBtn;
private Button cancelBtn;
private EditText inputTxt;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Defines objects
saveBtn = (Button) findViewById(R.id.basicNoteActivity_save);
cancelBtn = (Button) findViewById(R.id.basicNoteActivity_cancel);
inputTxt = (EditText) findViewById(R.id.basicNoteActivity_input);
// Calls a function to update/replace the displayed note text
readNoteData();
// Creates event handler for the save-button
saveBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Calls a function to write to a file
writeToFile();
// Updates the displayed text in the widget
String noteinput = inputTxt.getText().toString();
RemoteViews views = new RemoteViews("dk.mfoller.android.basicnote", R.drawable.main_widget);
views.setTextViewText(R.id.basicNoteWidget_notetext, noteinput);
// Updates the actual widget - NOTE: This updates ALL instances of the widget
ComponentName cn = new ComponentName(getBaseContext(), BasicNoteWidget.class);
AppWidgetManager.getInstance(getBaseContext()).updateAppWidget(cn, views);
}
});
// Creates event handler for the cancel-button
cancelBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
finish();
}
});
}
// A function to write to a file
protected void writeToFile() {
String FILENAME = "basicNote_data";
String noteinput = inputTxt.getText().toString();
try {
FileOutputStream fos = openFileOutput(FILENAME, MODE_PRIVATE);
//noteinput.replace("\\r", "\n");
fos.write(noteinput.getBytes());
fos.close();
// Displays a popup
Toast.makeText(this, "Note saved!", Toast.LENGTH_SHORT).show();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// A function to read from a file on load
protected void readNoteData() {
String FILENAME = "basicNote_data";
try {
FileInputStream fis = openFileInput(FILENAME);
InputStreamReader isr = new InputStreamReader(fis);
BufferedReader br = new BufferedReader(isr);
// How do I make this load as multiline text?!?!
String line = null;
String output = "";
while((line = br.readLine()) != null) {
output += line;
}
// Updates/replaces the displayed note text
if(output != "") {
inputTxt.setText(output);
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Thanks in advance! ..oh, and please be very specific. Like I said: I'm a total newbie :)
The readLine() call does not include the end-of-line characters.
Quickest solution is to change the read loop in readNoteData:
while((line = br.readLine()) != null) {
output += line + "\n";
}
You could also just read in the entire file and skip that step, but get this working first.
See the BufferedReader.readLine() docs for info.