I am uploading video to a localhost webpage. My code is using a Handler (the syntax of which is working in a different class for signup & login to the app.
However when I run the code in the emulator it creates the handler, run the next line, then skips over the code in the handler.post section. (I can see handler appears to be deprecated in the documentation but i'm too far down this road to change now).
Any suggestions would be very much appreciated. (I know there are probably other issues in the code and better ways to do what i'm trying to achieve, I'm just using this as a learning exercise).
Activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<Button
android:id="#+id/captureBtn"
android:layout_width="120dp"
android:layout_height="60dp"
android:layout_centerVertical="true"
android:layout_gravity="bottom"
android:text="Capture Video"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
/>
</RelativeLayout>
build.gradle
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<Button
android:id="#+id/captureBtn"
android:layout_width="120dp"
android:layout_height="60dp"
android:layout_centerVertical="true"
android:layout_gravity="bottom"
android:text="Capture Video"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
/>
</RelativeLayout>
MainActivity
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import android.Manifest;
import android.app.Activity;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
public class MainActivity extends AppCompatActivity {
// Storage Permissions
private static final int REQUEST_EXTERNAL_STORAGE = 1;
private static String[] PERMISSIONS_STORAGE = {
Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.WRITE_EXTERNAL_STORAGE
};
Button Upload;
private final String fileURI = "/storeage/emulated/0/DCIM/Camera/VID_20210424_141744.mp4";
private static final String serverUri = "http://192.168.0.116/racewatch/upload.php";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Upload = findViewById(R.id.captureBtn);
Upload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (ActivityCompat.checkSelfPermission(getApplicationContext(),
Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
Handler handler = new Handler();
System.out.println("Hi from here");
handler.post(new Runnable() {
#Override
public void run() {
// Start of upload thread
//Creating array for parameters
String[] field = new String[4];
field[0] = "username";
field[1] = "userid";
field[2] = "lat";
field[4] = "lon";
//Creating array for data
String[] data = new String[4];
data[0] = "patsky";
data[1] = "21";
data[2] = "53.6";
data[3] = "-6.1";
// instantiate a client - should be a singleton
OkHttpClient client = new OkHttpClient.Builder()
.connectTimeout(10, TimeUnit.SECONDS)
.readTimeout(10, TimeUnit.SECONDS)
.build();
// /storeage/emulated/0/DCIM/Camera/VID_20210424_141744.mp4
RequestBody requestBody = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart(field[0], data[0])
.addFormDataPart(field[1], data[1])
.addFormDataPart(field[2], data[2])
.addFormDataPart(field[3], data[3])
.addFormDataPart("file", "test.mp4", RequestBody.create(MediaType.parse("video/mp4"), new File(fileURI)))
.build();
Request request = new Request.Builder()
.url(serverUri)
.post(requestBody)
.build();
client.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(final Call call, final IOException e) {
//Toast.makeText(MainActivity.this, "Error in file upload", Toast.LENGTH_SHORT).show();
Log.e("file uuuupload", "exception", e);
}
#Override
public void onResponse(final Call call, final Response response) throws IOException {
String phpans = response.body().string();//reponse body can be only accessed once
//Toast.makeText(MainActivity.this, phpans, Toast.LENGTH_SHORT).show();
System.out.println("Error messssage" + phpans);
if (!response.isSuccessful()) {
//Toast.makeText(MainActivity.this, "File uploaded successfully", Toast.LENGTH_SHORT).show();
System.out.println("Error messaage" + phpans);
}
// Upload successful
}
});
}
});
} else {
ActivityCompat.requestPermissions(MainActivity.this, new String[]{
Manifest.permission.READ_EXTERNAL_STORAGE}, 44);
}
} // end of onClick
});
} // end of onCreate
}
AndroidManifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.uploadtoserverexample">
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:usesCleartextTraffic="true"
android:theme="#style/Theme.UploadToServerExample">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Related
I want to read notifications from other apps in android , but I am not able to do so. These are my implementations to achieve same.
This is my MainActivity.java
package com.example.demoapp;
import androidx.appcompat.app.AppCompatActivity;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.os.Bundle;
import android.text.Html;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
TableLayout tab;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tab = (TableLayout)findViewById(R.id.tab);
LocalBroadcastManager.getInstance(this).registerReceiver(onNotice, new IntentFilter("Msg"));
}
private BroadcastReceiver onNotice= new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String pack = intent.getStringExtra("package");
String title = intent.getStringExtra("title");
String text = intent.getStringExtra("text");
TableRow tr = new TableRow(getApplicationContext());
tr.setLayoutParams(new TableRow.LayoutParams( TableRow.LayoutParams.MATCH_PARENT, TableRow.LayoutParams.WRAP_CONTENT));
TextView textview = new TextView(getApplicationContext());
textview.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT, TableRow.LayoutParams.WRAP_CONTENT,1.0f));
textview.setTextSize(20);
textview.setTextColor(Color.parseColor("#0B0719"));
textview.setText(Html.fromHtml(pack +"<br><b>" + title + " : </b>" + text));
tr.addView(textview);
tab.addView(tr);
}
};
}
This is my NotificationService class
package com.example.demoapp;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.service.notification.NotificationListenerService;
import android.service.notification.StatusBarNotification;
import android.util.Log;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;
public class NotificationService extends NotificationListenerService {
Context context;
#Override
public void onCreate() {
super.onCreate();
context = getApplicationContext();
}
#Override
public void onNotificationPosted(StatusBarNotification sbn) {
String pack = sbn.getPackageName();
String ticker = sbn.getNotification().tickerText.toString();
Bundle extras = sbn.getNotification().extras;
String title = extras.getString("android.title");
String text = extras.getCharSequence("android.text").toString();
Log.i("Package",pack);
Log.i("Ticker",ticker);
Log.i("Title",title);
Log.i("Text",text);
Intent msgrcv = new Intent("Msg");
msgrcv.putExtra("package", pack);
msgrcv.putExtra("ticker", ticker);
msgrcv.putExtra("title", title);
msgrcv.putExtra("text", text);
LocalBroadcastManager.getInstance(context).sendBroadcast(msgrcv);
}
#Override
public void onNotificationRemoved(StatusBarNotification sbn) {
Log.i("Msg","Notification Removed");
}
}
This is my AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:dist="http://schemas.android.com/apk/distribution"
package="com.example.demoapp">
<dist:module dist:instant="true" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name="com.example.demoapp.NotificationService"
android:label="#string/app_name"
android:permission="android.permission.BIND_NOTIFICATION_LISTENER_SERVICE">
<intent-filter>
<action android:name="android.service.notification.NotificationListenerService" />
</intent-filter>
</service>
</application>
</manifest>
This is my activity.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent">
<TableLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/tab" />
</ScrollView>
</LinearLayout>
</androidx.constraintlayout.widget.ConstraintLayout>
I have tested app in Android 5 and above, it is not getting any notification details. I gave permission to the app for reading permissions in android while testing on Android 6 and above versions.
Suggest me where I am getting wrong.
I have created a small demo for you its working fine in Android API-18 and above devices.
Even you can
Read all incoming SMS
Read all incoming calls
Battery Low and other notifications too
This is screenshot for display notification of other application Picture1 Picture2
NotificationService.java
import android.app.Notification;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.service.notification.NotificationListenerService;
import android.service.notification.StatusBarNotification;
import android.util.Log;
import android.support.v4.content.LocalBroadcastManager;
import java.io.ByteArrayOutputStream;
public class NotificationService extends NotificationListenerService {
Context context;
#Override
public void onCreate() {
super.onCreate();
context = getApplicationContext();
}
#Override
public void onNotificationPosted(StatusBarNotification sbn) {
String pack = sbn.getPackageName();
String ticker ="";
if(sbn.getNotification().tickerText !=null) {
ticker = sbn.getNotification().tickerText.toString();
}
Bundle extras = sbn.getNotification().extras;
String title = extras.getString("android.title");
String text = extras.getCharSequence("android.text").toString();
int id1 = extras.getInt(Notification.EXTRA_SMALL_ICON);
Bitmap id = sbn.getNotification().largeIcon;
Log.i("Package",pack);
Log.i("Ticker",ticker);
Log.i("Title",title);
Log.i("Text",text);
Intent msgrcv = new Intent("Msg");
msgrcv.putExtra("package", pack);
msgrcv.putExtra("ticker", ticker);
msgrcv.putExtra("title", title);
msgrcv.putExtra("text", text);
if(id != null) {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
id.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
msgrcv.putExtra("icon",byteArray);
}
LocalBroadcastManager.getInstance(context).sendBroadcast(msgrcv);
}
#Override
public void onNotificationRemoved(StatusBarNotification sbn) {
Log.i("Msg","Notification Removed");
}
}
MainActivity.java
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.support.v4.content.LocalBroadcastManager;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ListView;
import java.util.ArrayList;
public class MainActivity extends Activity {
ListView list;
CustomListAdapter adapter;
ArrayList<Model> modelList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
modelList = new ArrayList<Model>();
adapter = new CustomListAdapter(getApplicationContext(), modelList);
list=(ListView)findViewById(R.id.list);
list.setAdapter(adapter);
LocalBroadcastManager.getInstance(this).registerReceiver(onNotice, new IntentFilter("Msg"));
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);//Menu Resource, Menu
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_settings:
Intent intent = new Intent(
"android.settings.ACTION_NOTIFICATION_LISTENER_SETTINGS");
startActivity(intent);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private BroadcastReceiver onNotice= new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
// String pack = intent.getStringExtra("package");
String title = intent.getStringExtra("title");
String text = intent.getStringExtra("text");
//int id = intent.getIntExtra("icon",0);
Context remotePackageContext = null;
try {
byte[] byteArray =intent.getByteArrayExtra("icon");
Bitmap bmp = null;
if(byteArray !=null) {
bmp = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);
}
Model model = new Model();
model.setName(title +" " +text);
model.setImage(bmp);
if(modelList !=null) {
modelList.add(model);
adapter.notifyDataSetChanged();
}else {
modelList = new ArrayList<Model>();
modelList.add(model);
adapter = new CustomListAdapter(getApplicationContext(), modelList);
list=(ListView)findViewById(R.id.list);
list.setAdapter(adapter);
}
} catch (Exception e) {
e.printStackTrace();
}
}
};
}
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="{relativePackage}.${activityClass}" >
<ListView
android:id="#+id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true" >
</ListView>
</RelativeLayout>
Androidmanifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.demoapp">
<uses-permission android:name="android.permission.RECEIVE_SMS"></uses-permission>
<uses-permission android:name="android.permission.READ_SMS" />
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme">
<activity
android:name="com.example.demoapp.MainActivity"
android:configChanges="keyboardHidden|orientation|screenSize"
android:label="#string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service
android:name="com.example.demoapp.NotificationService"
android:label="#string/app_name"
android:permission="android.permission.BIND_NOTIFICATION_LISTENER_SERVICE">
<intent-filter>
<action android:name="android.service.notification.NotificationListenerService" />
</intent-filter>
</service>
</application>
</manifest>
I'm following a retrofit tutorial https://futurestud.io/tutorials/retrofit-getting-started-and-android-client
The app compiles and runs but doesn't allow you to scroll beyond the first page. Any idea what I'm missing? Does this tutorial even have you show all the repos?
https://github.com/morenoh149/HarryLearnsAndroid/tree/master/HttpDemo
package com.harrymoreno.httpdemo;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ListView;
import android.widget.Toast;
import java.util.List;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
import com.harrymoreno.httpdemo.GitHubRepoAdapter;
public class MainActivity extends AppCompatActivity {
private ListView listView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.pagination_list);
Retrofit.Builder builder = new Retrofit.Builder()
.baseUrl("https://api.github.com/")
.addConverterFactory(GsonConverterFactory.create());
Retrofit retrofit = builder.build();
GithubClient client = retrofit.create(GithubClient.class);
Call<List<GithubRepo>> call = client.reposForUser("morenoh149");
call.enqueue(new Callback<List<GithubRepo>>() {
#Override
public void onResponse(Call<List<GithubRepo>> call, Response<List<GithubRepo>> response) {
List<GithubRepo> repos = response.body();
listView.setAdapter(new GitHubRepoAdapter(MainActivity.this, repos));
}
#Override
public void onFailure(Call<List<GithubRepo>> call, Throwable t) {
Toast.makeText(MainActivity.this, "error :(", Toast.LENGTH_SHORT).show();
}
});
}
}
and activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<ListView
android:id="#+id/pagination_list"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:layout_constraintTop_toTopOf="parent"
tools:layout_editor_absoluteX="0dp" />
</RelativeLayout>
use scrollview then listview in xml file
I'm stucked with this problem.
In my app I use SharedPrefManager as a singleton class, in order to keep some "session" information. In this simple example app I just save the user's name and a boolean that indicates whether or not the user is logged in to skip the login screen if already logged, or to show it if not.
When starting the app, after the splashscreen, the LoginActivity is started.
At this point, if the user has already logged in before (without logging out later, that means the boolean value of isuseradded SharedPreferences variable is true), the user is redirected to the MainActivity, otherwise he sees the login form, where he can insert username and password and make a REST API request to a remote server.
If the login is correct, the MainActivity starts and simply shows the name of the user, taken from the response JSON obtained by the remote login REST API call.
Now, here is my problem: I want to implement a simple logout feature that deletes (or changes, as in this test app) all the information stored by SharedPreferences and takes the user back to the LoginActivity.
But when I click logout, the values for SharedPreferences are updated only in MainActivity, while in LoginActivity they remain the same as before, so when the user is redirected to LoginActivity, the isusedadded shared preference is still true, and the user is redirected back to MainActivity.
But SharedPrefManager class is a singleton, so its values should be the same in every part of the app, because only one instance of it exists, so why do I have this behavior?
You can test the app by downloading the full app code here and using these credentials for login:
Username: 52346
Password: 32fjueM1 (case sensitive)
Here follows my code.
App.java:
package mypackage.sharedprefapp;
import android.app.Application;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.Volley;
public class App extends Application
{
private RequestQueue mRequestQueue;
private static App mInstance;
#Override
public void onCreate()
{
super.onCreate();
mInstance = this;
}
public static synchronized App getInstance()
{
return mInstance;
}
// This method returns the queue containing GET/POST requests
public RequestQueue getRequestQueue()
{
if(mRequestQueue == null)
{
mRequestQueue = Volley.newRequestQueue(getApplicationContext());
}
return mRequestQueue;
}
// This method adds a GET/POST request to the queue of requests
public <T> void addToRequestQueue(Request<T> req)
{
getRequestQueue().add(req);
}
}
SplashActivity.java
package mypackage.sharedprefapp;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
public class SplashActivity extends AppCompatActivity
{
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
Intent intent = new Intent(this, LoginActivity.class);
startActivity(intent);
finish();
}
}
LoginActivity.java
package mypackage.sharedprefapp;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
public class LoginActivity extends AppCompatActivity
{
private static final String TAG = "LoginActivity";
Button loginButton;
EditText userIDInput, passwordInput;
TextView loginErrorMsg, title;
LinearLayout bgLayout;
SharedPrefManager sharedPrefManager;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
sharedPrefManager = SharedPrefManager.getInstance(this);
Log.i("HERE", "LoginActivity onCreate: "+sharedPrefManager.isUserAdded());
}
#Override
protected void onResume()
{
super.onResume();
sharedPrefManager = SharedPrefManager.getInstance(this);
Log.i("HERE", "LoginActivity onResume: "+sharedPrefManager.getUserName());
// if the user is already logged in
if(sharedPrefManager.isUserAdded())
{
Log.i(TAG, "User is logged in");
// if the device is connected to the internet
if(Utils.isDeviceOnline(this))
{
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
finish();
}
// if the device is offline
else
{
Log.i(TAG, "Internet connection is not available");
}
}
// if the user is not logged in
else
{
Log.i(TAG, "User is NOT logged in");
setContentView(R.layout.activity_login);
title = (TextView) findViewById(R.id.title);
loginErrorMsg = (TextView) findViewById(R.id.login_errorText);
userIDInput = (EditText) findViewById(R.id.login_id_paziente);
passwordInput = (EditText) findViewById(R.id.login_password);
loginButton = (Button) findViewById(R.id.login_submitButton);
bgLayout = (LinearLayout) findViewById(R.id.login_parentLayout);
// Bind a custom click listener to the login button
loginButton.setOnClickListener(new LoginButtonClickListener(this));
// Bind a custom click listener to the background layout
// so that the soft keyboard is dismissed when clicking on the background
bgLayout.setOnClickListener(new LoginBackgroundClickListener());
}
}
}
LoginButtonClickListener.java
package mypackage.sharedprefapp;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Map;
public class LoginButtonClickListener implements View.OnClickListener
{
private Context context;
private SharedPrefManager sharedPrefManager;
public LoginButtonClickListener(Context c)
{
this.context = c;
}
#Override
public void onClick(View v)
{
sharedPrefManager = SharedPrefManager.getInstance(context);
// if internet connection is available
if(Utils.isDeviceOnline(context))
{
// Verify login credentials from DB
doLogin();
}
else {}
}
// check login data with REST API
private void doLogin()
{
final String paziente_id = ((EditText)((Activity)context).findViewById(R.id.login_id_paziente)).getText().toString();
final String paziente_password = ((EditText)((Activity)context).findViewById(R.id.login_password)).getText().toString();
StringRequest stringRequest = new StringRequest
(
Request.Method.POST,
"http://www.stefanopace.net/iCAREServer/api/v1/index.php/login",
new Response.Listener<String>()
{
#Override
public void onResponse(String s)
{
try
{
JSONObject obj = new JSONObject(s);
if(!obj.getBoolean("error"))
{
String name = obj.getString("nome");
sharedPrefManager.addUser(name);
Intent intent = new Intent(context, MainActivity.class);
context.startActivity(intent);
}
else
{
Toast.makeText(context, "Error on JSON response", Toast.LENGTH_LONG).show();
}
}
catch(JSONException e)
{
e.printStackTrace();
}
}
},
new Response.ErrorListener()
{
#Override
public void onErrorResponse(VolleyError volleyError)
{
Toast.makeText(context, volleyError.getMessage(), Toast.LENGTH_LONG).show();
}
})
{
#Override
protected Map<String, String> getParams() throws AuthFailureError
{
Map<String, String> params = new HashMap<>();
params.put("id_paziente", paziente_id);
params.put("password", paziente_password);
return params;
}
};
App.getInstance().addToRequestQueue(stringRequest);
}
}
LoginBackgroundClickListener.java
package mypackage.sharedprefapp;
import android.view.View;
public class LoginBackgroundClickListener implements View.OnClickListener
{
#Override
public void onClick(View v)
{
Utils.hideSoftKeyboard(v);
}
}
MainActivity.java
package mypackage.sharedprefapp;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity
{
private static final String TAG = "MainActivity";
TextView personName;
SharedPrefManager sharedPrefManager;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
sharedPrefManager = SharedPrefManager.getInstance(this);
setContentView(R.layout.activity_main);
personName = (TextView) findViewById(R.id.person_name);
Log.i(TAG, "Value: "+sharedPrefManager.isUserAdded());
personName.setText(sharedPrefManager.getUserName());
}
#Override
protected void onResume()
{
super.onResume();
sharedPrefManager = SharedPrefManager.getInstance(this);
Log.w("MainActivity", "onResume");
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.mainmenu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
switch(item.getItemId())
{
// Logout button has been pressed
case R.id.logout_action:
{
Log.i("Logout pressed", "Logout button has been pressed!");
final AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
alertDialogBuilder.setMessage("Are you sure you want to logout?");
alertDialogBuilder.setPositiveButton
(
"Yes",
new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface arg0, int arg1)
{
boolean success = sharedPrefManager.removeDataFromSharedPreference();
// if the operation is OK
if(success)
{
// go to the login activity
Intent intent = new Intent(MainActivity.this, LoginActivity.class);
startActivity(intent);
finish();
}
else
{
Toast.makeText(getApplicationContext(), "Error during logout", Toast.LENGTH_LONG).show();
}
}
}
);
alertDialogBuilder.setNegativeButton
(
"No",
new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface arg0, int arg1)
{}
}
);
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
return true;
}
}
return super.onOptionsItemSelected(item);
}
}
SharedPrefManager.java
package mypackage.sharedprefapp;
import android.content.Context;
import android.content.SharedPreferences;
public final class SharedPrefManager
{
private static final String TAG = "SharedPrefManager";
private SharedPreferences sharedPreferences;
private SharedPreferences.Editor editor;
private static SharedPrefManager mInstance;
private static final String SHARED_PREF = "sharedprefs";
private static final String KEY_IS_USER_ADDED = "isuseradded";
public static final String KEY_USER_NAME = "username";
private SharedPrefManager(Context context)
{
sharedPreferences = context.getSharedPreferences(SHARED_PREF, Context.MODE_PRIVATE);
editor = sharedPreferences.edit();
sharedPreferences.registerOnSharedPreferenceChangeListener(new LocalSharedPreferencesChangeListener());
}
public static SharedPrefManager getInstance(Context context)
{
if(mInstance == null)
{
mInstance = new SharedPrefManager(context);
}
return mInstance;
}
// add an user to the shared preferences
public boolean addUser(String name)
{
editor.putString(KEY_USER_NAME, name);
editor.putBoolean(KEY_IS_USER_ADDED, true);
return editor.commit();
}
public boolean removeDataFromSharedPreference()
{
editor.putString(KEY_USER_NAME, "HELLO");
editor.putBoolean(KEY_IS_USER_ADDED, false);
return editor.commit();
}
public String getUserName()
{
return sharedPreferences.getString(KEY_USER_NAME, "");
}
public boolean isUserAdded()
{
return sharedPreferences.getBoolean(KEY_IS_USER_ADDED, false);
}
}
Utils.java
package mypackage.sharedprefapp;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.support.v7.app.AlertDialog;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
public class Utils
{
public static void hideSoftKeyboard(View view)
{
InputMethodManager inputMethodManager = (InputMethodManager) view.getContext().getSystemService(Activity.INPUT_METHOD_SERVICE);
inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
// This method checks if the device is connected to the Internet
public static boolean isDeviceOnline(final Context context)
{
final ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if(connectivityManager != null)
{
final NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
boolean isOnline = (networkInfo != null && networkInfo.isConnectedOrConnecting());
if(!isOnline)
{
AlertDialog.Builder alertDialog = new AlertDialog.Builder(context);
alertDialog.setCancelable(false);
alertDialog.setTitle("Error");
alertDialog.setMessage("Internet is not available");
alertDialog.setPositiveButton("Try again", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which)
{
// Reload the Activity
Intent intent = ((Activity) context).getIntent();
((Activity) context).finish();
context.startActivity(intent);
}
});
alertDialog.show();
}
return isOnline;
}
return false;
}
}
LocalSharedPreferencesChangeListener
package mypackage.sharedprefapp;
import android.content.SharedPreferences;
import android.util.Log;
public class LocalSharedPreferencesChangeListener implements SharedPreferences.OnSharedPreferenceChangeListener
{
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key)
{
Log.i("HERE", key);
}
}
activity_login.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context=".LoginActivity"
android:padding="0dp">
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/scrollView"
android:layout_gravity="center_horizontal">
<LinearLayout
android:id="#+id/login_parentLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:clickable="true">
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#mipmap/ic_launcher"
android:layout_gravity="center_horizontal"
android:layout_marginTop="50dp"
android:layout_marginBottom="30dp" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/app_name"
android:layout_gravity="center_horizontal"
android:gravity="center_horizontal"
android:layout_marginBottom="30dp"
android:singleLine="false"
android:padding="5dp"
android:textSize="30sp" />
<EditText
android:id="#+id/login_id_paziente"
android:layout_width="match_parent"
android:layout_height="40dp"
android:inputType="number"
android:ems="10"
android:hint="Username"
android:textColor="#android:color/black"
android:textColorHint="#android:color/darker_gray"
android:singleLine="true"
android:minLines="1"
android:gravity="center_horizontal"
android:layout_marginLeft="50dp"
android:layout_marginRight="50dp"
android:focusableInTouchMode="true"
android:focusable="true" />
<EditText
android:id="#+id/login_password"
android:layout_width="match_parent"
android:layout_height="40dp"
android:hint="Password"
android:textColorHint="#android:color/darker_gray"
android:inputType="textPassword"
android:ems="10"
android:textColor="#android:color/black"
android:maxLines="1"
android:singleLine="true"
android:layout_marginTop="20dp"
android:gravity="center_horizontal"
android:layout_marginLeft="50dp"
android:layout_marginRight="50dp"
android:focusableInTouchMode="true"
android:focusable="true" />
<TextView
android:id="#+id/login_errorText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Login error"
android:textColor="#android:color/holo_red_dark"
android:layout_gravity="center_horizontal"
android:gravity="center_horizontal"
android:singleLine="false"
android:padding="5dp"
android:textSize="20sp"
android:layout_margin="10dp"
android:visibility="invisible" />
<Button
android:id="#+id/login_submitButton"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Login"
android:textSize="20sp"
android:layout_marginLeft="50dp"
android:layout_marginRight="50dp" />
</LinearLayout>
</ScrollView>
</LinearLayout>
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="mypackage.sharedprefapp.MainActivity">
<TextView
android:id="#+id/person_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
android:textSize="25sp"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />
</RelativeLayout>
splashscreen.xml (in drawable resources folder)
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="#android:color/holo_green_dark"/>
<item>
<bitmap
android:gravity="center"
android:src="#mipmap/ic_launcher"/>
</item>
</layer-list>
mainmenu.xml (in res/menu resource folder)
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item android:id="#+id/logout_action"
android:title="Logout"
app:showAsAction="always" />
</menu>
styles.xml
<resources>
...
<style name="SplashTheme" parent="Theme.AppCompat.NoActionBar">
<item name="android:windowBackground">#drawable/splashscreen</item>
</style>
</resources>
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="mypackage.sharedprefapp">
<!-- Needs internet to connect to Google Services -->
<uses-permission android:name="android.permission.INTERNET" />
<!-- Permission to check internet connection state -->
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<application
android:name=".App"
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity
android:name=".SplashActivity"
android:label="#string/app_name"
android:screenOrientation="portrait"
android:theme="#style/AppTheme">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".MainActivity"
android:label="#string/app_name"
android:screenOrientation="portrait"
android:theme="#style/AppTheme" />
<activity
android:name=".LoginActivity"
android:label="#string/app_name"
android:process=":other_process"
android:screenOrientation="portrait"
android:theme="#style/AppTheme">
<intent-filter>
<action android:name="android.intent.action.LOGIN_ACTION" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
</application>
</manifest>
build.gradle (Module: app)
dependencies {
...
compile 'com.android.volley:volley:1.0.0'
}
Thank you!
Just call editor.clear();
and editor.commit();
is enough to delete all data from shared preference.
Because onResume, you keep on instantiating a new SharedPrefManager
sharedPrefManager = new SharedPrefManager(this);
Modify your SharedPrefManager so that it only gives one instance at all times OR make sure that you are referring to the same object when you return to LoginActivity.
SharedPreferences is permanent storage, you can clear
SharedPreferences.Editor.clear().commit();
alternate solution
you want once app close clear entire values,try Application singleton class
#Ciammarica you can call this code on click of Logout button, hope this can help you..you can set in logout button boolean value false..
SessionManager.setUserLoggedIn(YourActivity.this, false); SessionManager.clearAppCredential(YourActivity.this);
I Changed my code in order to have only one instance of SharedPrefManager class.
This is my App singleton class:
public class App extends Application
{
private static App mInstance;
private SharedPrefManager sharedPrefManager;
#Override
public void onCreate() {
super.onCreate();
mInstance = this;
sharedPrefManager = new SharedPrefManager(this);
}
public SharedPrefManager getSharedPrefManager(){
return sharedPrefManager;
}
public static synchronized App getInstance(){
return mInstance;
}
}
Then from other classes I get the instance by calling
SharedPrefManager sharedPrefManager = App.getInstance().getSharedPrefManager();
Now, with this change, the onSharedPreferenceChanged() event is triggered only once, so this is better than before, but the "delayed" behavior is still there... I mean, even if I use editor.clear(); and editor.commit(); methods, the values are updated but I can see them only if I close and open the app again.
I found the problem myself... It didn't like the sharedPrefManager.removeDataFromSharedPreference(); method to be called from inside new DialogInterface.OnClickListener()
I took it in another part of the code and it worked.
I'm trying to connect to other Android devices using Bluetooth via my app. The app works fine while discovering nearby Bluetooth devices. However, upon connecting, the app crashes.
I have two JAVA files other than MainActivity.java that are responsible for discovering & connecting to other Bluetooth devices. Their codes are posted below:
SearchBTDevice.java (for discovering nearby devices)
package vertex2016.mvjce.edu.bluealert;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGattDescriptor;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.bluetooth.BluetoothAdapter;
import android.provider.Settings;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import java.util.Set;
public class SearchBTDevice extends AppCompatActivity {
public BluetoothAdapter BlueAdapter = BluetoothAdapter.getDefaultAdapter();
public ArrayAdapter PairedArrayAdapter;
public ArrayAdapter BTArrayAdapter;
BluetoothDevice btd;
public ListView devicesFound;
private final BroadcastReceiver BTReceiver= new BroadcastReceiver(){
public void onReceive(Context context, Intent intent)
{
String action = intent.getAction();
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
btd = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
BTArrayAdapter.add(btd.getName() + "\t" + btd.getAddress() + "\n");
}
}
};
IntentFilter filter1 = new IntentFilter(BluetoothDevice.ACTION_FOUND);
#Override
protected void onResume() {
super.onResume();
this.registerReceiver(BTReceiver,filter1);
}
#Override
protected void onPause() {
super.onPause();
BlueAdapter.cancelDiscovery();
this.unregisterReceiver(BTReceiver);
Toast.makeText(SearchBTDevice.this, "Discovery Stopped!!", Toast.LENGTH_SHORT).show();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search_btdevice);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LOCKED);
searchBTDevices();
}
public void searchBTDevices()
{
if(!BlueAdapter.startDiscovery())
Toast.makeText(SearchBTDevice.this, "Failed to Start Discovery", Toast.LENGTH_SHORT).show();
else
Toast.makeText(SearchBTDevice.this, "Discovery Startred", Toast.LENGTH_SHORT).show();
BTArrayAdapter = new ArrayAdapter(this, android.R.layout.simple_list_item_1);
devicesFound = (ListView)findViewById(R.id.searchpagelistView);
devicesFound.setAdapter(BTArrayAdapter);
devicesFound.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent connectedBTintent = new Intent(SearchBTDevice.this, ConnectedBTDevice.class);
connectedBTintent.putExtra("BluetoothDevice", btd);
startActivity(connectedBTintent);
}
});
}
}
This is updated ConnectedBTDevice.java, responsible for connecting devices
package vertex2016.mvjce.edu.bluealert;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import java.io.IOException;
import java.util.UUID;
public class ConnectedBTDevice extends AppCompatActivity {
public BluetoothDevice btd;
public BluetoothSocket btSocket, tempSocket;
private UUID myUUID;
ArrayAdapter arr;
ListView lv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_connected_btdevice);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LOCKED);
arr = new ArrayAdapter(this, android.R.layout.simple_list_item_2);
btd = getIntent().getParcelableExtra("BluetoothDevice");
connectBT();
displayStuff();
}
public void connectBT() {
Thread myThread = new Thread() {
public void run() {
tempSocket = null;
try {
tempSocket = btd.createRfcommSocketToServiceRecord(myUUID);
} catch (IOException e) {
e.printStackTrace();
}
BluetoothAdapter.getDefaultAdapter().cancelDiscovery();
try {
tempSocket.connect();
arr.add("CONNECTED TO-->" + btd.getName());
} catch (IOException e) {
e.printStackTrace();
try {
tempSocket.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
};
myThread.start();
}
public void displayStuff()
{
lv = (ListView)findViewById(R.id.connectedBTlistView);
lv.setAdapter(arr);
}
}
This is activity_connected_btdevice.xml for ConnectedBTDevice.java activity
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context="vertex2016.mvjce.edu.bluealert.SearchBTDevice">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/AppTheme.NoActionBar.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="#style/AppTheme.NoActionBar.PopupOverlay" />
</android.support.design.widget.AppBarLayout>
<include layout="#layout/content_connected_btdevice" />
</android.support.design.widget.CoordinatorLayout>
This is content_connected_btdevice.xml for ConnectedBTDevice.java
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context="vertex2016.mvjce.edu.bluealert.ConnectedBTDevice"
tools:showIn="#layout/activity_connected_btdevice">
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/connectedBTimageView"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:src="#drawable/bluealert_bg"
android:scaleType="centerCrop"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Connected Bluetooth Device"
android:id="#+id/connectedBTtextextView"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="105dp"
android:textSize="25dp"
android:textAlignment="center"/>
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/connectedBTlistView"
android:layout_below="#+id/connectedBTtextextView"
android:layout_centerHorizontal="true"
android:layout_marginTop="65dp" />
</RelativeLayout>
This is AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="vertex2016.mvjce.edu.bluealert">
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<application
android:allowBackup="true"
android:icon="#mipmap/bluealerticon"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme.NoActionBar">
<activity
android:name=".SplashScreen"
android:label="#string/app_name"
android:theme="#style/AppTheme.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".MainActivity" />
<activity
android:name=".SearchBTDevice"
android:label="#string/title_activity_search_btdevice"
android:parentActivityName=".MainActivity"
android:theme="#style/AppTheme.NoActionBar">
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="vertex2016.mvjce.edu.bluealert.MainActivity" />
</activity>
<activity
android:name=".ConnectedBTDevice"
android:label="#string/title_activity_connected_btdevice"
android:parentActivityName=".SearchBTDevice"
android:theme="#style/AppTheme.NoActionBar">
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="vertex2016.mvjce.edu.bluealert.SearchBTDevice" />
</activity>
</application>
</manifest>
Here's the exception that my updated logcat shows
03-24 00:19:40.541 7205-9703/vertex2016.mvjce.edu.bluealert E/AndroidRuntime: FATAL EXCEPTION: Thread-35890
Process: vertex2016.mvjce.edu.bluealert, PID: 7205
java.lang.NullPointerException: Attempt to invoke virtual method 'long java.util.UUID.getMostSignificantBits()' on a null object reference
at android.os.ParcelUuid.writeToParcel(ParcelUuid.java:129)
at android.bluetooth.IBluetooth$Stub$Proxy.connectSocket(IBluetooth.java:1767)
at android.bluetooth.BluetoothSocket.connect(BluetoothSocket.java:309)
at vertex2016.mvjce.edu.bluealert.ConnectedBTDevice$1.run(ConnectedBTDevice.java:63)
I don't understand what the problem is. I have tried several online tutorials, but nothing seemed to work. I know the problem is in my ConnectedBTDevice.java, but can't figure out the point at which it's throwing the exception.
Thank you for your time.
You are assigning BluetoothSocket to tempSocket, and then you try to invoke connect() method on btSocket which is null.
I'm doing the json parsing over the POSTMAN API WHICH WE CREATED and I'm trying to POST Login details to POSTMAN i.e:- username and password and if the details are correct POSTMAN will return response back in JSON STRING. When I run this im not able to get any sort of data in back. It showing me the UNEXPECTED RESPONSE CODE 400,406,404
MainActivity.java
package com.dropouts.copylogin;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonRequest;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Map;
public class MainActivity extends AppCompatActivity {
private EditText email;
private EditText password;
private Button login_register;
private RequestQueue requestQueue;
private StringRequest request;
private TextView tv;
private static String URL="http://192.168.1.18/rakyesh/test/rest/rest/login";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
email= (EditText) findViewById(R.id.user);
password=(EditText)findViewById(R.id.pass);
login_register=(Button)findViewById(R.id.loginbtn);
requestQueue= Volley.newRequestQueue(this);
login_register.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
request = new StringRequest(Request.Method.POST, URL, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
Log.e("Response of 192 returns username",">"+jsonObject.getString("username"));
if (jsonObject.names().get(0).equals("username")) {
Toast.makeText(getApplicationContext(), "SUCCESS"+ jsonObject.getString("username"),Toast.LENGTH_LONG).show();
startActivity(new Intent(getApplicationContext(), Welcome.class));
} else {
Toast.makeText(getApplicationContext(), "Error" + jsonObject.getString("error"), Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
HashMap<String, String> hashMap = new HashMap<String, String>();
hashMap.put("Content-Type","application/json; charset=utf-8");
hashMap.put("email", email.getText().toString());
hashMap.put("password", password.getText().toString());
return hashMap;
}
};
requestQueue.add(request);
}
});
}
}
MANIFEST.XML
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.dropouts.copylogin">
<uses-permission android:name="android.permission.INTERNET"/>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".Welcome"/>
</application>
</manifest>
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_gravity="center_horizontal"
android:orientation="vertical"
tools:context="com.dropouts.copylogin.MainActivity">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/user"
android:hint="username"
android:inputType="text"
android:maxLines="1"
android:singleLine="true"
android:layout_marginTop="50dp" />
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="textPassword"
android:ems="10"
android:maxLines="1"
android:singleLine="true"
android:id="#+id/pass"
android:hint="Pass"
android:layout_marginTop="42dp"
/>
<Button
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="LOGIN/REGISTER"
android:id="#+id/loginbtn"
/>
<TextView
android:layout_marginTop="10dp"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/txt"
android:textAppearance="?android:textAppearanceLarge"
android:layout_below="#+id/loginbtn"
/></LinearLayout>
WELCOME.JAVA
package com.dropouts.copylogin;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
/**
* Created by Pankaj on 3/17/2016.
*/
public class Welcome extends Activity {
Button logout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.welcome_activity);
logout= (Button) findViewById(R.id.log_out);
logout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(getApplicationContext(),MainActivity.class));
}
});
}
}
welcome_activity.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Welcome"
android:id="#+id/wlcmtxt"
android:textAppearance="?android:textAppearanceLarge"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Logout"
android:id="#+id/log_out"
android:layout_alignParentTop="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
</RelativeLayout>
Here are error code doc in HttpStatus.java.
int SC_NOT_FOUND = 404;
int SC_BAD_REQUEST = 400;
int SC_NOT_ACCEPTABLE;
I submit your request not meet the standards.These code below should be put in method 'getHeaders()' but not in 'getParams()'.
hashMap.put("Content-Type","application/json; charset=utf-8");
Here are a demo using StringRequest by post in volley.
https://gist.github.com/mombrea/7250835
You are passing application/json as Content-Type in your header and passing string data.If you want to post json data it is better to use JsonObjectRequest instead . Please try removing Content-Type header from HashMap.it might help.
UPDATE:
JSONObject params = new JSONObject();
//build your params
JsonObjectRequest jsObjRequest = new JsonObjectRequest
(Request.Method.POST, url, params, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
//parse the response for the result
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
// TODO Auto-generated method stub
}
});