How can Add downloading status show (like as android defualt browser ) - java

How can I show downloading status bar similar to android default browser:

You really should search before post a question here my friend.
There is a component in Android API that could help you called DownloadManager.
The Android DownloadManager introduced in Android 2.3. (API 9) is a system service which allows to handle long-running HTTP downloads in the background and notify the triggering application via a broadcast receiver once the download is finished.
Here is a little example for using the DownloadManager. The project will be called “de.vogella.android.downloadmanager” with the activity “DownloadManagerActivity” based on Android API9 or higher.
Change “main.xml” to the following.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="fill_parent">
<Button android:text="Start Download" android:id="#+id/button1"
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:onClick="onClick"></Button>
<Button android:text="View Downloads" android:id="#+id/button2"
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:onClick="showDownload"></Button>
<ImageView android:layout_height="wrap_content" android:id="#+id/imageView1"
android:src="#drawable/icon" android:layout_width="wrap_content"></ImageView>
</LinearLayout>
Change the code of your activity to the following.
package de.vogella.android.downloadmanager;
import android.app.Activity;
import android.app.DownloadManager;
import android.app.DownloadManager.Query;
import android.app.DownloadManager.Request;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
public class DownloadManagerActivity extends Activity {
private long enqueue;
private DownloadManager dm;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
BroadcastReceiver receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action)) {
long downloadId = intent.getLongExtra(
DownloadManager.EXTRA_DOWNLOAD_ID, 0);
Query query = new Query();
query.setFilterById(enqueue);
Cursor c = dm.query(query);
if (c.moveToFirst()) {
int columnIndex = c
.getColumnIndex(DownloadManager.COLUMN_STATUS);
if (DownloadManager.STATUS_SUCCESSFUL == c
.getInt(columnIndex)) {
ImageView view = (ImageView) findViewById(R.id.imageView1);
String uriString = c
.getString(c
.getColumnIndex(DownloadManager.COLUMN_LOCAL_URI));
view.setImageURI(Uri.parse(uriString));
}
}
}
}
};
registerReceiver(receiver, new IntentFilter(
DownloadManager.ACTION_DOWNLOAD_COMPLETE));
}
public void onClick(View view) {
dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
Request request = new Request(
Uri.parse("http://www.vogella.de/img/lars/LarsVogelArticle7.png"));
enqueue = dm.enqueue(request);
}
public void showDownload(View view) {
Intent i = new Intent();
i.setAction(DownloadManager.ACTION_VIEW_DOWNLOADS);
startActivity(i);
}
}
Also add the permission to go to the internet to your app.
If you implemented this example you have an Android application which can download my picture (sorry for this ;-)) and allow you to switch to the download manager to see the finished downloads.
Hope this helps.
Source: http://blog.vogella.com/2011/06/14/android-downloadmanager-example/

Related

Only one device being detected in bluetooth

