I want create application
Scan Barcode using ZXING Barcode Scanner
Like Blackberry Messenger
This is my code "MainActivity.java"
package com.example.ridwan.myapplication;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.TextView;
import info.vividcode.android.zxing.CaptureActivity;
import info.vividcode.android.zxing.CaptureActivityIntents;
public class MainActivity extends AppCompatActivity {
private TextView tvScanResult;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent captureIntent = new Intent(MainActivity.this, CaptureActivity.class);
CaptureActivityIntents.setPromptMessage(captureIntent, "Barcode scanning...");
startActivityForResult(captureIntent, 0);
tvScanResult = (TextView) findViewById(R.id.tv_scanresult);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 0) {
if (resultCode == Activity.RESULT_OK && data != null) {
String value = data.getStringExtra("SCAN_RESULT");
tvScanResult.setText(value);
} else if (resultCode == Activity.RESULT_CANCELED) {
tvScanResult.setText("Scanning Gagal, mohon coba lagi.");
}
} else {
}
super.onActivityResult(requestCode, resultCode, data);
}
}
Then this is my "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="com.example.ridwan.myapplication.MainActivity"
tools:showIn="#layout/activity_main">
<TextView
android:layout_marginTop="50dp"
android:id="#+id/tv_scanresult_title"
android:layout_centerHorizontal="true"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Result Scan : " />
<TextView
android:layout_below="#id/tv_scanresult_title"
android:id="#+id/tv_scanresult"
android:layout_centerHorizontal="true"
android:layout_width="wrap_content"
android:textColor="#ff1493"
android:layout_height="wrap_content"
android:text="_" />
</RelativeLayout>
Can you give me solution ?
i want to barcode in fragment.
I have achieved the same effect/UI you are looking for by using ZXing Android Embedded. Very straightforward to implement - and it also includes a torch functionality.
Step 1:
Add This Libray in Gradle in Dependancy
implementation 'com.google.zxing:core:3.2.1'
implementation 'com.journeyapps:zxing-android-embedded:3.2.0#aar'
Step 2:
BarcodeActivity.java
public class BarcodeActivity extends AppCompatActivity {
private EditText editTextProductId;
private Button buttonGenerate, buttonScan;
private ImageView imageViewResult;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_barcode);
initView();
}
private void initView() {
editTextProductId = findViewById(R.id.editTextProductId);
imageViewResult = findViewById(R.id.imageViewResult);
buttonGenerate = findViewById(R.id.buttonGenerate);
buttonGenerate.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
buttonGenerate_onClick(view);
}
});
buttonScan = findViewById(R.id.buttonScan);
buttonScan.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
buttonScan_onClick(view);
}
});
}
private void buttonGenerate_onClick(View view) {
try {
String productId = editTextProductId.getText().toString();
Hashtable<EncodeHintType, ErrorCorrectionLevel> hintMap = new Hashtable<EncodeHintType, ErrorCorrectionLevel>();
hintMap.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L);
Writer codeWriter;
codeWriter = new Code128Writer();
BitMatrix byteMatrix = codeWriter.encode(productId, BarcodeFormat.CODE_128,400, 200, hintMap);
int width = byteMatrix.getWidth();
int height = byteMatrix.getHeight();
Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
for (int i = 0; i < width; i++) {
for (int j = 0; j < height; j++) {
bitmap.setPixel(i, j, byteMatrix.get(i, j) ? Color.BLACK : Color.WHITE);
}
}
imageViewResult.setImageBitmap(bitmap);
} catch (Exception e) {
Toast.makeText(getApplicationContext(), e.getMessage(),
Toast.LENGTH_LONG).show();
}
}
private void buttonScan_onClick(View view) {
IntentIntegrator intentIntegrator = new IntentIntegrator(this);
intentIntegrator.setDesiredBarcodeFormats(IntentIntegrator.ALL_CODE_TYPES);
intentIntegrator.setCameraId(0);
intentIntegrator.initiateScan();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
IntentResult intentResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
if (intentResult != null) {
String productId = intentResult.getContents();
Toast.makeText(getApplicationContext(), productId, Toast.LENGTH_LONG).show();
}
}
}
Step 3:
activity_barcode.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:background="#ffffff"
android:orientation="vertical"
tools:ignore="HardcodedText">
<EditText
android:id="#+id/editTextProductId"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:hint="Product Id"
android:inputType="textPersonName" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button
android:id="#+id/buttonGenerate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Generate Barcode" />
<Button
android:id="#+id/buttonScan"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Scan Barcode" />
</LinearLayout>
<ImageView
android:id="#+id/imageViewResult"
android:layout_width="match_parent"
android:layout_height="335dp" />
</LinearLayout>
Please Add this code in MainActivity
Add This Libray in Gradle in Dependancy
compile 'com.journeyapps:zxing-android-embedded:3.3.0#aar'
compile 'me.dm7.barcodescanner:zxing:1.9'
Add jar zbar.jar
public class MainActivity extends AppCompatActivity implements ZXingScannerView.ResultHandler {
ZXingScannerView mScannerView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
QCscanner = (Button) findViewById(R.id.QCscanner);
mScannerView = new ZXingScannerView(this);
QCscanner.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try {
/*Intent intent = new Intent("com.google.zxing.client.android.SCAN");
intent.putExtra("SCAN_MODE", "QR_CODE_MODE");
startActivityForResult(intent, 0);*/
mScannerView = new ZXingScannerView(MainActivity.this); // Programmatically initialize the scanner view<br />
setContentView(mScannerView);
mScannerView.setResultHandler(MainActivity.this); // Register ourselves as a handler for scan results.<br />
mScannerView.startCamera();
} catch (Exception ex) {
ex.printStackTrace();
}
}
});
}
#Override
public void handleResult(Result result) {
Log.e("", result.getText()); // Prints scan results<br />
Log.e("", result.getBarcodeFormat().toString());
Toast.makeText(MainActivity.this, "" + result.getText() + "\n" + result.getBarcodeFormat().toString(), Toast.LENGTH_SHORT).show();
}
}
ZXING library allows you to launch an intent(activity) to scan barcodes. If you wants to make changes in that you have to make changes in CaptureActivity of ZXING lib.
Also, now since Google has included scanning feature in its playservices you can use Vision api for scanning in a fragment without integration of any third party library. https://github.com/googlesamples/android-vision/tree/master/visionSamples
Please use
https://github.com/journeyapps/zxing-android-embedded
Just include Scanner view and remove scan paddings by adding:
app:zxing_framing_rect_width="200dp"
app:zxing_framing_rect_height="200dp"
attributes.
<com.journeyapps.barcodescanner.DecoratedBarcodeView
android:id="#+id/zxing_barcode_scanner"
android:layout_width="200dp"
android:layout_height="200dp"
android:layout_centerHorizontal="true"
android:layout_marginTop="36dp"
app:zxing_framing_rect_width="200dp"
app:zxing_framing_rect_height="200dp"
app:zxing_preview_scaling_strategy="fitXY"
app:zxing_use_texture_view="false"
/>
try this. (It very simplified example):
First step. Add dependency in build.gradle(module app):
From version 4.x, only Android SDK 24+ is supported by default, and androidx is required.
implementation 'com.journeyapps:zxing-android-embedded:4.2.0'
implementation 'androidx.appcompat:appcompat:1.0.2'
For Android SDK versions < 24, you can downgrade zxing:core to 3.3.0 or earlier for Android 14+ support:
implementation 'com.google.zxing:core:3.3.0'
Second step. Paste DecoratedBarcodeView view in you layout (activity_main.xml in this example):
<?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"
app:layout_behavior="#string/appbar_scrolling_view_behavior">
<com.journeyapps.barcodescanner.DecoratedBarcodeView
android:id="#+id/barcode_scanner"
android:layout_width="match_parent"
android:layout_height="200dp"
android:layout_alignParentTop="true"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.0">
</com.journeyapps.barcodescanner.DecoratedBarcodeView>
<TextView
android:id="#+id/resultTextView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="TextView"
android:textSize="24dp"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/barcode_scanner" />
</androidx.constraintlayout.widget.ConstraintLayout>
Third step. Add this code to MainActivity:
class MainActivity : AppCompatActivity() {
private lateinit var binding: ActivityMainBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
val formats: Collection<BarcodeFormat> = Arrays.asList(BarcodeFormat.QR_CODE, BarcodeFormat.CODE_39)
binding.barcodeScanner.decoderFactory = DefaultDecoderFactory(formats)
binding.barcodeScanner.initializeFromIntent(Intent())
binding.barcodeScanner.decodeContinuous(object : BarcodeCallback {
override fun barcodeResult(result: BarcodeResult?) {
binding.resultTextView.text = result?.result?.text
}
})
}
override fun onResume() {
super.onResume()
binding.barcodeScanner.resume()
}
override fun onPause() {
super.onPause()
binding.barcodeScanner.pause()
}
}
Important! Implements onResume/onPause methods for activate DecoratedBarcodeView view. And don't forget grant Camera permissions for you app!
In this example i use this library:
https://github.com/journeyapps/zxing-android-embedded
Related
Respect my post Im a newbie :) thank you for understanding
sorry for my grammar
This program is to choose from gallery permission and send to second activity. the
permission is allowed is okay it will send it to the second activity...but when i clicked "oks" in the first popup permission and when i "dont allow files access the device" it will run and when i click button "pick " it will stay to and main activity when i click the button "pick"
MainActivity.java
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void buttonGalleryOpen(View view)
{
Intent intent = new Intent(this, gallery_view.class);
startActivity(intent);
}
}
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:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:id="#+id/textview1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="camera sample"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/textview1"
android:layout_marginTop="3dp">
<Button
android:id="#+id/button_pick"
android:layout_width="100dp"
android:layout_height="50dp"
android:layout_marginTop="30dp"
android:gravity="center"
android:onClick="buttonGalleryOpen"
android:text="pick" />
</RelativeLayout>
</RelativeLayout>
gallery_view.java
public class gallery_view extends AppCompatActivity {
private int STORAGE_PERMISSION_CODE = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_gallery_view);
if (ContextCompat.checkSelfPermission(gallery_view.this,
Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
Intent intent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
//noinspection deprecation
startActivityForResult(intent, 3);
} else {
requestStoragePermission();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK && data != null) {
Uri selectedImage = data.getData();
ImageView imageView = findViewById(R.id.imageviewfromgallery);
imageView.setImageURI(selectedImage);
} else {
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
}
}
private void requestStoragePermission() {
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.READ_EXTERNAL_STORAGE)) {
new AlertDialog.Builder(this)
.setTitle("Permission needed")
.setMessage("This permission is needed because of this and that")
.setPositiveButton("oks", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
ActivityCompat.requestPermissions(gallery_view.this, new
String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, STORAGE_PERMISSION_CODE);
}
})
.setNegativeButton("cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int i) {
dialog.dismiss();
}
})
.create().show();
} else {
Intent intent = new Intent(this, MainActivity.class);
startActivity(intent);
}
}
}
activity_gallery_view.xml
<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=".MainActivity">
<RelativeLayout
android:id="#+id/relative_1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="camera sample"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</RelativeLayout>
<RelativeLayout
android:layout_below="#id/relative_1"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<ImageView
android:id="#+id/imageviewfromgallery"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</RelativeLayout>
</RelativeLayout>
Check official documentation here https://developer.android.com/training/permissions/requesting#java
Also, after user disabled permission dialog,try to send user to app settings to enable it manually.
Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS); Uri uri = Uri.fromParts("package", getPackageName(), null); intent.setData(uri); startActivityForResult(intent, REQUEST_PERMISSION_SETTING);
I have a problem on getting my imageview button to work onclick. what im trying to do is to make the first image invisible so that the second one behind it can appear and at the same time define int special based on what image that has been clicked.
public class TrainingActivity extends AppCompatActivity implements View.OnClickListener {
public static int special;
public static ImageView a12,b13,a12a,b13a;
#Override
protected void onCreate(Bundle savedInstanceState) {
////////////////////////////////////////////////////////////////////////
super.onCreate(savedInstanceState);
setContentView(R.layout.home_page);
a12 = (ImageView) findViewById(R.id.young);
b13 = (ImageView) findViewById(R.id.old);
a12a = (ImageView) findViewById(R.id.young2);
b13a = (ImageView) findViewById(R.id.old2);
a12.setOnClickListener(this);
b13.setOnClickListener(this);
a12a.setOnClickListener(this);
b13a.setOnClickListener(this);
}
#Override
public void onClick(View v) {
if (v.getId() == R.id.young) {
a12.setVisibility(View.GONE);
a12a.setVisibility(View.VISIBLE);
special =0;
} else {
a12.setVisibility(View.VISIBLE);
a12a.setVisibility(View.GONE);
}
if (v.getId() == R.id.old) {
b13.setVisibility(View.GONE);
b13a.setVisibility(View.VISIBLE);
special =1;
} else {
b13.setVisibility(View.VISIBLE);
b13a.setVisibility(View.GONE);
}
}
this is my main class file. I've had already tried this codes in a new project and it works there but somehow doesn't here.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:aapt="http://schemas.android.com/aapt"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
xmlns:tools="http://schemas.android.com/tools"
android:background="#color/gray_color"
tools:context="com.codestudioapps.cardioexcercise.WalkandStep.activities.TrainingActivity">
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageButton
android:id="#+id/young2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="35dp"
android:layout_gravity="center_horizontal|left|center_vertical"
android:src="#drawable/img_body_surface_area1"
/>
<ImageButton
android:id="#+id/young"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="35dp"
android:layout_gravity="center_horizontal|left|center_vertical"
android:src="#drawable/img_body_surface_area" />
<ImageButton
android:id="#+id/old2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="35dp"
android:layout_gravity="center_horizontal|right|center_vertical"
android:src="#drawable/img_body_fat1"
/>
<ImageButton
android:id="#+id/old"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="35dp"
android:layout_gravity="center_horizontal|right|center_vertical"
android:src="#drawable/img_body_fat" />
</FrameLayout>
</androidx.cardview.widget.CardView>
</RelativeLayout>
And this is the layout. The problem might happen because of my manifest file but im unsure. Does anyone have any ideas?
Your code seems okay. Just, casting problem i.e. ImageButton to ImageView.
Your code should be as follows:
public class DemoActivity extends AppCompatActivity implements View.OnClickListener {
public static int special;
public static ImageButton a12, b13, a12a, b13a;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_demo);
a12 = findViewById(R.id.young);
b13 = findViewById(R.id.old);
a12a = findViewById(R.id.young2);
b13a = findViewById(R.id.old2);
a12.setOnClickListener(this);
b13.setOnClickListener(this);
a12a.setOnClickListener(this);
b13a.setOnClickListener(this);
}
#Override
public void onClick(View v) {
if (v.getId() == R.id.young) {
a12.setVisibility(View.GONE);
a12a.setVisibility(View.VISIBLE);
special = 0;
} else {
a12.setVisibility(View.VISIBLE);
a12a.setVisibility(View.GONE);
}
if (v.getId() == R.id.old) {
b13.setVisibility(View.GONE);
b13a.setVisibility(View.VISIBLE);
special = 1;
} else {
b13.setVisibility(View.VISIBLE);
b13a.setVisibility(View.GONE);
}
}
}
These two codes below are in the same MainActivity, in my Android Studio project
1) Recoding the audio from smartphone and playing it when pressing Play button:
public class Main2Activity extends AppCompatActivity {
//Declare variables
Button btnRecord, btnStopRecord, btnPlay, btnStop;
//String pathSave ="";
private static String pathSave;
MediaRecorder mediaRecorder;
MediaPlayer mediaPlayer;
final int REQUEST_PERMISSION_CODE=1000;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
//Request Runtime permission
if(!checkPermissionFromDevice()){
requestPermission();
}
//Init View
btnPlay = (Button) findViewById(R.id.btnPlay);
btnRecord = (Button) findViewById(R.id.btnStartRecord);
btnStop = (Button) findViewById(R.id.btnStop);
btnStopRecord = (Button) findViewById(R.id.btnStopRecord);
btnRecord.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick (View view){
if (checkPermissionFromDevice())
{
pathSave = Environment.getExternalStorageDirectory().getAbsolutePath()+"/"+ UUID.randomUUID().toString()+"audio_record.3gp";
setupMediaRecorder();
try{
mediaRecorder.prepare();
mediaRecorder.start();
} catch (IOException e){
e.printStackTrace();
}
btnPlay.setEnabled(false);
btnStop.setEnabled(false);
Toast.makeText(Main2Activity.this, "Recording...", Toast.LENGTH_SHORT).show();
}
else{
requestPermission();
}
}
});
btnStopRecord.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
mediaRecorder.stop();
btnStopRecord.setEnabled(false);
btnPlay.setEnabled(true);
btnRecord.setEnabled(true);
btnStop.setEnabled(false);
}
});
btnPlay.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
btnStop.setEnabled(true);
btnStopRecord.setEnabled(false);
btnRecord.setEnabled(false);
mediaPlayer = new MediaPlayer();
try{
mediaPlayer.setDataSource(pathSave);
mediaPlayer.prepare();
} catch (IOException e){
e.printStackTrace();
}
mediaPlayer.start();
Toast.makeText(Main2Activity.this, "Playing...", Toast.LENGTH_SHORT).show();
}
});
btnStop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
btnStopRecord.setEnabled(false);
btnRecord.setEnabled(true);
btnStop.setEnabled(false);
btnPlay.setEnabled(true);
if (mediaPlayer != null){
mediaPlayer.stop();
mediaPlayer.release();
setupMediaRecorder();
}
}
});
}
private void setupMediaRecorder(){
mediaRecorder = new MediaRecorder();
mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
mediaRecorder.setAudioEncoder(MediaRecorder.OutputFormat.AMR_NB);
mediaRecorder.setOutputFile(pathSave);
}
private void requestPermission() {
ActivityCompat.requestPermissions(this, new String[]{
Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.RECORD_AUDIO
} ,REQUEST_PERMISSION_CODE);
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
switch (requestCode)
{
case REQUEST_PERMISSION_CODE:
{
if(grantResults.length>0 && grantResults[0]== PackageManager.PERMISSION_GRANTED) {
Toast.makeText(this, "Permission Granted", Toast.LENGTH_SHORT).show();
}
else {
Toast.makeText( this, "Permission Denied", Toast.LENGTH_SHORT).show();
}
}
break;
}
}
private boolean checkPermissionFromDevice(){
int write_external_storage_result = ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE);
int record_audio_result = ContextCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO);
return write_external_storage_result == PackageManager.PERMISSION_GRANTED &&
record_audio_result == PackageManager.PERMISSION_GRANTED;
}
2) Saving the directory where the audio file is created and converting it to a vector:
String path = Environment.getExternalStorageDirectory().getAbsolutePath()+"/"+UUID.randomUUID().toString()+"audio_record.3gp";
public byte[] convert(String path) throws IOException {
FileInputStream fis = new FileInputStream(path);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] b = new byte[1024];
for (int readNum; (readNum = fis.read(b)) != -1; ) {
bos.write(b, 0, readNum);
}
byte[] bytes = bos.toByteArray();
return bytes;
}
Problems
Build Output:
Build: build failed
AAPT errors: (1 error)
Android resource linking failed
Example of error messages: (1) AAPT: C:\Users\cmorais.gradle\caches\transforms-2\files-2.1\cb634fe4b4d1fdfcd5255e485d30a0c1\material-1.0.0\res\anim-v21\design_bottom_sheet_slide_in.xml:17: error: resource integer/bottom_sheet_slide_duration (aka com.example.appsom:integer/bottom_sheet_slide_duration) not found. (2) C:\Users\cmorais.gradle\caches\transforms-2\files-2.1\cb634fe4b4d1fdfcd5255e485d30a0c1\material-1.0.0\res\anim-v21\design_bottom_sheet_slide_out.xml:17: error: resource integer/bottom_sheet_slide_duration (aka com.example.appsom:integer/bottom_sheet_slide_duration) not found. – moraiscarolinav 2 days ago
(3) C:\Users\cmorais.gradle\caches\transforms-2\files-2.1\cb634fe4b4d1fdfcd5255e485d30a0c1\material-1.0.0\res\animator-v21\design_appbar_state_list_animator.xml:19: error: attribute state_liftable (aka com.example.appsom:state_liftable) not found. (4) C:\Users\cmorais.gradle\caches\transforms-2\files-2.1\cb634fe4b4d1fdfcd5255e485d30a0c1\material-1.0.0\res\animator-v21\design_appbar_state_list_animator.xml:19: error: attribute state_lifted (aka com.example.appsom:state_lifted) not found. ... The project has (20) error messages with "not found" at the end.
3) My MainActivity XML file (Text):
<?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"
android:background="#color/maxwellBackground"
android:orientation="vertical"
tools:context=".MainActivity">
<Button
android:id="#+id/btnStartRecord"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="60dp"
android:background="#FC9B03"
android:text="#string/button_start"
android:textColor="#android:color/background_light"
android:textStyle="bold"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/textView2" />
<Button
android:id="#+id/btnStopRecord"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="55dp"
android:background="#FC9B03"
android:text="#string/button_stop"
android:textColor="#android:color/background_light"
android:textStyle="bold"
app:layout_constraintBottom_toTopOf="#+id/textView3"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/btnStartRecord"
app:layout_constraintVertical_bias="0.161" />
<Button
android:id="#+id/btnPlay"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#color/ColorYellow"
android:text="#string/button_play"
android:textColor="#android:color/background_light"
android:textStyle="bold"
app:layout_constraintBottom_toTopOf="#+id/btnStop"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.507"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/textView3"
app:layout_constraintVertical_bias="0.504" />
<Button
android:id="#+id/btnStop"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="128dp"
android:background="#color/ColorYellow"
android:text="#string/button_stop_play"
android:textColor="#android:color/background_light"
android:textStyle="bold"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.507"
app:layout_constraintStart_toStartOf="parent" />
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/record_area"
android:textColor="#android:color/background_light"
android:textSize="24sp"
android:textStyle="bold"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.088" />
<TextView
android:id="#+id/textView3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/play_area"
android:textColor="#android:color/background_light"
android:textSize="24sp"
android:textStyle="bold"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.498"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.573" />
</androidx.constraintlayout.widget.ConstraintLayout>
Buttons associated (XML Design)
[https://i.stack.imgur.com/uiO6F.png][1]
the is not file or resource named com.example.appsom:integer/bottom_sheet_slide_duration).
Create integers.xml file in your project's \res\values folder. In the file create your integer:
<resources>
<integer name="bottom_sheet_slide_duration">value</integer></resources>
I am new to Android Programming. I successfully integrated the Google sign-in and successful in Passing data to another Activity. But When I am going back to the activity through the navigation drawer where I passed the data it sowing empty screen. I Want to Save user Profile in that Activity. I want to save user details by clicking the save button permanently in the app to show as a user profile. Please help me in solving this Problem. Thanks, in Advance for the Solution.
Here are my java files and XML files.
activity_main3.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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_main3"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".Main3Activity">
<LinearLayout
android:id="#+id/prof_section"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:layout_marginTop="50dp"
android:orientation="horizontal">
<ImageView
android:id="#+id/prof_pic"
android:layout_width="90dp"
android:layout_height="125dp"
android:src="#drawable/profilep" />
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="28dp"
android:layout_marginTop="20dp"
android:orientation="vertical">
<TextView
android:id="#+id/name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="Disply Name Here"
android:textSize="18dp"
android:textStyle="bold" />
<TextView
android:id="#+id/email"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:gravity="center"
android:text="Disply Email Here"
android:textSize="18dp"
android:textStyle="bold" />
<Button
android:id="#+id/butn_logout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Logout"
/>
</LinearLayout>
</LinearLayout>
<com.google.android.gms.common.SignInButton
android:id="#+id/butn_login"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="50dp"
android:layout_marginRight="50dp"
android:layout_marginTop="60dp" >
</com.google.android.gms.common.SignInButton>
activity_detail.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: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=".Detail">
<ImageView
android:id="#+id/dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="10dp" />
<TextView
android:id="#+id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="10dp" />
<TextView
android:id="#+id/email"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="10dp" />
<Button
android:id="#+id/button_save"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="SAVE" />
Detail.Java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail);
dp = (ImageView) findViewById(R.id.dp);
name = (TextView) findViewById(R.id.name);
email = (TextView) findViewById(R.id.email);
Intent i = getIntent();
final String i_name, i_email, i_url;
i_name = i.getStringExtra("p_name");
i_email = i.getStringExtra("p_email");
i_url = i.getStringExtra("p_url");
name.setText(i_name);
email.setText(i_email);
new Thread(new Runnable() {
#Override
public void run() {
try {
URL url = new URL(i_url);
InputStream is = url.openConnection().getInputStream();
final Bitmap bmp = BitmapFactory.decodeStream(is);
runOnUiThread(new Runnable() {
#Override
public void run() {
dp.setImageBitmap(bmp);
}
});
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
}
Main3Activity.Java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main3);
preferenceConfig = new SharedPreferenceConfig(getApplicationContext());
if (preferenceConfig.readLoginStatus()) {
startActivity(new Intent(this, Main2Activity.class));
finish();
}
Prof_Section = (LinearLayout) findViewById(R.id.prof_section);
SignOut = (Button) findViewById(R.id.butn_logout);
SignIn = (SignInButton) findViewById(R.id.butn_login);
Name = (TextView) findViewById(R.id.name);
Email = (TextView) findViewById(R.id.email);
Prof_Pic = (ImageView) findViewById(R.id.prof_pic);
SignIn.setOnClickListener(this);
SignOut.setOnClickListener(this);
Prof_Section.setVisibility(View.GONE);
GoogleSignInOptions signInOptions = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN).requestEmail().requestProfile().build();
googleApiClient = new GoogleApiClient.Builder(this).enableAutoManage(this, this).addApi(Auth.GOOGLE_SIGN_IN_API, signInOptions).build();
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.butn_login:
signIn();
break;
case R.id.butn_logout:
signOut();
break;
}
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
}
private void signIn() {
Intent intent = Auth.GoogleSignInApi.getSignInIntent(googleApiClient);
startActivityForResult(intent, REQ_CODE);
}
private void signOut() {
Auth.GoogleSignInApi.signOut(googleApiClient).setResultCallback(new ResultCallback<Status>() {
#Override
public void onResult(#NonNull Status status) {
updateUI(false);
}
});
}
private void updateUI(boolean isLogin) {
if (isLogin) {
Prof_Section.setVisibility(View.VISIBLE);
SignIn.setVisibility(View.GONE);
} else {
Prof_Section.setVisibility(View.GONE);
SignIn.setVisibility(View.VISIBLE);
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQ_CODE) {
GoogleSignInResult googleSignInResult = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
GoogleSignInAccount account = googleSignInResult.getSignInAccount();
String name = account.getDisplayName();
String email = account.getEmail();
String img_url = account.getPhotoUrl().toString();
Name.setText(name);
Email.setText(email);
Glide.with(this).load(img_url).into(Prof_Pic);
updateUI(true);
preferenceConfig.writeLoginStatus(true);
try {
Intent sendData = new Intent(Main3Activity.this, Detail.class);
name = account.getDisplayName();
email = account.getEmail();
img_url = account.getPhotoUrl().toString();
sendData.putExtra("p_name", name);
sendData.putExtra("p_email", email);
sendData.putExtra("p_url", img_url);
startActivity(sendData);
} catch (Exception e) {
Toast.makeText(Main3Activity.this, e.getMessage(), Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(Main3Activity.this, "Login Failed", Toast.LENGTH_SHORT).show();
}
}
Use shared preferences for your purpose. You can read more about it here.
An example is provided here sharedPreferences
I making an app which you can use to start other apps like Netflix on. I have four imagebuttons on the first XML file which is going to be the "Favorites". When you click on any of these imagebuttons you start the intent for the app you wanted to start. Then the app gets opened. How can I make it so that the Favorites changes automatically after what the user uses.
Here is my Java Code:
package com.carlo_projekt.tvprograms;
import android.app.AlertDialog;
import android.content.ActivityNotFoundException;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.speech.RecognizerIntent;
import android.speech.tts.TextToSpeech;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Locale;
' public class MainActivity extends AppCompatActivity {
ImageButton speakBtn;
Button CategoriesBtn;
TextView text;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
speakBtn = (ImageButton) findViewById(R.id.SpeakImageBtn);
CategoriesBtn = (Button) findViewById(R.id.CategoriesBtn);
text = (TextView) findViewById(R.id.textView);
}
public void OpenGame(View view) {
Intent intent = new Intent(this, MoreActivity.class);
startActivity(intent);
}
public void Speak(View view)
{
Intent recognizeIntent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
recognizeIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
recognizeIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, "en-US");
recognizeIntent.putExtra(RecognizerIntent.EXTRA_PROMPT, "Hi! Which app do you want to start?");
try {
startActivityForResult(recognizeIntent, 1);
}
catch (ActivityNotFoundException a)
{
Toast.makeText(MainActivity.this, "Sorry! Your device doesn't support this function!", Toast.LENGTH_LONG).show();
}
}
public void onActivityResult(int request_Code, int result_Code, Intent recognizeIntent)
{
super.onActivityResult(request_Code, result_Code, recognizeIntent);
switch (request_Code)
{
case 1: if(result_Code == RESULT_OK && recognizeIntent != null)
{
ArrayList<String> result = recognizeIntent.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
for(int i = 0; i<result.size(); i++)
{
result.set(i, result.get(i).toLowerCase());
if(result.get(i).compareTo("start netflix") == 0)
{
Intent NetflixIntent = getPackageManager().getLaunchIntentForPackage("com.netflix.mediaclient");
startActivity(NetflixIntent);
}
else if(result.get(i).compareTo("start youtube") == 0)
{
Intent NetflixIntent = getPackageManager().getLaunchIntentForPackage("com.google.android.youtube");
startActivity(NetflixIntent);
}
else if(result.get(i).compareTo("start viafree") == 0)
{
Intent NetflixIntent = getPackageManager().getLaunchIntentForPackage("se.viafree.android");
startActivity(NetflixIntent);
}
else if(result.get(i).compareTo("start tvfour") == 0)
{
Intent NetflixIntent = getPackageManager().getLaunchIntentForPackage("se.tv4.tv4playtab");
startActivity(NetflixIntent);
}
else if(result.get(i).compareTo("start dplay") == 0)
{
Intent NetflixIntent = getPackageManager().getLaunchIntentForPackage("se.kanal5play");
startActivity(NetflixIntent);
}
else if(result.get(i).compareTo("start viaplay") == 0)
{
Intent NetflixIntent = getPackageManager().getLaunchIntentForPackage("com.viaplay.android");
startActivity(NetflixIntent);
}
else if(result.get(i).compareTo("start svtplay") == 0)
{
Intent NetflixIntent = getPackageManager().getLaunchIntentForPackage("se.svt.android.svtplay");
startActivity(NetflixIntent);
}
/**text.setText(result.get(i));*/
}
}
}
}
public void OpenApps(String packageName)
{
if(getPackageManager().getLaunchIntentForPackage(packageName) != null)
{
Intent tv4PlayIntent = getPackageManager().getLaunchIntentForPackage(packageName);
startActivity(tv4PlayIntent);
}
else
{
String marketAppPackageName = "market://details?id="+ packageName;
MessageBox(marketAppPackageName);
}
}
public void NetflixFunction(View view)
{
String netflixPackageName = new String("com.netflix.mediaclient");
OpenApps(netflixPackageName);
}
public void ViafreeFunction(View view)
{
String viafreePackageName = new String("se.viafree.android");
OpenApps(viafreePackageName);
}
public void YoutubeFunction(View view)
{
String youtubePackageName = new String("com.google.android.youtube");
OpenApps(youtubePackageName);
}
public void Tv4PlayFunction(View view)
{
String tv4playPackageName = new String("se.tv4.tv4playtab");
OpenApps(tv4playPackageName);
}
public void LayoutsShow(View view)
{
RelativeLayout layoutShow = findViewById(R.id.LayoutShow);
if (layoutShow.getVisibility() == View.GONE) {
layoutShow.setVisibility(View.VISIBLE);
}
else if (layoutShow.getVisibility() == View.VISIBLE) {
layoutShow.setVisibility(View.GONE);
}
}
public void MessageBox(final String uriIntent)
{
AlertDialog alertDialog = new AlertDialog.Builder(MainActivity.this).create();
alertDialog.setTitle("Couldn't find this app");
String messageText = "We cant find this app, do you want to download it?";
alertDialog.setMessage(messageText);
alertDialog.setButton(AlertDialog.BUTTON_NEGATIVE, "Yes",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent MarketIntent = new Intent(Intent.ACTION_VIEW);
MarketIntent.setData(Uri.parse(uriIntent));
startActivity(MarketIntent);
dialog.dismiss();
}
});
alertDialog.setButton(AlertDialog.BUTTON_POSITIVE, "No",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
alertDialog.show();
}}
This is my XML Code:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.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"
android:background="#color/backgroundColor"
tools:context="com.carlo_projekt.tvprograms.MainActivity">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:ignore="MissingConstraints"
tools:layout_editor_absoluteX="0dp"
tools:layout_editor_absoluteY="0dp">
<Button
android:id="#+id/CategoriesBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="56dp"
android:background="#drawable/round_corners"
android:onClick="OpenGame"
android:text="Categories"
android:textAllCaps="false" />
<ImageButton
android:id="#+id/NetflixImageBtn"
android:layout_width="90dp"
android:layout_height="90dp"
android:layout_centerVertical="true"
android:layout_toStartOf="#+id/CategoriesBtn"
android:onClick="NetflixFunction"
app:srcCompat="#drawable/netflix" />
<ImageButton
android:id="#+id/YoutubeImageBtn"
android:layout_width="90dp"
android:layout_height="90dp"
android:layout_alignTop="#+id/NetflixImageBtn"
android:layout_toEndOf="#+id/CategoriesBtn"
android:onClick="YoutubeFunction"
app:srcCompat="#drawable/youtube" />
<ImageButton
android:id="#+id/ViafreeImageBtn"
android:layout_width="90dp"
android:layout_height="90dp"
android:layout_alignStart="#+id/NetflixImageBtn"
android:layout_below="#+id/NetflixImageBtn"
android:layout_marginTop="52dp"
android:onClick="ViafreeFunction"
app:srcCompat="#drawable/viafree" />
<ImageButton
android:id="#+id/Tv4PlayImageBtn"
android:layout_width="90dp"
android:layout_height="90dp"
android:layout_alignEnd="#+id/YoutubeImageBtn"
android:layout_alignTop="#+id/ViafreeImageBtn"
android:onClick="Tv4PlayFunction"
app:srcCompat="#drawable/tv4" />
<ImageButton
android:id="#+id/SpeakImageBtn"
android:layout_width="40dp"
android:layout_height="60dp"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:onClick="Speak"
app:srcCompat="#drawable/microphone" />
<ImageButton
android:id="#+id/imageButton19"
android:layout_width="40dp"
android:layout_height="20dp"
android:layout_alignParentEnd="true"
app:srcCompat="#drawable/sweden" />
<ImageButton
android:id="#+id/imageButton24"
android:layout_width="40dp"
android:layout_height="20dp"
android:layout_alignParentEnd="true"
android:layout_below="#+id/imageButton19"
app:srcCompat="#drawable/great_britain" />
<ImageButton
android:id="#+id/imageButton22"
android:layout_width="40dp"
android:layout_height="20dp"
android:layout_alignParentEnd="true"
android:layout_below="#+id/imageButton24"
app:srcCompat="#drawable/germany" />
<ImageButton
android:id="#+id/imageButton23"
android:layout_width="40dp"
android:layout_height="20dp"
android:layout_alignParentEnd="true"
android:layout_below="#+id/imageButton22"
app:srcCompat="#drawable/france" />
<ImageButton
android:id="#+id/imageButton25"
android:layout_width="40dp"
android:layout_height="20dp"
android:layout_alignParentEnd="true"
android:layout_below="#+id/imageButton23"
app:srcCompat="#drawable/spanish" />
<TextView
android:id="#+id/textView"
android:layout_width="193dp"
android:layout_height="33dp"
android:layout_alignParentBottom="true"
android:layout_alignParentEnd="true"
android:layout_marginBottom="217dp"
android:layout_marginEnd="90dp"
android:text="TextView"
android:textColor="#ff00" />
</RelativeLayout>
</android.support.constraint.ConstraintLayout>
`
I'm pretty new with stack overflow so I hope you understand what I'm trying to do.
Get SharedPreferences object:
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
Create a click listener that will update the click count for the appropriate button:
View.OnClickListener myClickListener= new View.OnClickListener() {
public void onClick(View v) {
String tag = (String) v.getTag();
sharedPref
.edit()
.putInt(tag, shardPref.getInteger(tag) + 1)
.apply();
}
};
Now for each of your buttons, you will want to set both the click listener and a tag for naming purposes:
Button btn = findViewById(R.id.NetflixImageBtn);
btn.setTag("netflix");
btn.setOnClickListener(myClickListener);
Now when you click a button, it will increment the count associated with the tag. You can use that information however you wish.