First, Thank you very much for looking at this!
I've been handed an app someone wrote before Marshmallow. I've fixed the Theme and SSL issues that came with Nougat but I'm having a heck of a time with Write to External Storage Permission or something associated. Debug is lacking or I'm not using it properly. This app creates a file onto the device and adds the ssl cert and login info in a folder called My Documents.
When I open the app it say network timeout right away. That message is from LoginActivity.java . I click ok then I get the Android pop up asking to allow permissions. I allow it. After that I put in the username and password and click login. It instantly gives the network timeout message from LoginActivity.java. LoginActivity.java is the Main Activity. If I click ok it's back to the login screen. All permissions are in the Android Manifest as well.
Maybe it's not from permissions but it works fine in version 22. I've worked on this 12 hours today and thought if you guys could help that'd be great. I'm a network engineer dabbling in Java so please excuse my question if it's "ugly".
I tried to find a line by line debug like I've done with phonegap but wasn't successful.
My Apps Main Activity LoginActivity.java and associated activity is LoginScreen.java and shown below.
LoginActivity.java
public class LoginActivity extends Activity {
private String userName = "";
private static final int PERMS_REQUEST_CODE = 123;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.blackactivity);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
new SSLHandler().execute();
if(Variables.testing)
{
}
if (hasPermissions()){
// our app has permissions.
try {
attemptLogin();
} catch (Exception e) {
GUI.oneOptionDialog(this, e.toString(), "OK", false);
e.printStackTrace();
}
}
else {
//our app doesn't have permissions, So i m requesting permissions.
requestPerms();
}
}
//Begin Permission Methods
#SuppressLint("WrongConstant")
private boolean hasPermissions(){
int res = 0;
//string array of permissions,
String[] permissions = new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE};
for (String perms : permissions){
res = checkCallingOrSelfPermission(perms);
if (!(res == PackageManager.PERMISSION_GRANTED)){
return false;
}
}
return true;
}
private void requestPerms(){
String[] permissions = new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE};
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
requestPermissions(permissions,PERMS_REQUEST_CODE);
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
boolean allowed = true;
switch (requestCode){
case PERMS_REQUEST_CODE:
for (int res : grantResults){
// if user granted all permissions.
allowed = allowed && (res == PackageManager.PERMISSION_GRANTED);
}
break;
default:
// if user not granted permissions.
allowed = false;
break;
}
if (allowed){
//user granted all permissions we can perform our task.
try {
attemptLogin();
} catch (Exception e) {
GUI.oneOptionDialog(this, e.toString(), "OK", false);
e.printStackTrace();
}
}
else {
// we will give warning to user that they haven't granted permissions.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (shouldShowRequestPermissionRationale(Manifest.permission.WRITE_EXTERNAL_STORAGE)){
Toast.makeText(this, "Storage Permissions denied.", Toast.LENGTH_SHORT).show();
}
}
}
}
//End Permission Methods
private void attemptLogin() throws IOException {
String filepath = Variables.fileFolder + "/login.txt";
File tempFile = new File(filepath);
if (!tempFile.exists()) {
startActivity(new Intent(LoginActivity.this, LoginScreen.class));
finish();
}
String username = "";
String passwordHash = "";
String salt = "";
boolean fileExists = false;
BufferedReader reader = null;
FileInputStream fileInputStream = null;
try {
fileInputStream = new FileInputStream(new File(filepath));
InputStreamReader inputStreamReader = new InputStreamReader(
fileInputStream);
reader = new BufferedReader(inputStreamReader);
username = reader.readLine();
passwordHash = reader.readLine();
salt = reader.readLine();
reader.close();
userName = username;
fileInputStream.close();
} catch (Exception e) {
startActivity(new Intent(LoginActivity.this, LoginScreen.class));
finish();
}
fileExists = true;
if (fileExists) {
try {
LoginTask login = new LoginTask();
login.execute(username, passwordHash, salt);
} catch (Exception e) {
}
}
}
private class LoginTask extends AsyncTask<String, Void, Boolean> {
Boolean success = false;
Boolean timedOut = false;
ProgressDialog mProgressDialog;
#Override
protected void onPostExecute(Boolean result) {
try {
mProgressDialog.dismiss();
} catch (Exception e) {
}
if (timedOut) {
AlertDialog.Builder builder = new AlertDialog.Builder(
LoginActivity.this);
builder.setMessage("Network Timed Out").setTitle("Notice");
builder.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.dismiss();
startActivity(new Intent(LoginActivity.this,
LoginScreen.class));
finish();
}
});
AlertDialog dialog = builder.create();
dialog.show();
} else {
if (result) {
Variables.storeTechName(userName, LoginActivity.this);
Variables.assignTechName();
startActivity(new Intent(LoginActivity.this,
MainActivity.class));
finish();
} else {
startActivity(new Intent(LoginActivity.this,
LoginScreen.class));
finish();
}
}
}
#Override
protected void onPreExecute() {
mProgressDialog = ProgressDialog.show(LoginActivity.this,
"Loading...", "Logging you in...");
mProgressDialog.getWindow().setGravity(Gravity.BOTTOM);
}
#Override
protected Boolean doInBackground(String... params) {
try {
URL json = new URL(Variables.urlPrefix + "/Login.svc/input?a="
+ params[0] + "&b=" + params[1] + "&c=" + params[2]);
HttpsURLConnection jc = (HttpsURLConnection) json
.openConnection();
jc.setConnectTimeout(Variables.timeoutTimeLimit);
jc.setSSLSocketFactory(Variables.context.getSocketFactory());
InputStreamReader input = new InputStreamReader(
jc.getInputStream());
BufferedReader reader = new BufferedReader(input);
String line = reader.readLine();
JSONObject jsonResponse = new JSONObject(line);
success = jsonResponse.getBoolean("LoginMethodResult");
jc.disconnect();
reader.close();
} catch (Exception e) {
System.out.println(e.toString());
timedOut = true;
}
return success;
}
}
#Override
protected void onPause() {
super.onPause();
}
}
LoginScreen.java
public class LoginScreen extends Activity {
private String userName;
private static final int PERMS_REQUEST_CODE = 123;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.loginscreen);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
if (!SSLHandler.loaded) {
new SSLHandler().execute();
}
// Creates login and name files and attempts to log in
Button createButton = (Button) findViewById(R.id.createbutton);
createButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (((EditText) findViewById(R.id.usernamefield)).getText()
.toString().isEmpty()
|| ((EditText) findViewById(R.id.passwordfield))
.getText().toString().isEmpty()) {
GUI.oneOptionDialog(LoginScreen.this,
"Missing field entries", "OK", false);
} else {
createLoginFile();
((EditText) findViewById(R.id.usernamefield)).setText("");
((EditText) findViewById(R.id.passwordfield)).setText("");
attemptLogin();
}
}
});
}
#SuppressLint("WrongConstant")
private boolean hasPermissions(){
int res = 0;
//string array of permissions,
String[] permissions = new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE};
for (String perms : permissions){
res = checkCallingOrSelfPermission(perms);
if (!(res == PackageManager.PERMISSION_GRANTED)){
return false;
}
}
return true;
}
private void requestPerms(){
String[] permissions = new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE};
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
requestPermissions(permissions,PERMS_REQUEST_CODE);
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
boolean allowed = true;
switch (requestCode){
case PERMS_REQUEST_CODE:
for (int res : grantResults){
// if user granted all permissions.
allowed = allowed && (res == PackageManager.PERMISSION_GRANTED);
}
break;
default:
// if user not granted permissions.
allowed = false;
break;
}
if (allowed){
//user granted all permissions we can perform our task.
createFiles();
}
else {
// we will give warning to user that they haven't granted permissions.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (shouldShowRequestPermissionRationale(Manifest.permission.WRITE_EXTERNAL_STORAGE)){
Toast.makeText(this, "Storage Permissions denied.", Toast.LENGTH_SHORT).show();
}
}
}
}
private void createFiles() {
}
private void attemptLogin() {
String username = "";
String passwordHash = "";
String salt = "";
boolean fileExists = false;
try {
String filepath = Variables.fileFolder + "/login.txt";
FileInputStream fileInputStream = new FileInputStream(new File(
filepath));
InputStreamReader inputStreamReader = new InputStreamReader(
fileInputStream);
BufferedReader reader = new BufferedReader(inputStreamReader);
username = reader.readLine();
passwordHash = reader.readLine();
salt = reader.readLine();
reader.close();
userName = username;
fileInputStream.close();
fileExists = true;
}
catch (Exception e) {
GUI.oneOptionDialog(LoginScreen.this,
"Login file does not exist. Please enter login info.",
"OK", false);
}
if (fileExists) {
try {
LoginTask login = new LoginTask();
login.execute(username, passwordHash, salt);
} catch (Exception e) {
}
}
}
private class LoginTask extends AsyncTask<String, Void, Boolean> {
Boolean timedOut = false;
Boolean success = false;
ProgressDialog mProgressDialog;
#Override
protected void onPostExecute(Boolean result) {
try {
mProgressDialog.dismiss();
} catch (Exception e) {
}
if (timedOut) {
GUI.oneOptionDialog(LoginScreen.this, "Network Timed Out",
"OK", false);
} else {
if (result) {
Variables.storeTechName(userName, LoginScreen.this);
Variables.assignTechName();
startActivity(new Intent(LoginScreen.this,
MainActivity.class));
finish();
} else {
GUI.oneOptionDialog(LoginScreen.this,
"Login Failed. Please try again.", "OK", false);
}
}
}
#Override
protected void onPreExecute() {
mProgressDialog = ProgressDialog.show(LoginScreen.this,
"Loading...", "Logging you in...");
}
#Override
protected Boolean doInBackground(String... params) {
try {
URL json = new URL(Variables.urlPrefix + "/Login.svc/input?a="
+ params[0] + "&b=" + params[1] + "&c=" + params[2]);
HttpsURLConnection jc = (HttpsURLConnection) json
.openConnection();
jc.setConnectTimeout(Variables.timeoutTimeLimit);
jc.setSSLSocketFactory(Variables.context.getSocketFactory());
jc.setConnectTimeout(Variables.timeoutTimeLimit);
InputStreamReader input = new InputStreamReader(
jc.getInputStream());
BufferedReader reader = new BufferedReader(input);
String line = reader.readLine();
JSONObject jsonResponse = new JSONObject(line);
success = jsonResponse.getBoolean("LoginMethodResult");
jc.disconnect();
reader.close();
} catch (Exception e) {
timedOut = true;
}
return success;
}
}
private void createLoginFile() {
try {
File dir = new File(Variables.fileFolder);
if (!dir.isDirectory()) {
dir.mkdirs();
}
String filepath = Variables.fileFolder + "/Login.txt";
String username = ((EditText) findViewById(R.id.usernamefield))
.getText().toString();
String password = ((EditText) findViewById(R.id.passwordfield))
.getText().toString();
String salt = new RandomString(20).nextString();
String passwordHash = Variables.sha256(password + salt);
PrintWriter writer = new PrintWriter(filepath, "UTF-8");
writer.println(username);
writer.println(passwordHash);
writer.println(salt);
writer.close();
} catch (Exception e) {
GUI.oneOptionDialog(LoginScreen.this, e.toString(), "OK", false);
}
}
#Override
protected void onPause() {
super.onPause();
}
}
Related
When I open the activity, I request for the directory permission. Once the permission is allowed, I write the name and content of the file and then I press the save button. There is a confirmation dialog before saving the file. I choose YES there and then the following error appears.
2019-07-17 04:29:31.063 17879-17879/com.halimlab.catatanharian E/WindowManager: android.view.WindowLeaked: Activity com.halimlab.catatanharian.InsertAndViewActivity has leaked window DecorView#56fdc15[InsertAndViewActivity] that was originally added here
at android.view.ViewRootImpl.<init>(ViewRootImpl.java:538)
at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:346)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:94)
at android.app.Dialog.show(Dialog.java:329)
at androidx.appcompat.app.AlertDialog$Builder.show(AlertDialog.java:1007)
at com.halimlab.catatanharian.InsertAndViewActivity.konfirmasiSave(InsertAndViewActivity.java:191)
at com.halimlab.catatanharian.InsertAndViewActivity.onBackPressed(InsertAndViewActivity.java:197)
at com.halimlab.catatanharian.InsertAndViewActivity.buatDanUbah(InsertAndViewActivity.java:177)
at com.halimlab.catatanharian.InsertAndViewActivity$1.onClick(InsertAndViewActivity.java:188)
at androidx.appcompat.app.AlertController$ButtonHandler.handleMessage(AlertController.java:167)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6739)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:495)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:859)
Here is my code.
public class InsertAndViewActivity extends AppCompatActivity implements View.OnClickListener {
public static final int REQUEST_CODE_STORAGE = 100;
int eventID = 0;
EditText edtFileName, edtContent;
Button btnSimpan;
boolean isEditable = false;
String fileName = "";
String tempCatatan = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_insert_and_view);
// button back
ActionBar menu = getSupportActionBar();
menu.setDisplayShowHomeEnabled(true);
menu.setDisplayHomeAsUpEnabled(true);
// input
edtFileName = findViewById(R.id.editFilename);
edtContent = findViewById(R.id.editContent);
// button
btnSimpan = findViewById(R.id.btnSimpan);
btnSimpan.setOnClickListener(this);
Bundle extras = getIntent().getExtras();
if (extras != null) {
fileName = extras.getString("filename");
edtFileName.setText(fileName);
getSupportActionBar().setTitle("Ubah Catatan");
} else {
getSupportActionBar().setTitle("Tambah Catatan");
}
eventID = 1;
if (Build.VERSION.SDK_INT >= 23) {
if (periksaIzin()) {
bacaFile();
}
} else {
bacaFile();
}
}
#Override
public void onClick(View view) {
switch (view.getId()){
case R.id.btnSimpan :
eventID = 2;
if (!tempCatatan.equals(edtContent.getText().toString())) {
if (Build.VERSION.SDK_INT >= 23) {
konfirmasiSave();
}
} else {
konfirmasiSave();
}
break;
}
}
public boolean periksaIzin() {
if (Build.VERSION.SDK_INT >= 23) {
if (checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) == getPackageManager().PERMISSION_GRANTED) {
return true;
} else {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_CODE_STORAGE);
return false;
}
} else {
return true;
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case REQUEST_CODE_STORAGE :
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
if (eventID == 1) {
bacaFile();
} else {
konfirmasiSave();
}
}
break;
}
}
void bacaFile() {
String path = Environment.getExternalStorageDirectory().toString() + "/halimlab.catatan";
File file = new File(path, edtFileName.getText().toString());
if (file.exists()) {
StringBuilder text = new StringBuilder();
try {
BufferedReader br = new BufferedReader(new FileReader(file));
String line = br.readLine();
while (line != null) {
text.append(line);
line = br.readLine();
}
br.close();
} catch (Exception e) {
System.out.println("ERROR" + e.getMessage());
}
tempCatatan = text.toString();
edtContent.setText(text.toString());
}
}
void buatDanUbah() {
String state = Environment.getExternalStorageState();
if (!Environment.MEDIA_MOUNTED.equals(state)) {
return;
}
String path = Environment.getExternalStorageDirectory().toString() + "/halimlab.catatan";
File parent = new File(path);
if (parent.exists()) {
File file = new File(path, edtFileName.getText().toString());
FileOutputStream outputStream = null;
try {
file.createNewFile();
outputStream = new FileOutputStream(file);
OutputStreamWriter streamWriter = new OutputStreamWriter(outputStream);
streamWriter.append(edtContent.getText());
streamWriter.flush();
streamWriter.close();
streamWriter.flush();
streamWriter.close();
} catch (Exception e) {
e.printStackTrace();
}
} else {
parent.mkdir();
File file = new File(path, edtFileName.getText().toString());
FileOutputStream outputStream = null;
try {
file.createNewFile();
outputStream = new FileOutputStream(file, false);
outputStream.write(edtContent.getText().toString().getBytes());
outputStream.flush();
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
onBackPressed();
}
void konfirmasiSave () {
new AlertDialog.Builder(this)
.setTitle("Simpan Catatan")
.setMessage("Apakah anda akan menyimpan catatan ini ?")
.setIcon(android.R.drawable.ic_dialog_alert)
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
buatDanUbah();
}
})
.setNegativeButton(android.R.string.no, null).show();
}
#Override
public void onBackPressed() {
if (!tempCatatan.equals(edtContent.getText().toString())) {
konfirmasiSave();
}
super.onBackPressed();
}
#Override
public boolean onOptionsItemSelected(#NonNull MenuItem item) {
if (item.getItemId() == R.id.home) {
onBackPressed();
}
return super.onOptionsItemSelected(item);
}
}
I have the necessary permissions in my AndroidManifest.xml.
<uses-permission android:name = "android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name = "android.permission.READ_EXTERNAL_STORAGE"/>
You need to modify the onBackPressed function like the following.
#Override
public void onBackPressed() {
if (!tempCatatan.equals(edtContent.getText().toString()))
konfirmasiSave();
else super.onBackPressed(); // Do that in the else part.
}
Because in the konfirmasiSave function you are opening a dialog which is not being closed or any action is being taken upon it and hence you are calling the super.onBackPressed which is trying to return back to the previous activity and hence causing the window leak error.
And handle the value of the tempCatatan variable before exiting so that your onBackPressed function performs as expected.
I am new to asynchronous tasks and trying to create a login UI. When I make a request from the server with valid credentials, everything works fine. When the credentials are incorrect, I use a set of "if" statements to check what the error code of the response is and print the corresponding message. I also have such a message for the case that the response is empty. I can see from the part of the server that all the responses include status codes, even when the credentials are invalid. Furthermore I can see the status code by using checkpoints in my code. But when I try to extract the status code from a response I got for invalid credentials, the only "if" statement that works is the one checking if the response is equal to "". None of the conditions of the other "if" statements are fulfilled even when they should be. Here is my code:
public String GET(String u) {
HttpURLConnection httpURLConnection = null;
BufferedReader bufferedReader;
StringBuilder stringBuilder;
String line;
String jsonString = "";
try {
URL url = new URL(u);
httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("GET");
bufferedReader = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));
stringBuilder = new StringBuilder();
while ((line = bufferedReader.readLine()) != null) {
stringBuilder.append(line + '\n');
}
jsonString = stringBuilder.toString();
} catch (Exception e) {
e.printStackTrace();
} finally {
httpURLConnection.disconnect();
}
return jsonString;
}
public void ProcessResponse(String response) {
if(response!="") {
try {
json = new JSONObject(response);
} catch (JSONException e) {
e.printStackTrace();
}
try {
status = json.getInt("status_code");
if (status == 500) {
Toast.makeText(this, "Internal server error! Please repeat action!", Toast.LENGTH_SHORT).show();
} else if(status == 401) {
Toast.makeText(this, "Invalid credentials", Toast.LENGTH_SHORT).show();
} else if(status == 400) {
Toast.makeText(this, "Bad Request! Please repeat action!", Toast.LENGTH_SHORT).show();
} else if(status == 200) {
try {
SharedPreferences.Editor editor = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE).edit();
editor.putString("base_url", baseURL);
editor.putInt("store_id", json.getInt("store_id"));
editor.putInt("pin", json.getInt("pin_number"));
editor.putInt("delete_table",json.getInt("delele_table_id"));
editor.commit();
} catch (JSONException e) {
e.printStackTrace();
}
Intent intent = new Intent(getApplicationContext(), APICall.class);
intent.putExtra("Action","Main Menu");
startActivity(intent);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Toast.makeText(LoginActivity.this, "Problem encountered!", Toast.LENGTH_SHORT).show();
}
}
private class ServerCall extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
String url = params[0];
return GET(url);
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
ProcessResponse(s);
}
}
These functions are called in another part of the code with the execute function as usually done in AsyncTask.
Thank you in advance for your help people!
Edit: The function is called like this:
public class LoginActivity extends AppCompatActivity {
public static final String MY_PREFS_NAME = "Shared Preferences";
String url = "";
String baseURL = "";
int status = 0;
JSONObject json = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
Button login = (Button) findViewById(R.id.login_button);
CheckBox mode = (CheckBox) findViewById(R.id.login_development_mode);
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
EditText developerURL = (EditText) findViewById(R.id.base_url);
EditText store = (EditText) findViewById(R.id.store_id_field);
EditText pin = (EditText) findViewById(R.id.pin_field);
baseURL = developerURL.getText().toString();
url = baseURL + "/api/auth/check?store_id="+store.getText().toString()+
"&pin_number="+pin.getText().toString();
ServerCall loginCall = new ServerCall();
loginCall.execute(url);
}
});
/*more code, including the AsyncTask mentioned above*/
}
I found the answer to my problem. Thank you all for responding. I changed the GET and processResponse methods as follows:
public String GET(String u) {
HttpURLConnection httpURLConnection = null;
BufferedReader bufferedReader;
StringBuilder stringBuilder;
String line;
String jsonString = "";
int code = -1;
try {
URL url = new URL(u);
httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("GET");
code = httpURLConnection.getResponseCode();
bufferedReader = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));
stringBuilder = new StringBuilder();
while ((line = bufferedReader.readLine()) != null) {
stringBuilder.append(line + '\n');
}
jsonString = stringBuilder.toString();
} catch (Exception e) {
e.printStackTrace();
status = code;
return "";
} finally {
httpURLConnection.disconnect();
}
return jsonString;
}
public void ProcessResponse(String response) {
if (status == 500) {
Toast.makeText(this, "Internal server error! Please repeat action!", Toast.LENGTH_SHORT).show();
} else if(status == 401) {
Toast.makeText(this, "Invalid credentials", Toast.LENGTH_SHORT).show();
} else if(status == 400) {
Toast.makeText(this, "Bad Request! Please repeat action!", Toast.LENGTH_SHORT).show();
} else if(status == 200) {
if(response!="") {
try {
json = new JSONObject(response);
SharedPreferences.Editor editor = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE).edit();
editor.putString("base_url", baseURL);
editor.putInt("store_id", json.getInt("store_id"));
editor.putInt("cell_phone", json.getInt("cell_phone"));
editor.putInt("pin", json.getInt("pin_number"));
editor.putInt("delete_table", json.getInt("delele_table_id"));
editor.commit();
} catch (JSONException e) {
e.printStackTrace();
}
Intent intent = new Intent(getApplicationContext(), APICall.class);
intent.putExtra("Action","Main Menu");
startActivity(intent);
} else {
Toast.makeText(LoginActivity.this, "Problem encountered!", Toast.LENGTH_SHORT).show();
}
}
}
I am not sure if the way I used the httpURLConnection is the most efficient or if my code is just stupid, but it works, so if anyone has any suggestions to improve it, feel free! Thank you all again!
Quickly about what I am trying to do. I am creating a script that scans looks for certain Wi-Fi connection. If it finds it, returns to StartingActivity with String.
But how do I make it display Toast if it scanned all connections and didn't found the right one. Because right now, it just sits there and does nothing. And I have to explain user that it found nothing.
Button btnHit;
TextView txtJson;
String urlfinal;
String fssid;
Intent intent;
private static final String TAG = "My Activity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_find_connection);
btnHit = (Button) findViewById(R.id.request);
txtJson = (TextView) findViewById(R.id.results);
if (Build.VERSION.SDK_INT > 22) {
final String CoarseLocation = Manifest.permission.ACCESS_COARSE_LOCATION;
final String AccessWifi = Manifest.permission.ACCESS_WIFI_STATE;
final String ChangeWifi = Manifest.permission.CHANGE_WIFI_STATE;
if (checkSelfPermission(CoarseLocation) != PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION}, 123);
}
if (checkSelfPermission(AccessWifi) != PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[]{Manifest.permission.ACCESS_WIFI_STATE, Manifest.permission.ACCESS_WIFI_STATE}, 123);
}
if (checkSelfPermission(ChangeWifi) != PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[]{Manifest.permission.CHANGE_WIFI_STATE, Manifest.permission.CHANGE_WIFI_STATE}, 123);
}
}
LocationManager lman = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
boolean network_enabled = false;
try
{
network_enabled = lman.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
} catch (Exception ex) {}
if (!network_enabled)
{
startActivityForResult(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS), 0);
}
btnHit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final WifiManager mWifiManager = (WifiManager) getSystemService(WIFI_SERVICE);
mWifiManager.setWifiEnabled(true);
IntentFilter filter = new IntentFilter();
filter.addAction(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION);
registerReceiver(new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
List<ScanResult> results = mWifiManager.getScanResults();
final int Amount = results.size();
int num = 0;
while (num < Amount)
{
Log.v(TAG, "SSID = " + results.get(num).SSID);
num = num+1;
}
int dis = 0;
String res = "Results:\n\n\n";
while (dis < Amount)
{
res = res + results.get(dis).SSID + "\n\n";
new JsonTask().execute(results.get(dis).SSID);
dis = dis+1;
}
}
}, filter);
mWifiManager.startScan();
}
});
}
private class JsonTask extends AsyncTask<String, String, String> {
ProgressDialog pd;
protected void onPreExecute() {
super.onPreExecute();
pd = new ProgressDialog(FindConnection.this);
pd.setMessage("Please wait...");
pd.setCancelable(false);
pd.show();
}
protected String doInBackground(String... params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
fssid = params[0];
urlfinal = "http://myurl?ssid=" + fssid;
URL url = new URL(urlfinal);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line+"\n");
if (!line.equals("null"))
{
String NetworkSSID = fssid;
String NetworkPass = line;
WifiConfiguration config = new WifiConfiguration();
config.SSID = "\"" + NetworkSSID + "\"";
config.preSharedKey = "\"" + NetworkPass + "\"";
WifiManager wifiman = (WifiManager) getApplicationContext().getSystemService(WIFI_SERVICE);
wifiman.addNetwork(config);
List<WifiConfiguration> list = wifiman.getConfiguredNetworks();
for ( WifiConfiguration i : list )
{
if (i.SSID != null && i.SSID.equals("\"" + NetworkSSID + "\""))
{
wifiman.disconnect();
wifiman.enableNetwork(i.networkId, true);
wifiman.reconnect();
break;
}
Intent intent1 = new Intent(FindConnection.this, StartingPage.class);
intent1.putExtra("ssid_name", fssid);
startActivity(intent1);
}
}
}
return buffer.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if (pd.isShowing()){
pd.dismiss();
}
}
}
UPDATE:
My best guess how to do that is set a timer and if it sits there for 5 seconds then display a toast (that means it hasn't changed activity, so found no results). But it feel that it is not the best way to do it.
Show your toast after the following line, if results.size is zero (0).
final int Amount = results.size();
That is probably suffice. [I am not sure if you can throw toast from a broadcast receiver. I have barely worked with them.]
Cheers!
when i am doing offline login my app is crashing...and showing the error
Attempt to invoke virtual method 'java.lang.String org.json.JSONObject.getString(java.lang.String)' on a null object reference
In Online it is working fine no issues but in offline it is crashing not at all giving where the issue is please help me in this
public class MainActivity extends AppCompatActivity {
**// Initializing variables**
EditText login;
EditText password;
String statusRes;
String id;
String projectName;
String loginValue;
String stockPoint;
JSONObject myRespObject = null;
public static final String Passkey = "passKey";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setTitle("LOGIN");
setContentView(R.layout.login);
login = (EditText) findViewById(R.id.loginname);
password = (EditText) findViewById(R.id.Password);
final Button saveme = (Button) findViewById(R.id.save);
**SharedPreferences sharedpreferences = getSharedPreferences(AppConstants.MyPREFERENCES, Context.MODE_PRIVATE);
saveme.setOnClickListener(new Button.OnClickListener() {
public URL url;
public void onClick(android.view.View v) {
if (!CheckNetwork.isInternetAvailable(MainActivity.this){
if (!validate()) {
onLoginFailed();
return;
}
SharedPreferences prefs = getSharedPreferences(AppConstants.MyPREFERENCES, Context.MODE_PRIVATE);
String loginValue = prefs.getString(AppConstants.LOGIN_VALUE, "");
String Passkey = prefs.getString(AppConstants.PASS_KEY, "");
String Internet = prefs.getString("Internet", "false");
String projectName = prefs.getString(AppConstants.PROJECT_NAME, "");
String stockPoint = prefs.getString(String.valueOf(AppConstants.STOCK_POINT),"");
String id = prefs.getString(AppConstants.ID, "");
Intent profactivity = new Intent(MainActivity.this, View.class);
profactivity.putExtra("Internet", false);
profactivity.putExtra("loginValue", loginValue);
profactivity.putExtra("id", id);
profactivity.putExtra("projectName", projectName);
profactivity.putExtra("stockPoint", stockPoint);
startActivity(profactivity);
**Toast.makeText(MainActivity.this, "Offline Login ", Toast.LENGTH_SHORT).show();
finish();
}
****for the above code, here it is throughing the error**
try {
final String loginValue = URLEncoder.encode(login.getText().toString(), "UTF-8");
final String passValue = URLEncoder.encode(password.getText().toString(), "UTF-8");
try {
new Thread(new Runnable() {
**//Thread to stop network calls on the UI thread**
public void run() {
//Request the HTML
ArrayList<String> list = null;
try {
String loginValue = URLEncoder.encode(login.getText().toString(), "UTF-8");
String passValue = URLEncoder.encode(password.getText().toString(), "UTF-8");
String ROOT_URL = getResources().getString(R.string.ROOT_URL) + "/api/v1/user/signIn?loginName=" + loginValue + "&password=" + passValue;
Log.i("httpget", "################" + ROOT_URL);
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet(ROOT_URL);
HttpResponse response = client.execute(request);
if (response.getStatusLine().getStatusCode() == 200) {
String server_response = EntityUtils.toString(response.getEntity());
myRespObject = new JSONObject(server_response);
//Do something with the response
//Toast.makeText(getBaseContext(),server_response,Toast.LENGTH_LONG).show();
statusRes = myRespObject.getString("status");
JSONObject respObject = myRespObject.getJSONObject("response");
id = respObject.getString("_id");
AppConstants._ID = id;
projectName = respObject.getString("projectName");
Actors actor = new Actors();
list = new ArrayList<>();
JSONArray jsonArray = respObject.getJSONArray("stockPoint");
Intent i = getIntent();
Serializable subject = i.getSerializableExtra("stockPoint");
if (jsonArray != null) {
int len = jsonArray.length();
for (int k = 0; k < len; k++)
list.add(jsonArray.get(k).toString());
}
actor.setStockPoint(list);
AppConstants.STOCK_POINT = stockPoint;
stockPoint = respObject.getString("stockPoint");
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
final ArrayList<String> finalList = list;
runOnUiThread(new Runnable() {
#Override
public void run() {
try {
statusRes = myRespObject.getString("status");
} catch (JSONException e) {
e.printStackTrace();
}
if (statusRes.equalsIgnoreCase("success")) {
SharedPreferences sharedpreferences = getSharedPreferences(AppConstants.MyPREFERENCES, Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString(AppConstants.LOGIN_VALUE, loginValue);
editor.putString(AppConstants.PASS_KEY, passValue);
editor.putString("Internet", "true");
editor.putString(AppConstants.ID, id);
editor.putString(AppConstants.PROJECT_NAME, projectName);
editor.putString(String.valueOf(AppConstants.STOCK_POINT), String.valueOf(stockPoint));
editor.commit();
**//Here move to next screen or home screen**
Intent profactivity = new Intent(MainActivity.this, View.class); profactivity.putExtra("Internet", true); profactivity.putExtra("loginValue", loginValue); profactivity.putExtra("id", id);
profactivity.putExtra("projectName", projectName);
profactivity.putExtra("stockPoint", finalList);
startActivity(profactivity);
Toast.makeText(MainActivity.this, "Login Successfully", Toast.LENGTH_LONG).show();
finish();
} else if (statusRes.equalsIgnoreCase("failed")) {
if (!validate()) {
onLoginFailed();
return;
}
}
}
});
}
}).start();
//return data;
} catch (Exception e) {
Log.i("httpget", "################Error1 -->" + e.getStackTrace());
**Toast.makeText(getBaseContext(), "ERROR : " + e.getMessage(), Toast.LENGTH_LONG).show();**
}
} catch (UnsupportedEncodingException ex) {
finish();
}
}
});
}
public boolean validate() {
boolean valid = true;
String email = login.getText().toString();
String passwor = password.getText().toString();
if (email.isEmpty() || email.length() < 2 || email.length() > 10) {
login.setError("enter valid username");
valid = false;
} else {
login.setError("Invalid username");
}
if (passwor.isEmpty() || passwor.length() < 2 || passwor.length() > 10) {
password.setError("enter valid password");
valid = false;
} else {
password.setError("Invalid password");
}
return valid;
}
public void onLoginFailed() {
**Toast.makeText(getBaseContext(), "Invalid login", Toast.LENGTH_LONG).show();**
}
}
--------------------------------------------------------------------------------
The error that you have mentioned says you have error on following line.
projectName = respObject.getString("projectName");
"responseObject" is null, hence you are getting NullPointerException.
am developing an Android Application for Email System, and the application needs to connect server (written by my partner).
My cellphone use wifi generated by my PC, when I try to login,the server just reports the "Connection reset"error for a few times in 10 seconds.
Client Login IP:59.71.68.237 Server host:Iris Time:2015.06.13 at 09:04:36
java.net.SocketException:Connection reset
at java.net.SocketInputStream.read(SocketInputStream.java:209)
at java.net.SocketInputStream.read(SocketInputStream.java:141)
at sun.nio.cs.StreamDecoder.readBytes(StreamDecoder.java:284)
at sun.nio.cs.StreamDecoder.implRead(StreamDecoder.java:326)
at sun.nio.cs.StreamDecoder.read(StreamDecoder.java:178)
at java.io.InputSteamReader.read(InputStreamReader.java:184)
at java.io.BufferedReader.fill(BufferedReader.java:161)
at java.io.BufferedReader.readLine(BufferedReader.java:324)
at java.io.BufferedReader.readLine(BufferedReader.java:389)
at com.mailService.emsp.tempEMSP.run(tempEMSP.java:42)
at java.lang.Thread.run(Thread.java:745)
I debug in Android,and I find out that the code stops after executing
client = new Socket(ServerInfo.sockethost, ServerInfo.socketport);
and the server reports error just after that.
Here is the client code.
public class Login extends Activity {
private Intent intent = null;
private EditText account = null; //Account
private EditText passwpord = null; //password
private Button login = null; // login
private TextView register = null; // register
private String useraccount = null;
private String userpassword = null;
private Dialog m_Dialog = null; // dialog
private Socket client; //client socket
private BufferedReader reader;
private PrintWriter writer;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
intent = this.getIntent();
account = (EditText) this.findViewById(R.id.login_account);
passwpord = (EditText) this.findViewById(R.id.login_password);
login = (Button) this.findViewById(R.id.login_button);
register = (TextView) this.findViewById(R.id.login_register);
register.setClickable(true);
//login button event
login.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
useraccount = account.getText().toString();
userpassword = account.getText().toString();
//judge whether the account is null
if (Regex.isEmpty(useraccount)) {
Toast.makeText(getApplicationContext(), "Please fill in account!",
Toast.LENGTH_SHORT).show();
}
// judge whether the account meets email form
else if (Regex.isEmail(useraccount)) {
Toast.makeText(getApplicationContext(), "account form is wrong!",
Toast.LENGTH_SHORT).show();
}
// judge whether password is null
else if (Regex.isEmpty(userpassword)) {
Toast.makeText(getApplicationContext(), "Please fill in the password!",
Toast.LENGTH_SHORT).show();
} else {
System.out.println("Client:Connecting");
m_Dialog = ProgressDialog.show(Login.this, "Hint", "Login...",true);
// create a new thread
new Thread(new Runnable() {
int flag = 0;
int mark = 0;
// based on the custom protocol
#Override
public void run() {
try {
// create a new socket
System.out.println("new Socket('', 6666);");
//This is where the code stops
client = new Socket(ServerInfo.sockethost, ServerInfo.socketport);
System.out.println("Socket 'client' created.");
String command = null;
System.out.println("new reader.");
// IO reader and writer
reader = new BufferedReader(
new InputStreamReader(client.getInputStream()));
System.out.println("new writer.");
writer = new PrintWriter(client.getOutputStream(), true);
// Client:login
writer.println("login");
while ((command = reader.readLine()) != null) {
StringTokenizer stk = new StringTokenizer(command);
String cmd = stk.nextToken();
System.out.println("cmd:" + cmd);
if (cmd.equals("user")) {
writer.println(useraccount);
System.out
.println("writer.println('useraccount');");
} else if (cmd.equals("pass")) {
writer.println(userpassword);
System.out
.println("writer.println('userpassword');");
} else if (cmd.equals("inexist")) {
writer.println(useraccount);
System.out
.println("inexist, writer.println('username');");
} else if (cmd.equals("error")) {
writer.println(useraccount);
System.out
.println("error, writer.println('username');");
} else if (cmd.equals("loginok")) {
System.out.println("case 'loginok'");
mark = 1;
System.out.println("========mark = "
+ mark);
break;
}
}
System.out.println("Login succeed!,flag=0");
} catch (Exception e) {
flag = 1; // Login fail
e.printStackTrace();
} finally {
try {
if (client != null)
client.close();
} catch (IOException e) {
e.printStackTrace();
}
}
m_Handler.post(new Runnable() {
#Override
public void run() {
if (flag == 0) {
ServerInfo.username = useraccount;
ServerInfo.password = userpassword;
intent.setClass(Login.this,
MainActivity.class);
Bundle bundle = new Bundle();
bundle.putString("username",
useraccount);
bundle.putString("password",
userpassword);
intent.putExtras(bundle);
startActivity(intent);
Login.this.finish();
System.out
.println("Client: Login succeed!");
Toast.makeText(getApplicationContext(),
"Login succeed!!", Toast.LENGTH_SHORT)
.show();
} else {
Toast.makeText(getApplicationContext(),
"Login fail!", Toast.LENGTH_SHORT)
.show();
}
}
});
m_Dialog.dismiss();
}
}).start();
}
}
});
}
}
When I execute client code separately from the application, it just works fine!
What is the problem ? Do you have any suggestions ?