I'm making a bluetooth application using android studio and the problem is that the application scans for devices once only. After it finds a device, it stops looking for other.I want to search for all available devices around my device. The activity code is:
package com.example.yubrajsharma.my_application;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.ProgressBar;
import java.util.ArrayList;
import static android.view.View.INVISIBLE;
public class MainActivity extends AppCompatActivity{
BluetoothAdapter mBluetoothAdapter;
int count;
Button lister;
public ArrayList<BluetoothDevice> mBTDevices = new ArrayList<>();
String[] mBTDevice;
ArrayAdapter<String> adapter;
private static final String TAG = "MainActivity";
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action.equals(mBluetoothAdapter.ACTION_STATE_CHANGED)) {
final int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, mBluetoothAdapter.ERROR);
}
}
};
#Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(mReceiver);
unregisterReceiver(mReciever);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ProgressBar pg = (ProgressBar) findViewById(R.id.progressBar);
pg.setVisibility(View.INVISIBLE);
Button searchbtn = (Button) findViewById(R.id.searchbtn);
Button lister = (Button) findViewById(R.id.lists);
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if(mBluetoothAdapter.isEnabled()){
lister.setVisibility(View.VISIBLE);
}
lister.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
listdata();
}
});
}
private BroadcastReceiver mReciever = new BroadcastReceiver(){
#Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
ProgressBar pg = (ProgressBar) findViewById(R.id.progressBar);
if (action.equals(BluetoothDevice.ACTION_FOUND)) {
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
mBTDevices.add(device);
}
count = mBTDevices.size();
int j = 0;
mBTDevice = new String[count];
if(count>0) {
for (BluetoothDevice device : mBTDevices) {
mBTDevice[j] = device.getName();
j++;
}
ListView pairing = (ListView) findViewById(R.id.paired);
adapter = new ArrayAdapter<String>(MainActivity.this,android.R.layout.simple_list_item_1,mBTDevice);
pairing.setAdapter(adapter);
}
else{
mBTDevice[0] = "no devices found";
ListView pairing = (ListView) findViewById(R.id.paired);
adapter = new ArrayAdapter<String>(MainActivity.this,android.R.layout.simple_list_item_1,mBTDevice);
pairing.setAdapter(adapter);
}
mBluetoothAdapter.cancelDiscovery();
pg.setVisibility(View.INVISIBLE);
Log.d(TAG, "Disabled");
}
};
private void listdata() {
if(mBluetoothAdapter.isDiscovering()) {
mBluetoothAdapter.cancelDiscovery();
}
mBluetoothAdapter.startDiscovery();
ProgressBar pg = (ProgressBar) findViewById(R.id.progressBar);
pg.setVisibility(View.VISIBLE);
IntentFilter infill = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(mReciever, infill);
}
public void enableDisableBT(View view) {
Button lister = (Button) findViewById(R.id.lists);
if(!mBluetoothAdapter.isEnabled()){
Intent enableBTintent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivity(enableBTintent);
IntentFilter btIntent = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
registerReceiver(mReceiver, btIntent);
}
if(mBluetoothAdapter.isEnabled()){
mBluetoothAdapter.disable();
IntentFilter btIntent = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
registerReceiver(mReceiver, btIntent);
}
}
}
The Code for the xml file is:
<?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"
tools:context="com.example.yubrajsharma.my_application.MainActivity"
tools:layout_editor_absoluteY="81dp"
tools:layout_editor_absoluteX="0dp">
<Button
android:id="#+id/lists"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="List Devices"
android:visibility="invisible"
app:layout_constraintLeft_toRightOf="#+id/searchbtn"
app:layout_constraintBottom_toBottomOf="#+id/searchbtn"
android:layout_marginRight="28dp"
android:layout_marginEnd="28dp"
android:layout_alignParentTop="true"
android:layout_alignRight="#+id/paired"
android:layout_alignEnd="#+id/paired" />
<Button
android:id="#+id/searchbtn"
android:onClick="enableDisableBT"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="ON/OFF"
android:visibility="visible"
tools:layout_editor_absoluteX="0dp"
tools:layout_editor_absoluteY="3dp" />
<ListView
android:id="#+id/paired"
android:layout_width="368dp"
android:layout_height="422dp"
app:layout_constraintTop_toBottomOf="#+id/lists"
app:layout_constraintLeft_toLeftOf="#+id/searchbtn"
android:layout_marginBottom="13dp"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
<ProgressBar
android:id="#+id/progressBar"
style="?android:attr/progressBarStyle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_marginEnd="29dp"
android:layout_marginRight="29dp"
android:layout_toLeftOf="#+id/lists"
android:layout_toStartOf="#+id/lists"
tools:visibility="invisible" />
</RelativeLayout>
How to scan all the available devices?
Well in your BroadcastReceiver.onReceive method once it gets called you call:
mBluetoothAdapter.cancelDiscovery();
So this stops the discovering process. Try to remove this line and see what happens.
However keep in mind the following from the official documentation:
Because discovery is a heavyweight procedure for the Bluetooth
adapter, this method should always be called before attempting to
connect to a remote device with connect(). Discovery is not managed by
the Activity, but is run as a system service, so an application should
always call cancel discovery even if it did not directly request a
discovery, just to be sure.

App user force to login first

I am beginner in App development and I have ready made source code.
Please find below two files, I want to force user to login first then redirect to home page, If I change MainActivity to LoginActivity in IntroActivity file user getting login window but after login not redirect to MainActivity page. Please suggesst where exactly I need to change.
Code are:
File 1 :IntroActivity.java
package com.ristana.bullish.ui.activity;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.ristana.bullish.R;
import com.ristana.bullish.entity.ApiResponse;
import com.ristana.bullish.manager.PrefManager;
import java.util.Timer;
import java.util.TimerTask;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import com.ristana.bullish.api.apiClient;
import com.ristana.bullish.api.apiRest;
public class IntroActivity extends AppCompatActivity {
private ProgressBar intro_progress;
private RelativeLayout activity_intro;
private PrefManager prf;
private TextView text_view_app_version;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getSupportActionBar().hide();
prf= new PrefManager(getApplicationContext());
initView();
Timer myTimer = new Timer();
myTimer.schedule(new TimerTask() {
#Override
public void run() {
// If you want to modify a view in your Activity
IntroActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
if (prf.getString("LOGGED").contains("TRUE")){
checkAccount();
}else{
Intent intent = new Intent(IntroActivity.this,MainActivity.class);
startActivity(intent);
}
}
});
}
}, 5000);
}
private void initView(){
setContentView(R.layout.activity_intro);
this.intro_progress=(ProgressBar) findViewById(R.id.intro_progress);
this.activity_intro=(RelativeLayout) findViewById(R.id.activity_intro);
intro_progress.setVisibility(View.VISIBLE);
this.text_view_app_version=(TextView) findViewById(R.id.text_view_app_version);
try {
PackageInfo pInfo = getPackageManager().getPackageInfo(getPackageName(),0);
String version = pInfo.versionName;
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
}
private void checkAccount() {
intro_progress.setVisibility(View.VISIBLE);
Retrofit retrofit = apiClient.getClient();
apiRest service = retrofit.create(apiRest.class);
Call<ApiResponse> call = service.check(prf.getString("ID_USER"),prf.getString("TOKEN_USER"));
call.enqueue(new Callback<ApiResponse>() {
#Override
public void onResponse(Call<ApiResponse> call, Response<ApiResponse> response) {
if (response.isSuccessful()){
if (response.body().getCode()==200){
Intent intent = new Intent(IntroActivity.this,MainActivity.class);
startActivity(intent);
}else if(response.body().getCode()==500){
logout();
Intent intent = new Intent(IntroActivity.this,MainActivity.class);
startActivity(intent);
}else {
Intent intent = new Intent(IntroActivity.this,MainActivity.class);
startActivity(intent);
}
}else{
Intent intent = new Intent(IntroActivity.this,MainActivity.class);
startActivity(intent);
}
}
#Override
public void onFailure(Call<ApiResponse> call, Throwable t) {
Intent intent = new Intent(IntroActivity.this,MainActivity.class);
startActivity(intent);
intro_progress.setVisibility(View.INVISIBLE);
}
});
}
public void logout(){
PrefManager prf= new PrefManager(getApplicationContext());
prf.remove("ID_USER");
prf.remove("SALT_USER");
prf.remove("TOKEN_USER");
prf.remove("NAME_USER");
prf.remove("TYPE_USER");
prf.remove("USERNAME_USER");
prf.remove("URL_USER");
prf.remove("LOGGED");
Toast.makeText(getApplicationContext(),getString(R.string.message_logout_desibaled),Toast.LENGTH_LONG).show();
}
#Override
public void onPause(){
super.onPause();
finish();
}
}
File 2: activity_intro.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"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/activity_intro"
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="com.ristana.bullish.ui.activity.IntroActivity">
<ProgressBar
android:progressDrawable="#drawable/progress_yellow"
android:indeterminateDrawable="#drawable/progress_yellow"
style="?android:attr/progressBarStyleLarge"
android:layout_width="40dp"
android:layout_height="40dp"
android:layout_centerInParent="true"
android:layout_alignParentBottom="true"
android:layout_marginBottom="10dp"
android:id="#+id/intro_progress" />
<LinearLayout
android:orientation="vertical"
android:layout_marginTop="20dp"
android:layout_below="#+id/logo_app"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:layout_gravity="center"
android:gravity="center"
android:padding="5dp"
android:textSize="20dp"
android:textStyle="bold"
android:layout_centerInParent="true"
android:textColor="#color/primary_text"
android:textAlignment="center"
android:text=" "
android:id="#+id/text_view_app_name"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<TextView
android:layout_gravity="center"
android:gravity="center"
android:padding="8dp"
android:textSize="18dp"
android:layout_centerInParent="true"
android:textColor="#color/primary_text"
android:textAlignment="center"
android:text=" "
android:id="#+id/text_view_app_version"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</LinearLayout>
<ImageView
android:layout_width="130dp"
android:layout_height="130dp"
app:srcCompat="#drawable/logo"
android:id="#+id/logo_app"
android:layout_centerInParent="true"
android:layout_centerHorizontal="true" />
</RelativeLayout>
Thanks in advance.
As it was stated in the comments, I guess you don't not how this code works, at all, so I will try to simplified for you.
First you are using retrofit, which is an excellent tool to use for getting and posting data to servers without all the trouble (google that and you will find out more). Then you are using PrefManager that is used to store some key/value pairs in application storage so you can retrive them when needed. (What are the PreferenceManager and SharedPreference classes used for in Android? here's a link that will clear that).
And to the part that you asked about, you are calling retrofits on respons, and if it responsed with success (means that the login data was send to server, tested, and it's ok), then you are creating new Intent telling to swipe IntoActivity.this (your currentactivity) with MainActivity.class and with the startActivity(intent) it redirects you to MainActivity. You can't just "change" the MainActivty with LoginActivity and wait to be redirected to Main. You can redirect the intent to LoginActivity and then redirect it again to MainActivity (as I don't know what you are trying to do here). And don't forget, any new activity should be stated in the Manifest.
I will suggest reading more about android and it's basics before you try to take on this kind of code as you will be lost.
Good luck coding.
Just check out what is the response code return from retrofit call.
Best way would be debug the code. On successful response/failure, code is written. But still need to know whether code reaching there. If it does not reach there , the steps would not be carried out.
Hope that helps.

IllegalStateException: Could not find method in a parent or ancestor Context for android:onClick attribute defined on view class

When i click on a button with ID "btnDiscoverable_on_off" and "lvNewDevices" i get this error :
java.lang.IllegalStateException: Could not find method btnDiscover(View) in a parent or ancestor Context for android:onClick attribute defined on view class android.support.v7.widget.AppCompatButton with id 'btnFindUnpairedDevices'
This is the code :
import android.Manifest;
import android.app.Fragment;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import java.util.ArrayList;
public class PrimoFragment extends Fragment implements
AdapterView.OnItemClickListener {
View myView;
private static final String TAG = "MainActivity";
BluetoothAdapter mBluetoothAdapter;
Button btnEnableDisable_Discoverable;
public ArrayList<BluetoothDevice> mBTDevices = new ArrayList<>();
public DeviceListAdapter mDeviceListAdapter;
ListView lvNewDevices;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, Bundle savedInstanceState) {
myView = inflater.inflate(R.layout.primo_layout, container, false);
Button btnONOFF = (Button) myView.findViewById(R.id.btnONOFF);
btnEnableDisable_Discoverable = (Button) myView.findViewById(R.id.btnDiscoverable_on_off);
lvNewDevices = (ListView) myView.findViewById(R.id.lvNewDevices);
mBTDevices = new ArrayList<>();
//Broadcasts when bond state changes (ie:pairing)
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
getActivity().registerReceiver(mBroadcastReceiver4, filter);
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
lvNewDevices.setOnItemClickListener(PrimoFragment.this);
btnONOFF.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.d(TAG, "onClick: enabling/disabling bluetooth.");
enableDisableBT();
}
});
return myView;
}
public void enableDisableBT(){
if(mBluetoothAdapter == null){
Log.d(TAG, "enableDisableBT: Does not have BT capabilities.");
}
if(!mBluetoothAdapter.isEnabled()){
Log.d(TAG, "enableDisableBT: enabling BT.");
Intent enableBTIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivity(enableBTIntent);
IntentFilter BTIntent = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
getActivity().registerReceiver(mBroadcastReceiver1, BTIntent);
}
if(mBluetoothAdapter.isEnabled()){
Log.d(TAG, "enableDisableBT: disabling BT.");
mBluetoothAdapter.disable();
IntentFilter BTIntent = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
getActivity().registerReceiver(mBroadcastReceiver1, BTIntent);
}
}
public void btnEnableDisable_Discoverable(View view) {
Log.d(TAG, "btnEnableDisable_Discoverable: Making device discoverable for 300 seconds.");
Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
startActivity(discoverableIntent);
IntentFilter intentFilter = new IntentFilter(mBluetoothAdapter.ACTION_SCAN_MODE_CHANGED);
getActivity().registerReceiver(mBroadcastReceiver2,intentFilter);
}
public void btnDiscover(View view) {
Log.d(TAG, "btnDiscover: Looking for unpaired devices.");
if(mBluetoothAdapter.isDiscovering()){
mBluetoothAdapter.cancelDiscovery();
Log.d(TAG, "btnDiscover: Canceling discovery.");
//check BT permissions in manifest
checkBTPermissions();
mBluetoothAdapter.startDiscovery();
IntentFilter discoverDevicesIntent = new IntentFilter(BluetoothDevice.ACTION_FOUND);
getActivity().registerReceiver(mBroadcastReceiver3, discoverDevicesIntent);
}
if(!mBluetoothAdapter.isDiscovering()){
//check BT permissions in manifest
checkBTPermissions();
mBluetoothAdapter.startDiscovery();
IntentFilter discoverDevicesIntent = new IntentFilter(BluetoothDevice.ACTION_FOUND);
getActivity().registerReceiver(mBroadcastReceiver3, discoverDevicesIntent);
}
}
/**
* This method is required for all devices running API23+
* Android must programmatically check the permissions for bluetooth. Putting the proper permissions
* in the manifest is not enough.
*
* NOTE: This will only execute on versions > LOLLIPOP because it is not needed otherwise.
*/
private void checkBTPermissions() {
if(Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP){
int permissionCheck = this.getActivity().checkSelfPermission("Manifest.permission.ACCESS_FINE_LOCATION");
permissionCheck += this.getActivity().checkSelfPermission("Manifest.permission.ACCESS_COARSE_LOCATION");
if (permissionCheck != 0) {
this.getActivity().requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION}, 1001); //Any number
}
}else{
Log.d(TAG, "checkBTPermissions: No need to check permissions. SDK version < LOLLIPOP.");
}
}
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
//first cancel discovery because its very memory intensive.
mBluetoothAdapter.cancelDiscovery();
Log.d(TAG, "onItemClick: You Clicked on a device.");
String deviceName = mBTDevices.get(i).getName();
String deviceAddress = mBTDevices.get(i).getAddress();
Log.d(TAG, "onItemClick: deviceName = " + deviceName);
Log.d(TAG, "onItemClick: deviceAddress = " + deviceAddress);
//create the bond.
//NOTE: Requires API 17+? I think this is JellyBean
if(Build.VERSION.SDK_INT > Build.VERSION_CODES.JELLY_BEAN_MR2){
Log.d(TAG, "Trying to pair with " + deviceName);
mBTDevices.get(i).createBond();
}
}
}
XML code primo_fragment:
<?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">
<Button
android:text="ON/OFF"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/btnONOFF"
android:layout_alignParentEnd="true" />
<Button
android:text="Enable Discoverable"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/btnDiscoverable_on_off"
android:onClick="btnEnableDisable_Discoverable"
android:layout_centerHorizontal="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/btnFindUnpairedDevices"
android:text="Discover"
android:onClick="btnDiscover" />
<ListView
android:layout_width="wrap_content"
android:layout_height="150dp"
android:id="#+id/lvNewDevices"
android:layout_marginTop="62dp"
android:layout_alignParentStart="true" />
</RelativeLayout>
device_adapter_view
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/tvDeviceName"
android:textSize="15sp"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/tvDeviceAddress"
android:textSize="15sp"/>
</LinearLayout>
What is wrong with these two button ? I can't find the problem
Please follow this structure to use xml onClick attribute for Fragment. Hope your problem will be resolved.

Why does my java code always print out zero for signal strength in android studio

I am pretty new to coding and this is my first time working with TelephonyManager. I can't figure out why the TextView only prints out a zero when i hit the button in this code. I need it to print out the signal strength. The app compiles and runs and the permissions are there so I am out of ideas right now.
Please and thank you.
package com.example.vitaliy_2.signalminer11;
import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.telephony.PhoneStateListener;
import android.telephony.SignalStrength;
import android.telephony.TelephonyManager;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class Menu extends AppCompatActivity{
TextView cdmaSignal;
Button cellButt;
String cap;
TelephonyManager tm;
MMPSL mm;
float sigstr;
int permissionCheck;
#RequiresApi(api = Build.VERSION_CODES.N)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_menu);
cdmaSignal = (TextView) findViewById(R.id.cdmaSignal);
cellButt = (Button) findViewById(R.id.cellButt);
mm = new MMPSL();
tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
tm.listen(mm,PhoneStateListener.LISTEN_SIGNAL_STRENGTHS);
permissionCheck = ContextCompat.checkSelfPermission(Menu.this,
Manifest.permission.READ_PHONE_STATE);
cap = Float.toString(sigstr);
String nmp = "Permission required for the continued function of the phone signal monitor ";
if(permissionCheck != PackageManager.PERMISSION_GRANTED){
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.READ_PHONE_STATE)) {
} else {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.READ_PHONE_STATE},
1);
}
cdmaSignal.setText(nmp);
}
}
public void clkFrSgnl(View view){
cdmaSignal.setText(cap);
// tts = Integer.toString(gs.signal);
//gsmSignal.setText(tts);
}
class MMPSL extends PhoneStateListener{
#Override
public void onSignalStrengthsChanged(SignalStrength signalStrength) {
super.onSignalStrengthsChanged(signalStrength);
sigstr = signalStrength.getCdmaDbm();
sigstr = (2 * sigstr) - 113;
}
}
}
This is the xml file
<?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:id="#+id/activity_menu"
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="com.example.vitaliy_2.signalminer11.Menu">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/cell_signal_CDMA"
android:textAlignment="center"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:id="#+id/cdmaSignal"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
<Button
android:text="#string/get_signal_CDMA"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:id="#+id/cellButt"
android:onClick="clkFrSgnl" />
</RelativeLayout>
From what I've done in the past, the andoroid:onClick function was enough for the button and the in the code. the view class is called.
public void clkFrSgnl(View view){
cap = Float.toString(sigstr);
cdmaSignal.setText(cap);
}
I don't see an onClickListener attached to your button. The button isn't doing anything.
If the button is having it's onClickListener set elsewhere, clkFrSgnl() is not changing the text of cap so cdmaSignal.setText(cap); is just constantly resetting the text to what cap was set to in onCreate.
Try something like
onSignalStrengthsChanged(){
super.onSignalStrengthsChanged(signalStrength);
sigstr = signalStrength.getCdmaDbm();
sigstr = (2 * sigstr) - 113;
cap = sigstr;
}
I'm pretty sure the float sigstr can just be converted to the String cap, if not .toString() it.

Open browser to web page Android App

Trying to grasp Java and Android would like help with a simple task of opening a users browser after they click a button.
I have been doing tutorials for the last two days though it might help if I just took a stab at it and got feedback. thanks in advance for any help.
main.xml:
<AbsoluteLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#drawable/bgimage2">
>
<Button
android:id="#+id/goButton"
android:layout_width="150px"
android:layout_height="wrap_content"
android:text="#string/start"
android:layout_x="80px"
android:layout_y="21px"
>
</AbsoluteLayout>
GetURL.java:
package com.patriotsar;
import android.app.Activity;
import android.content.Intent;
import android.view.View.OnClickListener;
String url = "http://www.yahoo.com";
Intent i = new Intent(Intent.ACTION_VIEW);
Uri u = Uri.parse(url);
i.setData(u);
public class patriosar extends Activity {
private Button goButton;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
goButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v){
try {
// Start the activity
startActivity(i);
} catch (ActivityNotFoundException e) {
// Raise on activity not found
Toast toast = Toast.makeText(context, "Browser not found.", Toast.LENGTH_SHORT);
}
}
});
}
}
It's close, but a few things are in the wrong place or missing. The below code works -- I tried to make the minimum necessary alterations. You could load both versions into something like WinMerge to see exactly what changed.
main.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#drawable/bgimage2"
>
<Button
android:id="#+id/goButton"
android:layout_width="150px"
android:layout_height="wrap_content"
android:text="#string/start"
android:layout_x="80px"
android:layout_y="21px"
></Button>
</LinearLayout>
GetURL.java:
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class GetURL extends Activity {
private Button goButton;
String url = "http://www.yahoo.com";
Intent i = new Intent(Intent.ACTION_VIEW);
Uri u = Uri.parse(url);
Context context = this;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
goButton = (Button)findViewById(R.id.goButton);
goButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v){
try {
// Start the activity
i.setData(u);
startActivity(i);
} catch (ActivityNotFoundException e) {
// Raise on activity not found
Toast.makeText(context, "Browser not found.", Toast.LENGTH_SHORT);
}
}
});
}
}
(You also need a bgimage2.png file in /res/drawable/ and a start string in /res/values/strings.xml, of course).
To simplify you could do
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.yahoo.com"));
startActivity(intent);

Categories

Resources