I have an app that runs a basic TicTacToe game, stores leaderboard data and saves it to a file. This functionality is all split up across various java files. The TicTacToe game is stored in its own java file/activity. It takes in the username that is set from another activity.
I have to make the game run using AsyncTask. I've implemented the methods and tried passing them void and then calling the game methods from inside the onPreExecute doInBackground and onPostExecute but I cant get it to work properly. I also get errors when passing void as an argument for AsyncTask class.
How can I call the methods inside the AsyncTask to make the game playable?
Included is the full source code for the game, it is fully functional.
PlayGameActivity
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.StreamCorruptedException;
import java.util.HashMap;
import java.util.Map;
public class PlayGameActivity extends AppCompatActivity implements View.OnClickListener {
private Button[][] buttons = new Button[3][3];
private boolean player1Turn = true;
private int roundCount;
private int player1Points;
private int player2Points;
private TextView textViewPlayer1;
private TextView textViewPlayer2;
//MainMenuActivity MMA = new MainMenuActivity();
public String subFolder = "/userdata";
public String file = "test.ser";
Map<String, Integer> userList = new HashMap<>();
String inputName;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_play_game);
SharedPreferences result = getSharedPreferences("PREFS", MODE_PRIVATE);
inputName = result.getString("username", "");
textViewPlayer1 = findViewById(R.id.text_view_p1);
textViewPlayer2 = findViewById(R.id.text_view_p2);
textViewPlayer1.setText(inputName +":");
textViewPlayer2.setText("Android:");
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
String buttonID = "button_" + i + j;
int resID = getResources().getIdentifier(buttonID, "id", getPackageName());
buttons[i][j] = findViewById(resID);
buttons[i][j].setOnClickListener(this);
}
}
Button buttonReset = findViewById(R.id.button_reset);
buttonReset.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
resetGame();
}
});
}
public void startAsyncTask(View v) {
}
//The void arguments are causing issues
private class ExampleAsyncTask extends AsyncTask<void, void, void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void doInBackground(void... voids) {
}
#Override
protected void onPostExecute(void aVoid) {
super.onPostExecute(aVoid);
}
#Override
protected void onProgressUpdate(void... values) {
super.onProgressUpdate(values);
}
}
#Override
public void onClick(View v) {
if (!((Button) v).getText().toString().equals("")) {
return;
}
if (player1Turn) {
((Button) v).setText("X");
} else {
((Button) v).setText("O");
}
roundCount++;
if (checkForWin()) {
if (player1Turn) {
player1Wins();
} else {
player2Wins();
}
} else if (roundCount == 9) {
draw();
} else {
player1Turn = !player1Turn;
}
}
private boolean checkForWin() {
String[][] field = new String[3][3];
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
field[i][j] = buttons[i][j].getText().toString();
}
}
for (int i = 0; i < 3; i++) {
if (field[i][0].equals(field[i][1])
&& field[i][0].equals(field[i][2])
&& !field[i][0].equals("")) {
return true;
}
}
for (int i = 0; i < 3; i++) {
if (field[0][i].equals(field[1][i])
&& field[0][i].equals(field[2][i])
&& !field[0][i].equals("")) {
return true;
}
}
if (field[0][0].equals(field[1][1])
&& field[0][0].equals(field[2][2])
&& !field[0][0].equals("")) {
return true;
}
if (field[0][2].equals(field[1][1])
&& field[0][2].equals(field[2][0])
&& !field[0][2].equals("")) {
return true;
}
return false;
}
public void writeSettings(View v) {
File cacheDir = null;
File appDirectory = null;
if (android.os.Environment.getExternalStorageState().
equals(android.os.Environment.MEDIA_MOUNTED)) {
cacheDir = getApplicationContext().getExternalCacheDir();
appDirectory = new File(cacheDir + subFolder);
} else {
cacheDir = getApplicationContext().getCacheDir();
String BaseFolder = cacheDir.getAbsolutePath();
appDirectory = new File(BaseFolder + subFolder);
}
if (appDirectory != null && !appDirectory.exists()) {
appDirectory.mkdirs();
}
File fileName = new File(appDirectory, file);
FileOutputStream fos = null;
ObjectOutputStream out = null;
try {
fos = new FileOutputStream(fileName);
out = new ObjectOutputStream(fos);
out.writeObject(userList);
} catch (IOException ex) {
ex.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (fos != null)
fos.flush();
fos.close();
if (out != null)
out.flush();
out.close();
} catch (Exception e) {
}
}
}
public void readSettings(String userName) {
File cacheDir = null;
File appDirectory = null;
if (android.os.Environment.getExternalStorageState().
equals(android.os.Environment.MEDIA_MOUNTED)) {
cacheDir = getApplicationContext().getExternalCacheDir();
appDirectory = new File(cacheDir + subFolder);
} else {
cacheDir = getApplicationContext().getCacheDir();
String BaseFolder = cacheDir.getAbsolutePath();
appDirectory = new File(BaseFolder + subFolder);
}
if (appDirectory != null && !appDirectory.exists()) return; // File does not exist
File fileName = new File(appDirectory, file);
FileInputStream fis = null;
ObjectInputStream in = null;
try {
fis = new FileInputStream(fileName);
in = new ObjectInputStream(fis);
Map<String, Integer> myHashMap = (Map<String, Integer>) in.readObject();
userList = myHashMap;
if (userList.containsKey(userName.toLowerCase())) {
int count = userList.containsKey(userName) ? userList.get(userName) : 0;
userList.put(userName, count + 1);
} else {
userList.put(userName.toLowerCase(), 1);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (StreamCorruptedException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (fis != null) {
fis.close();
}
if (in != null) {
in.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
private void player1Wins() {
player1Points++;
readSettings(inputName);
writeSettings(null);
Toast.makeText(this, inputName + " wins!", Toast.LENGTH_SHORT).show();
updatePointsText();
resetBoard();
}
private void player2Wins() {
player2Points++;
readSettings("android");
writeSettings(null);
Toast.makeText(this, "Android wins!", Toast.LENGTH_SHORT).show();
updatePointsText();
resetBoard();
}
private void draw() {
Toast.makeText(this, "Draw!", Toast.LENGTH_SHORT).show();
resetBoard();
}
private void updatePointsText() {
textViewPlayer1.setText(inputName + ": " + player1Points);
textViewPlayer2.setText("Android: " + player2Points);
}
private void resetBoard() {
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
buttons[i][j].setText("");
}
}
roundCount = 0;
player1Turn = true;
}
/*
* Close the activity
* */
private void resetGame() {
// player1Points = 0;
// player2Points = 0;
// updatePointsText();
// resetBoard();
finish();
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt("roundCount", roundCount);
outState.putInt("player1Points", player1Points);
outState.putInt("player2Points", player2Points);
outState.putBoolean("player1Turn", player1Turn);
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
roundCount = savedInstanceState.getInt("roundCount");
player1Points = savedInstanceState.getInt("player1Points");
player2Points = savedInstanceState.getInt("player2Points");
player1Turn = savedInstanceState.getBoolean("player1Turn");
}
}
activity_play_game.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:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.example.tictactoe.PlayGameActivity">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="#+id/text_view_p1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:freezesText="true"
android:text="Player 1: 0"
android:textSize="30sp" />
<TextView
android:id="#+id/text_view_p2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/text_view_p1"
android:freezesText="true"
android:text="Player 2: 0"
android:textSize="30sp" />
<Button
android:id="#+id/button_reset"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_centerVertical="true"
android:layout_marginEnd="33dp"
android:text="reset" />
</RelativeLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1">
<Button
android:id="#+id/button_00"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:freezesText="true"
android:textSize="60sp" />
<Button
android:id="#+id/button_01"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:freezesText="true"
android:textSize="60sp" />
<Button
android:id="#+id/button_02"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:freezesText="true"
android:textSize="60sp" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1">
<Button
android:id="#+id/button_10"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:freezesText="true"
android:textSize="60sp" />
<Button
android:id="#+id/button_11"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:freezesText="true"
android:textSize="60sp" />
<Button
android:id="#+id/button_12"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:freezesText="true"
android:textSize="60sp" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1">
<Button
android:id="#+id/button_20"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:freezesText="true"
android:textSize="60sp" />
<Button
android:id="#+id/button_21"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:freezesText="true"
android:textSize="60sp" />
<Button
android:id="#+id/button_22"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:freezesText="true"
android:textSize="60sp" />
</LinearLayout>
</LinearLayout>
AsyncTask did not accept void as an argument, it is Void :
AsyncTask<Void, Void, Void>
Related
I'm trying to incorporate somehow into Android audio player, functionality of marking of the fragment of the song in the player that it is supposed to play. I see this like clipping of the fragment as in Audacity. I'm trying to get it with a range seekbar (two blue dots on a line that can be adjust) on which user mark the beginning and the end to play and when replay mode is enabled the player will play that marked section over and over again.
It looks like on this image
The application is written in the Java language.
Below are the related code.
Dependency
implementation 'com.yahoo.mobile.client.android.util.rangeseekbar:rangeseekbar-
library:0.1.0'
PlayerActivity.java
package com.example.marcin.playerexperiment;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.database.Cursor;
import android.media.AudioAttributes;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Handler;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import com.yahoo.mobile.client.android.util.rangeseekbar.RangeSeekBar;
import android.widget.Button;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;
import java.io.IOException;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
public class PlayerActivity extends AppCompatActivity {
RangeSeekBar<Integer> mRangeSeekBar;
MediaPlayer mMediaPlayer;
Button playButton, openButton, replayButton;
int max;
SeekBar mSeekBar;
public static final int PICK_FILE =99;
ScheduledExecutorService timer;
TextView title, elapse, mEndTextView;
String duration;
Boolean isRepeat = false;
Runnable mRunnable;
Handler mHandler;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_player);
//otwórz
openButton = findViewById(R.id.open);
//powtórz
replayButton = findViewById(R.id.replayButton);
//range seekbar
mRangeSeekBar = findViewById(R.id.rangeSeekBar);
//seekbar - linia dzwięku
mSeekBar = findViewById(R.id.seekBar);
//mRangeSeekBar.setNotifyWhileDragging(true);
title = (TextView) findViewById(R.id.title);
elapse = (TextView) findViewById(R.id.elapse);
playButton = findViewById(R.id.play);
// mEndTextView = findViewById(R.id.end_duration);
mHandler = new Handler();
//Odtwórz |>
playButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(mMediaPlayer != null){
if(mMediaPlayer.isPlaying()){
mMediaPlayer.pause();
playButton.setText("ODTWÓRZ");
timer.shutdown();
}else{
mMediaPlayer.start();
playButton.setText("PAUZA");
timer = Executors.newScheduledThreadPool(1);
timer.scheduleAtFixedRate(new Runnable() {
#Override
public void run() {
// playProgress ();
if (mMediaPlayer != null) {
if (!mSeekBar.isPressed()) {
mSeekBar.setProgress(mMediaPlayer.getCurrentPosition());
}
}
}
},10,10, TimeUnit.MILLISECONDS);
}
}
}
});
//otwieranie pliku dzwiękowego
openButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(Intent.ACTION_OPEN_DOCUMENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
intent.setType("audio/*");
startActivityForResult(intent, PICK_FILE);
}
});
mRangeSeekBar.setOnRangeSeekBarChangeListener(new RangeSeekBar.OnRangeSeekBarChangeListener<Integer>() {
#Override
public void onRangeSeekBarValuesChanged(RangeSeekBar<?> bar, Integer minValue, Integer maxValue) {
mMediaPlayer.seekTo(minValue);
max = maxValue;
String infoMax = String.valueOf(max);
Log.i("MAX", infoMax);
}
});
mSeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
if (mMediaPlayer != null){
int millis = mMediaPlayer.getCurrentPosition();
long total_secs = TimeUnit.SECONDS.convert(millis, TimeUnit.MILLISECONDS);
long mins = TimeUnit.MINUTES.convert(total_secs, TimeUnit.SECONDS);
long secs = total_secs - (mins*60);
elapse.setText(mins + ":" + secs + " / " + duration);
//Log.i("Duration:", duration);
}
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
if (mMediaPlayer != null) {
mMediaPlayer.seekTo(seekBar.getProgress());
}
}
});
//Loop
replayButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//repeat = false
if(isRepeat){
isRepeat = false;
mMediaPlayer.setLooping(false);
replayButton.setText("Powtórka wyłączona");
Toast.makeText(PlayerActivity.this, "Tryb powtórki jest wyłączony", Toast.LENGTH_SHORT).show();
}else{
isRepeat = true;
mMediaPlayer.setLooping(true);
replayButton.setText("Powtórka włączona");
Toast.makeText(PlayerActivity.this, "Tryb powtórki jest włączony", Toast.LENGTH_SHORT).show();
}
//mediaPlayer.setLooping(true);
// Toast.makeText(PlayerActivity.this, "Repeat if ON", Toast.LENGTH_SHORT).show();
}
});
playButton.setEnabled(false);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_FILE && resultCode == RESULT_OK){
if (data != null){
Uri uri = data.getData();
createMediaPlayer(uri);
}
}
}
public void createMediaPlayer(Uri uri){
mMediaPlayer = new MediaPlayer();
mMediaPlayer.setAudioAttributes(
new AudioAttributes.Builder()
.setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)
.setUsage(AudioAttributes.USAGE_MEDIA)
.build()
);
try {
mMediaPlayer.setDataSource(getApplicationContext(), uri);
mMediaPlayer.prepare();
title.setText(getNameFromUri(uri));
playButton.setEnabled(true);
mRangeSeekBar.setNotifyWhileDragging(true);
mRangeSeekBar.setRangeValues(0, mMediaPlayer.getDuration());
max = mMediaPlayer.getDuration();
mSeekBar.setMax(max);
mSeekBar.setProgress(0);
long total_secs = TimeUnit.SECONDS.convert(max, TimeUnit.MILLISECONDS);
long mins = TimeUnit.MINUTES.convert(total_secs, TimeUnit.SECONDS);
long secs = total_secs - (mins*60);
duration = mins + ":" + secs;
elapse.setText("00:00 / " + duration);
mMediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
releaseMediaPlayer();
}
});
} catch (IOException e){
title.setText(e.toString());
}
}
#SuppressLint("Range")
public String getNameFromUri(Uri uri){
String fileName = "";
Cursor cursor = null;
cursor = getContentResolver().query(uri, new String[]{
MediaStore.Images.ImageColumns.DISPLAY_NAME
}, null, null, null);
if (cursor != null && cursor.moveToFirst()) {
fileName = cursor.getString(cursor.getColumnIndex(MediaStore.Images.ImageColumns.DISPLAY_NAME));
}
if (cursor != null) {
cursor.close();
}
return fileName;
}
private void playProgress () {
if (mMediaPlayer.getCurrentPosition() == max) {
mMediaPlayer.stop();
}
if (mMediaPlayer.isPlaying()) {
mRunnable = new Runnable() {
#Override
public void run() {
playProgress();
}
};
mHandler.postDelayed(mRunnable, 0);
}
}
#Override
protected void onDestroy() {
super.onDestroy();
releaseMediaPlayer();
}
public void releaseMediaPlayer(){
if (timer != null) {
timer.shutdown();
}
if (mMediaPlayer != null) {
mMediaPlayer.release();
mMediaPlayer = null;
}
playButton.setEnabled(false);
elapse.setText("TYTUL");
elapse.setText("00:00 / 00:00");
mSeekBar.setMax(100);
mSeekBar.setProgress(0);
}
}
Activity_player.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"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context=".PlayerActivity">
<Button
android:id="#+id/play"
android:layout_width="wrap_content"
android:layout_height="37dp"
android:layout_marginStart="150dp"
android:layout_marginEnd="173dp"
android:text="Play"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/seekBar" />
<com.yahoo.mobile.client.android.util.rangeseekbar.RangeSeekBar
android:id="#+id/rangeSeekBar"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_marginTop="357dp"
android:layout_marginBottom="20dp"
app:layout_constraintBottom_toTopOf="#+id/seekBar"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<TextView
android:id="#+id/elapse"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="287dp"
android:layout_marginBottom="51dp"
android:text="00-00"
app:layout_constraintBottom_toTopOf="#+id/rangeSeekBar"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.461"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="1.0" />
<SeekBar
android:id="#+id/seekBar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/rangeSeekBar" />
<androidx.constraintlayout.widget.Barrier
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:barrierDirection="top"
tools:layout_editor_absoluteX="92dp"
tools:layout_editor_absoluteY="357dp" />
<Button
android:id="#+id/open"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="154dp"
android:layout_marginEnd="163dp"
android:layout_marginBottom="140dp"
android:backgroundTint="#color/teal_200"
android:text="Open file"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/play" />
<TextView
android:id="#+id/title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="173dp"
android:layout_marginEnd="202dp"
app:layout_constraintBottom_toTopOf="#+id/elapse"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="1.0"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_bias="0.824" />
<Button
android:id="#+id/replayButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="150dp"
android:layout_marginEnd="142dp"
android:backgroundTint="#color/purple_500"
android:text="Replay"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/open" />
</androidx.constraintlayout.widget.ConstraintLayout>
I am developing android project to receive Bluetooth signal from Bluetooth device h6. Then save this data in my application as internally. Now i can get data from device. But trooblr is still i can't save data internally. In this code compile error is being come. I can't understand how solve that error. I am using android studio 3.1.2 and using 27 Api version. My Java cod is
package com.example.randikawann.androidbluetoothh6;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.media.MediaScannerConnection;
import android.os.Handler;
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 java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.util.Set;
import java.util.UUID;
import java.io.FileOutputStream;
import java.io.FileWriter;
public class MainActivity extends AppCompatActivity {
// private final String DEVICE_NAME="MyBTBee";
private final String DEVICE_ADDRESS="20:15:07:27:46:85";
private final UUID PORT_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");//Serial Port Service ID
private static final String TAG = "MyActivity";
private BluetoothDevice device;
private BluetoothSocket socket;
private OutputStream outputStream;
private InputStream inputStream;
Button startButton, sendButton,clearButton,stopButton;
TextView textView;
EditText editText;
boolean deviceConnected=false;
Thread thread;
byte buffer[];
int bufferPosition;
boolean stopThread;
String string;
private static final String FILE_NAME = "example.txt";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
startButton = (Button) findViewById(R.id.buttonStart);
sendButton = (Button) findViewById(R.id.buttonSend);
clearButton = (Button) findViewById(R.id.buttonClear);
stopButton = (Button) findViewById(R.id.buttonStop);
editText = (EditText) findViewById(R.id.editText);
textView = (TextView) findViewById(R.id.textView);
setUiEnabled(false);
}
public void setUiEnabled(boolean bool)
{
startButton.setEnabled(!bool);
sendButton.setEnabled(bool);
stopButton.setEnabled(bool);
textView.setEnabled(bool);
}
public boolean BTinit()
{
boolean found=false;
BluetoothAdapter bluetoothAdapter=BluetoothAdapter.getDefaultAdapter();
if (bluetoothAdapter == null) {
Toast.makeText(getApplicationContext(),"Device doesnt Support Bluetooth",Toast.LENGTH_SHORT).show();
}
if(!bluetoothAdapter.isEnabled())
Toast.makeText(getApplicationContext(),"Bluetooth adapter not anabled",Toast.LENGTH_SHORT).show();
{
Intent enableAdapter = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableAdapter, 0);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
Set<BluetoothDevice> bondedDevices = bluetoothAdapter.getBondedDevices();
Toast.makeText(getApplicationContext(),"find bounded device",Toast.LENGTH_SHORT).show();
if(bondedDevices.isEmpty())
{
Toast.makeText(getApplicationContext(),"Please Pair the Device first",Toast.LENGTH_SHORT).show();
}
else
{
for (BluetoothDevice iterator : bondedDevices)
{
if(iterator.getAddress().equals(DEVICE_ADDRESS))
{
device=iterator;
found=true;
break;
}
}
}
return found;
}
public boolean BTconnect()
{
boolean connected=true;
try {
socket = device.createRfcommSocketToServiceRecord(PORT_UUID);
socket.connect();
} catch (IOException e) {
e.printStackTrace();
connected=false;
}
if(connected)
{
try {
outputStream=socket.getOutputStream();
} catch (IOException e) {
e.printStackTrace();
}
try {
inputStream=socket.getInputStream();
} catch (IOException e) {
e.printStackTrace();
}
}
return connected;
}
public void onClickStart(View view) {
if(BTinit())
{
if(BTconnect())
{
setUiEnabled(true);
deviceConnected=true;
beginListenForData();
textView.append("\nConnection Opened!\n");
}
}
}
void beginListenForData()
{
final Handler handler = new Handler();
stopThread = false;
buffer = new byte[1024];
Thread thread = new Thread(new Runnable()
{
public void run()
{
while(!Thread.currentThread().isInterrupted() && !stopThread) {
try {
int byteCount = inputStream.available();
if (byteCount > 0) {
byte[] rawBytes = new byte[byteCount];
inputStream.read(rawBytes);
string = new String(rawBytes, "UTF-8");
handler.post(new Runnable() {
public void run() {
textView.setText(string);
Log.i(TAG, "***************************" + string);
//store value from file
save();
}
});
}
} catch (IOException ex) {
stopThread = true;
}
}
}
});
thread.start();
}
//Save input value
public void save() {
String text = string;
FileOutputStream fos = null;
try {
fos = openFileOutput(FILE_NAME, MODE_PRIVATE);
fos.write(text.getBytes());
Toast.makeText(this, "Saved to " + getFilesDir() + "/" + FILE_NAME,
Toast.LENGTH_LONG).show();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
//Read saved files
public void load(View v) {
FileInputStream fis = null;
try {
fis = openFileInput(FILE_NAME);
InputStreamReader isr = new InputStreamReader(fis);
BufferedReader br = new BufferedReader(isr);
StringBuilder sb = new StringBuilder();
String text;
while ((text = br.readLine()) != null) {
sb.append(text).append("\n");
}
editText.setText(sb.toString());
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fis != null) {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public void onClickSend(View view) {
String string = editText.getText().toString();
string.concat("\n");
try {
outputStream.write(string.getBytes());
} catch (IOException e) {
e.printStackTrace();
}
textView.append("\nSent Data:"+string+"\n");
}
public void onClickStop(View view) throws IOException {
stopThread = true;
outputStream.close();
inputStream.close();
socket.close();
setUiEnabled(false);
deviceConnected=false;
textView.append("\nConnection Closed!\n");
}
public void onClickClear(View view) {
textView.setText("");
}
}
Also my activity xml file is
<?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:minHeight="14dp"
tools:context=".MainActivity"
tools:layout_editor_absoluteY="81dp">
<EditText
android:id="#+id/editText"
android:layout_width="364dp"
android:layout_height="wrap_content"
android:layout_alignParentEnd="true"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="10dp"
android:layout_marginStart="10dp"
android:layout_marginTop="70dp"
android:inputType=""
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:id="#+id/buttonStart"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_below="#+id/editText"
android:layout_marginLeft="10dp"
android:layout_marginStart="10dp"
android:layout_marginTop="50dp"
android:onClick="onClickStart"
android:text="#string/begin"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/editText"
tools:ignore="OnClick" />
<Button
android:id="#+id/buttonSend"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/editText"
android:layout_marginEnd="196dp"
android:layout_marginLeft="5dp"
android:layout_marginRight="196dp"
android:layout_marginStart="5dp"
android:layout_marginTop="50dp"
android:layout_toEndOf="#+id/buttonStart"
android:layout_toRightOf="#+id/buttonStart"
android:onClick="onClickSend"
android:text="#string/send"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toEndOf="#+id/buttonStart"
app:layout_constraintTop_toBottomOf="#+id/editText"
tools:ignore="OnClick,UnknownId" />
<Button
android:id="#+id/button0Stop"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/editText"
android:layout_marginLeft="5dp"
android:layout_marginStart="5dp"
android:layout_marginTop="50dp"
android:layout_toEndOf="#+id/buttonSend"
android:layout_toRightOf="#+id/buttonSend"
android:onClick="onClickStop"
android:text="#string/stop"
app:layout_constraintStart_toEndOf="#+id/buttonSend"
app:layout_constraintTop_toBottomOf="#+id/editText"
tools:ignore="OnClick" />
<Button
android:id="#+id/buttonClear"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/editText"
android:layout_marginLeft="5dp"
android:layout_marginStart="5dp"
android:layout_marginTop="50dp"
android:onClick="onClickClear"
android:text="#string/clear"
app:layout_constraintStart_toEndOf="#+id/button0Stop"
app:layout_constraintTop_toBottomOf="#+id/editText"
tools:ignore="OnClick" />
<TextView
android:id="#+id/textView"
android:layout_width="183dp"
android:layout_height="111dp"
android:layout_marginEnd="157dp"
android:layout_marginRight="157dp"
android:layout_marginTop="92dp"
android:text="TextView"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintTop_toBottomOf="#+id/buttonStart" />
</android.support.constraint.ConstraintLayout>
and also compile error is . I hope your immidiate answer
About file save, In Android (6.0+), I must be write files in /data directory, only with permission do write (without manifest permissions)
Example:
String directory = "/Android/data/" + getPackageName();
String pathToSave = directory + "/" + FILE_NAME;
About error, I need more details
I have an application where I am recording audio in an activity. User has a start recording and stop recording button to do that. Once user clicks the stop recording button, it sends the recorded mp3 file to server (encoded string) and server process it and a response is received. I want to do the following tasks:
Since this process is long, I want to do this in a separate thread(preferably).
The process of sending and receiving response is to be shown using progress bar.
User should be able to navigate to other screens while he is waiting(i.e. current activity may be destroyed)
I tried using Toast messages before and after the function where I send mp3 to server. But there is no sync, sometimes msg comes early, sometime it's late. That's why a proper progress bar is required.How to do this? Can AsyncTask be used with what I want to achieve in (3). or should I use some other form of multithreading. Please help.Below is the activity
(Please ignore the indentations, I couldn't fix the code on stack-overflow:
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import org.apache.commons.io.FileUtils;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
public class RecordActivity extends AppCompatActivity {
private static final String LOG_TAG = "AudioRecordTest";
private static String msg = "default";
public final static String Result_MESSAGE = "in.innovatehub.ankita_mehta.tinyears.ResultMESSAGE";
private static final int REQUESTCODE_RECORDING = 109201;
private Button mRecorderApp = null;
private static String mFileName = "music.mp3";
private static String mFilePath = String.valueOf(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS + "/TinyEars/"));
private MediaRecorder mRecorder = null;
private MediaPlayer mPlayer = null;
private ImageButton mRecordImageButton = null;
private ImageButton mPlayImageButton = null;
boolean mStartRecording = true;
boolean mStartPlaying = true;
private Button mShowStatsButton = null;
private static final String TAG = "RecordActivity";
private Handler handler = new Handler();
final Runnable updater = new Runnable() {
public void run() {
handler.postDelayed(this, 1);
if(mRecorder!=null) {
int maxAmplitude = mRecorder.getMaxAmplitude();
if (maxAmplitude != 0) {
// visualizerView.addAmplitude(maxAmplitude);
}
}
else{
}
}
};
private void onRecord(boolean start) {
if (start) {
startRecording();
} else {
stopRecording();
}
}
private void onPlay(boolean start) {
if (start) {
startPlaying();
} else {
stopPlaying();
}
}
private void startPlaying() {
mPlayer = new MediaPlayer();
try {
mPlayer.setDataSource(mFilePath+"/"+mFileName);
mPlayer.prepare();
mPlayer.start();
mPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
public void onCompletion(MediaPlayer mp) {
Log.i("Completion Listener", "Song Complete");
stopPlaying();
mRecordImageButton.setEnabled(true);
}
});
} catch (IOException e) {
Log.e(LOG_TAG, "prepare() failed");
}
}
private void stopPlaying() {
if (mPlayer != null) {
mPlayer.reset();
mPlayer.release();
mPlayer = null;
mPlayImageButton.setImageResource(R.drawable.playicon);
// mStartPlaying = true;
} else {
mPlayImageButton.setImageResource(R.drawable.pauseicon);
// mStartPlaying = false;
}
}
private void startRecording() {
AudioRecordTest(String.valueOf(System.currentTimeMillis()));
mRecorder = new MediaRecorder();
mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
mRecorder.setOutputFile(mFilePath+"/"+mFileName);
mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);
try {
mRecorder.prepare();
} catch (IOException e) {
Log.e(LOG_TAG, "prepare() failed");
}
try {
mRecorder.start();
Toast.makeText(getApplicationContext(), "Recording started", Toast.LENGTH_LONG).show();
} catch (Exception e) {
Log.e(LOG_TAG, "start() failed");
}
}
private void stopRecording() {
if (mRecorder != null) {
mRecorder.stop();
mRecorder.release();
Toast.makeText(getApplicationContext(), "Audio recorded successfully",Toast.LENGTH_LONG).show();
mRecorder = null;
mRecordImageButton.setImageResource(R.drawable.micicon);
// mStartRecording = true;
} else {
mRecordImageButton.setImageResource(R.drawable.stopicon);
// mStartRecording = false;
}
}
public void AudioRecordTest(String text) {
boolean exists = (new File(mFilePath+"/"+mFileName)).exists();
if (!exists) {
new File(mFileName).mkdirs();
}
// mFileName += "audiorecordtest.mp3";
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_record);
Log.d(TAG,"HERE IS FILE PATH"+mFilePath+"/"+mFileName);
mRecordImageButton = (ImageButton) findViewById(R.id.imageButton2);
mPlayImageButton = (ImageButton) findViewById(R.id.imageButton3);
mShowStatsButton = (Button) findViewById(R.id.showMeStats);
mRecorderApp = (Button) findViewById(R.id.recorderApp);
AudioRecordTest("00000");
mRecordImageButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on click
onRecord(mStartRecording);
if (mStartRecording) {
mRecordImageButton.setImageResource(R.drawable.stopicon);
mPlayImageButton.setEnabled(false);
//setText("Stop recording");
} else {
mRecordImageButton.setImageResource(R.drawable.micicon);
mPlayImageButton.setEnabled(true);
mShowStatsButton.setEnabled(true);
mShowStatsButton.setVisibility(View.VISIBLE);
Toast.makeText(getApplicationContext(),"Hold on... we are getting the results!",Toast.LENGTH_SHORT).show();
pressedSavBtn();
Toast.makeText(getApplicationContext(),"Parsing done ... now you may see the results!",Toast.LENGTH_SHORT).show();
//setText("Start recording");
}
mStartRecording = !mStartRecording;
}
});
mPlayImageButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on click
onPlay(mStartPlaying);
if (mStartPlaying) {
mPlayImageButton.setImageResource(R.drawable.pauseicon);
mRecordImageButton.setEnabled(false);
mShowStatsButton.setEnabled(false);
//setText("Stop playing");
} else {
mPlayImageButton.setImageResource(R.drawable.playicon);
mRecordImageButton.setEnabled(true);
mShowStatsButton.setEnabled(false);
//setText("Start playing");
}
mStartPlaying = !mStartPlaying;
}
});
//Calling recorder ...
mRecorderApp.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view) {
Intent intent = new Intent(MediaStore.Audio.Media.RECORD_SOUND_ACTION);
if (isAvailable(getApplicationContext(), intent)) {
startActivityForResult(intent, REQUESTCODE_RECORDING);
}
}
});
mShowStatsButton = (Button) findViewById(R.id.showMeStats);
mShowStatsButton.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view) {
sendResults(msg);
}
});
}
public void pressedSavBtn(){
try {
thread.start();
} catch (Exception ex) {
ex.printStackTrace();
} finally {
mShowStatsButton.setVisibility(View.VISIBLE);
}
}
public void writeToFile(String data)
{
// Get the directory for the user's public pictures directory.
final File path = new File(mFilePath+"/");
// Make sure the path directory exists.
if(!path.exists())
{
// Make it, if it doesn't exit
path.mkdirs();
}
final File file = new File(path, "config.txt");
// Save your stream, don't forget to flush() it before closing it.
try
{
file.createNewFile();
FileOutputStream fOut = new FileOutputStream(file);
OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut);
myOutWriter.append(data);
myOutWriter.close();
fOut.flush();
fOut.close();
}
catch (IOException e)
{
Log.e("Exception", "File write failed: " + e.toString());
}
}
private static String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append((line + "\n"));
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
try {
//THIS IS FILE ENCODING CODE
File file = new File(mFilePath+"/"+mFileName);
byte[] bytes = FileUtils.readFileToByteArray(file);
String encoded = Base64.encodeToString(bytes, 0);
Log.d("~~~~~~~~ Encoded: ", encoded);
writeToFile(encoded);
//THIS IS URL CONN CODE
String link = "http://192.168.50.0:9000/divide_result";
URL url = new URL(link);
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(link);
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("Name", "StackOverFlow"));
nameValuePairs.add(new BasicNameValuePair("Date", encoded));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
String sb = convertStreamToString(response.getEntity().getContent());
Log.d(TAG,"MESSAGE NOW"+sb);
Log.d(TAG, sb);
msg = sb.toString();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
} catch (Exception e) {
e.printStackTrace();
}
}
});
public void sendResults(String res){
Log.d(TAG, "Inside on create, Navigating to Result Screen Activity!");
Intent intent = new Intent(getApplicationContext(), ResultsScreenActivity.class);
intent.putExtra(Result_MESSAGE, res);
startActivity(intent);
}
public static boolean isAvailable(Context ctx, Intent intent) {
final PackageManager mgr = ctx.getPackageManager();
List<ResolveInfo> list = mgr.queryIntentActivities(intent,PackageManager.MATCH_DEFAULT_ONLY);
return list.size() > 0;
}
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
if (requestCode == REQUESTCODE_RECORDING) {
if (resultCode == RESULT_OK) {
Uri audioUri = intent.getData();
// make use of this MediaStore uri
// e.g. store it somewhere
}
else {
// react meaningful to problems
}
}
else {
super.onActivityResult(requestCode,
resultCode, intent);
}
}
#Override
public void onPause() {
super.onPause();
if (mRecorder != null) {
mRecorder.release();
mRecorder = null;
}
if (mPlayer != null) {
mPlayer.release();
mPlayer = null;
}
thread.stop();
}
#Override
protected void onDestroy() {
super.onDestroy();
handler.removeCallbacks(updater);
if(mRecorder!=null) {
mRecorder.stop();
mRecorder.reset();
mRecorder.release();
}
}
#Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
handler.post(updater);
}
}
Also below is the layout-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:id="#+id/activity_record"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center|center_horizontal"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:screenOrientation="portrait"
android:orientation="vertical"
tools:context="in.innovatehub.mobile.ankita_mehta.tinyears.RecordActivity">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/linearLayout_record"
android:orientation="vertical"
android:gravity="center">
<ImageButton
android:id="#+id/imageButton2"
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_gravity="center"
android:scaleType="fitXY"
android:src="#drawable/micicon" />
<ImageButton
android:id="#+id/imageButton3"
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_gravity="center"
android:scaleType="fitXY"
android:src="#drawable/playicon" />
<Button
android:id="#+id/showMeStats"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:visibility="gone"
android:onClick="loadStats"
android:text="#string/showMeStats" />
<Button
android:id="#+id/recorderApp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:visibility="invisible"
android:gravity="center"
android:text="#string/UseRecorderApp" />
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/loadStatsLinearLayout"
android:gravity="center"
android:visibility="gone"
android:orientation="vertical">
<TextView
android:id="#+id/loadingMessage"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="#string/loadingMessage"
/>
<ProgressBar
android:id="#+id/downloadProgress"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:indeterminate="true"
/>
</LinearLayout>
</LinearLayout>
You can use an IntentService to upload your content to the server. By default, it runs on a seperate thread and is not activity bound. Then use a broadcast receiver to communicate the result back to any activity. You can find an example here.
For the progress bar, you can create a notification and show the progress bar there, this will not block your application's UI.
For hitting the server at you should use AsyncTask or Runnable thread, without disturb the main tread
for custome progress dialog use the following code
xml file.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:background="#color/color_white"
android:padding="5dp" >
<ProgressBar
android:id="#+id/layCustomContentProgress"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="10dp" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<TextView
android:id="#+id/layCustomProgressHeading"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Medium Text"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/layCustomProgressInfo"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Small Text"
android:textAppearance="?android:attr/textAppearanceSmall" />
</LinearLayout>
</LinearLayout>
and the method
public Dialog getCustomPogressDialog(Context context, String heading, String text) {
// Declare the customer dialog
Dialog dlgProgress = new Dialog(context);
// Set no title for the dialog
dlgProgress.requestWindowFeature(Window.FEATURE_NO_TITLE);
// Set the content view to the customer_alert layout
dlgProgress.setContentView(R.layout.layout_custom_process_progress);
// Cancel the dialog when touched outside.
dlgProgress.setCanceledOnTouchOutside(false);
// Set the main heading
TextView dlgHeading = (TextView) dlgProgress.findViewById(R.id.layCustomProgressHeading);
dlgHeading.setText(heading);
// set the info
TextView dlgInfo = (TextView) dlgProgress.findViewById(R.id.layCustomProgressInfo);
dlgInfo.setText(text);
// Return the refenrece to the dialog
return dlgProgress;
}
My onclicklistener for my "LoginBtn". However that code inside that block only runs once and then doesn't run ever again. Please help me, I've tried everything. I know so because I have ran the log and it only logs out the value once and then never again.
package com.example.jj.test;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.PorterDuff;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.ScaleDrawable;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.AppCompatDrawableManager;
import android.util.Log;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
import com.goebl.david.Webb;
import org.json.JSONException;
import org.json.JSONObject;
public class MainActivity extends AppCompatActivity implements View.OnClickListener{
private static final String TAG = "test";
boolean loginform;
Button Loginbtn;
ImageView logoIV;
String email;
String password;
String token;
EditText emailET;
EditText passwordET;
final Webb webb = Webb.create();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Loginbtn = (Button) findViewById(R.id.loginbtn);
Loginbtn.setOnClickListener(this);
logoIV = (ImageView) findViewById(R.id.logoIV);
emailET = (EditText) findViewById(R.id.emailET);
passwordET = (EditText) findViewById(R.id.passwordET);
loginform = false;
ModifyEditText();
}
public void ModifyEditText(){
Drawable drawable = getResources().getDrawable(R.mipmap.email);
drawable.setBounds(0, 0, (int) (drawable.getIntrinsicWidth() * 0.6),
(int) (drawable.getIntrinsicHeight() * 0.6));
ScaleDrawable sd = new ScaleDrawable(drawable, 0, 40, 40);
emailET.setCompoundDrawables(null, null,sd.getDrawable(), null);
drawable = getResources().getDrawable(R.mipmap.password);
drawable.setBounds(0, 0, (int) (drawable.getIntrinsicWidth() * 0.6),
(int) (drawable.getIntrinsicHeight() * 0.6));
sd = new ScaleDrawable(drawable, 0, 40, 40);
passwordET.setCompoundDrawables(null, null, sd.getDrawable(), null);
final Drawable d = emailET.getBackground();
final Drawable nd = d.getConstantState().newDrawable();
nd.setColorFilter(AppCompatDrawableManager.getPorterDuffColorFilter(
Color.parseColor("#FFFFFF"), PorterDuff.Mode.SRC_IN));
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
emailET.setBackground(nd);
passwordET.setBackground(nd);
}
}
public void startAnimation() {
Loginbtn.setText("Login");
logoIV.startAnimation(AnimationUtils.loadAnimation(this, R.anim.animmovetop));
Loginbtn.startAnimation(AnimationUtils.loadAnimation(this, R.anim.animmovedown));
Animation animFadeIn = AnimationUtils.loadAnimation(this, android.R.anim.fade_in);
emailET.setAnimation(animFadeIn);
passwordET.setAnimation(animFadeIn);
emailET.setVisibility(View.VISIBLE);
passwordET.setVisibility(View.VISIBLE);
Loginbtn.setBackgroundResource(R.drawable.transparentrectangel);
loginform = true;
}
public void LoginRequest(final JSONObject id) throws Exception {
final String testurl = "http://api.dermatrax.com/api/v1/token/generate?email="+email+"&password="+password+;
new AsyncTask<Void, Void, JSONObject>() {
#Override
protected JSONObject doInBackground(Void... params) {
try {
Log.d("TEST","Sending request");
JSONObject response = webb
.post(testurl)
.body(id)
.ensureSuccess()
.readTimeout(4000)
.asJsonObject()
.getBody();
return response;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(JSONObject result) {
if (result != null) {
Log.d("TEST", result.toString());
try {
JSONObject data = result.getJSONObject("data");
token = data.get("token").toString();
Log.d("TEST", token);
if (token != null && !token.isEmpty()) {
Intent intent = new Intent(getApplicationContext(), UserData.class);
intent.putExtra("token", token);
intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
startActivity(intent);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
else{
Toast.makeText(getApplicationContext(),"Wrong email or password",Toast.LENGTH_LONG);
}
}
}.execute().get();
//executeOnExecutor(AsyncTask.SERIAL_EXECUTOR);
}
#Override
public void onClick(View v) {
if(v.getId() == R.id.loginbtn){
Log.d("TEST", "loginform is = " + loginform);
JSONObject params = new JSONObject();
if (loginform == false) {
try {
startAnimation();
//LoginRequest(params);
} catch (Exception e) {
e.printStackTrace();
}
} else if (loginform == true) {
email = emailET.getText().toString();
password = passwordET.getText().toString();
try {
//params.put("email", email);
//params.put("password", password);
params.put("email", "blabla#combustiongroup.com");
params.put("password", "blabla");
LoginRequest(params);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
xml code
<?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="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
tools:context="com.example.jj.test.MainActivity">
<RelativeLayout
android:background="#292446"
android:orientation="vertical"
android:id="#+id/midLL"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<Button
android:padding="10dp"
android:layout_width="300dp"
android:gravity="center"
android:layout_height="40dp"
android:text="Go"
android:id="#+id/loginbtn"
android:textColor="#FFFFFF"
android:background="#drawable/roundbutton"
android:layout_below="#+id/logoIV"
android:layout_centerHorizontal="true" />
<de.hdodenhof.circleimageview.CircleImageView
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/logoIV"
android:src="#mipmap/bigmatchlogo"
android:layout_width="70dp"
android:layout_height="70dp"
app:civ_border_width="2dp"
app:civ_border_color="#d6d6d6"
android:layout_alignBottom="#+id/emailET"
android:layout_centerHorizontal="true"
android:layout_marginBottom="20dp" />
<EditText
android:layout_marginBottom="10dp"
android:textColorHint="#FFFFFF"
android:hint="Email"
android:visibility="invisible"
android:layout_width="300dp"
android:layout_height="wrap_content"
android:inputType="textEmailAddress"
android:ems="10"
android:id="#+id/emailET"
android:layout_marginTop="217dp"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />
<EditText
android:drawableRight="#mipmap/password"
android:hint="Password"
android:textColorHint="#FFFFFF"
android:visibility="invisible"
android:layout_width="300dp"
android:layout_height="50dp"
android:inputType="textPassword"
android:ems="10"
android:layout_marginTop="10dp"
android:id="#+id/passwordET"
android:layout_below="#+id/emailET"
android:layout_alignLeft="#+id/emailET"
android:layout_alignStart="#+id/emailET" />
</RelativeLayout>
</LinearLayout>
Log cat
06-15 15:49:11.898 8631-8631/com.example.jj.test D/TEST: loginform is = false
06-15 15:50:36.598 8631-8631/com.example.jj.test D/szxszxszxszxszx: spannableStringBuilder.......1
06-15 15:50:36.598 8631-8631/com.example.jj.test D/szxszxszx: setSpan start is 0,end is 0,flags is 18boolena is false
Write this code inside onCreate()...
Loginbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(v.getId() == R.id.loginbtn){
Log.d("TEST", "loginform is = " + loginform);
JSONObject params = new JSONObject();
if (loginform == false) {
try {
startAnimation();
//LoginRequest(params);
} catch (Exception e) {
e.printStackTrace();
}
} else if (loginform == true) {
email = emailET.getText().toString();
password = passwordET.getText().toString();
try {
//params.put("email", email);
//params.put("password", password);
params.put("email", "blabla#combustiongroup.com");
params.put("password", "blabla");
LoginRequest(params);
} catch (Exception e) {
e.printStackTrace();
}
}
}
I want to get the location of user in my android application through Facebook login.I implemented login and everything is working fine other than location(Location which user updates in his profile as "Lives in").I retrieved username and id using this.I set permission also.But its not working.Please help me.
Here is my class
public class FacebookActivity extends Activity implements OnClickListener
{
Facebook fb;
//ImageView pic;
CircularImageView pic;
ImageView button;
TextView welcome,location;
SharedPreferences sp;
String APP_ID = "xxxxxxxx";
String name;
String id;
String town;
String currentCity;
String imgurl_check;
Drawable d ;
Bitmap bitmap;
String access_token;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
fb = new Facebook(APP_ID);
sp = getPreferences(MODE_PRIVATE);
access_token = sp.getString("access_token", null);
long expires = sp.getLong("access_expires", 0);
if(access_token !=null)
{
fb.setAccessToken(access_token);
}
if(expires !=0)
{
fb.setAccessExpires(expires);
}
button = (ImageView) findViewById(R.id.login);
welcome = (TextView) findViewById(R.id.name);
location = (TextView) findViewById(R.id.location);
//pic = (ImageView) findViewById(R.id.picture_pic);
pic = (CircularImageView) findViewById(R.id.picture_pic);
button.setOnClickListener(this);
updateButtonImage();
}
private void updateButtonImage()
{
if(fb.isSessionValid())
{
//button.setImageResource(R.drawable.fb_logout);
button.setVisibility(View.INVISIBLE);
new GetProfileName().execute();
new LoadProfileImage(pic)
.execute("https://graph.facebook.com/me/picture?width=200&height=200&method=GET&access_token="
+ access_token);
//pic.setVisibility(View.VISIBLE);
}
else
{
button.setImageResource(R.drawable.fb_login);
welcome.setVisibility(View.INVISIBLE);
pic.setVisibility(View.INVISIBLE);
}
}
private class GetProfileName extends AsyncTask<URL, Integer, Long> {
protected Long doInBackground(URL... urls)
{
JSONObject obj = null;
JSONObject obj1 = null;
URL img_url = null;
String jsonUser;
String jsonPicture;
try {
jsonUser = fb.request("me");
obj = Util.parseJson(jsonUser);
id = obj.optString("id");
name = obj.optString("name");
currentCity = obj.getJSONObject("location").getString("name");
Log.d("Executing thread",id);
Log.d("Executing thread",name);
Log.d("Executing thread",currentCity);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (FacebookError e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
protected void onProgressUpdate(Integer... progress) {
}
protected void onPostExecute(Long result) {
location.setText(currentCity);
location.setVisibility(View.VISIBLE);
welcome.setText(name);
welcome.setVisibility(View.VISIBLE);
sp = getPreferences(MODE_PRIVATE);
final SharedPreferences.Editor editor = sp.edit();
editor.putString("UserName", name);
editor.commit();
}
}
/**
* Background Async task to load user profile picture from url
* */
private class LoadProfileImage extends AsyncTask<String, Void, Bitmap> {
CircularImageView bmImage;
public LoadProfileImage(CircularImageView bmImage) {
this.bmImage = bmImage;
}
protected Bitmap doInBackground(String... urls) {
String urldisplay = urls[0];
Bitmap mIcon11 = null;
try {
InputStream in = new java.net.URL(urldisplay).openStream();
mIcon11 = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return mIcon11;
}
protected void onPostExecute(Bitmap result) {
bmImage.setImageBitmap(result);
pic.setVisibility(View.VISIBLE);
String extr = Environment.getExternalStorageDirectory().toString();
File mFolder = new File(extr + "/App");
if (!mFolder.exists()) {
mFolder.mkdir();
}
String s = "myfile.png";
File f = new File(mFolder.getAbsolutePath(),s);
String strMyImagePath = f.getAbsolutePath();
FileOutputStream fos = null;
try {
fos = new FileOutputStream(f);
result.compress(Bitmap.CompressFormat.PNG,70, fos);
fos.flush();
fos.close();
// MediaStore.Images.Media.insertImage(getContentResolver(), b, "Screen", "screen");
}catch (FileNotFoundException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
#Override
public void onClick(View v)
{
if(fb.isSessionValid())
{
try {
fb.logout(getApplicationContext());
updateButtonImage();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
else
{
//login to fb
fb.authorize(FacebookActivity.this,new String[] {"email","user_hometown","user_location"},new DialogListener() {
#Override
public void onFacebookError(FacebookError e) {
// TODO Auto-generated method stub
Toast.makeText(FacebookActivity.this, "fberror", Toast.LENGTH_SHORT).show();
}
#Override
public void onError(DialogError e) {
// TODO Auto-generated method stub
Toast.makeText(FacebookActivity.this, "onerror", Toast.LENGTH_SHORT).show();
}
#Override
public void onComplete(Bundle values) {
// TODO Auto-generated method stub
Editor editor = sp.edit();
editor.putString("access_token", fb.getAccessToken());
editor.putLong("access_expires", fb.getAccessExpires());
editor.commit();
updateButtonImage();
}
#Override
public void onCancel() {
// TODO Auto-generated method stub
Toast.makeText(FacebookActivity.this, "Oncancel", Toast.LENGTH_SHORT).show();
}
});
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
fb.authorizeCallback(requestCode, resultCode, data);
}
}
Download source code from here:
https://deepshikhapuri.wordpress.com/2017/04/07/get-location-of-facebook-user-using-graph-api-in-android/
Add this dependency:
compile 'com.facebook.android:facebook-android-sdk:4.0.1'
activity_main.xml
<LinearLayout android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
xmlns:android="http://schemas.android.com/apk/res/android">
<ImageView
android:layout_width="100dp"
android:layout_height="100dp"
android:id="#+id/iv_image"
android:layout_marginTop="10dp"
android:layout_marginBottom="10dp"
android:layout_gravity="center_horizontal"
android:src="#drawable/profile"/>
<LinearLayout
android:layout_width="match_parent"
android:orientation="horizontal"
android:layout_height="wrap_content">
<TextView
android:layout_width="100dp"
android:layout_height="40dp"
android:text="Name"
android:gravity="center_vertical"
android:textSize="15dp"
android:textColor="#000000"
android:layout_marginLeft="10dp"
android:layout_marginTop="10dp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="40dp"
android:text="Name"
android:textSize="15dp"
android:id="#+id/tv_name"
android:gravity="center_vertical"
android:textColor="#000000"
android:layout_marginLeft="10dp"
android:layout_marginTop="10dp"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="100dp"
android:layout_height="40dp"
android:text="Email"
android:gravity="center_vertical"
android:textSize="15dp"
android:layout_below="#+id/tv_name"
android:textColor="#000000"
android:layout_marginLeft="10dp"
android:layout_marginTop="10dp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="40dp"
android:layout_below="#+id/tv_name"
android:text="Email"
android:gravity="center_vertical"
android:textSize="15dp"
android:id="#+id/tv_email"
android:textColor="#000000"
android:layout_marginLeft="10dp"
android:layout_marginTop="10dp"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="100dp"
android:layout_height="40dp"
android:text="DOB"
android:gravity="center_vertical"
android:textSize="15dp"
android:textColor="#000000"
android:layout_marginLeft="10dp"
android:layout_marginTop="10dp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="40dp"
android:layout_below="#+id/tv_name"
android:text="DOB"
android:gravity="center_vertical"
android:textSize="15dp"
android:id="#+id/tv_dob"
android:layout_toRightOf="#+id/tv_email"
android:textColor="#000000"
android:layout_marginLeft="10dp"
android:layout_marginTop="10dp"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<TextView
android:layout_width="100dp"
android:layout_height="40dp"
android:text="Location"
android:gravity="center_vertical"
android:textSize="15dp"
android:textColor="#000000"
android:layout_marginLeft="10dp"
android:layout_marginTop="10dp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="40dp"
android:layout_below="#+id/tv_name"
android:text="location"
android:gravity="center_vertical"
android:textSize="15dp"
android:id="#+id/tv_location"
android:textColor="#000000"
android:layout_marginLeft="10dp"
android:layout_marginTop="10dp"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:background="#6585C8"
android:id="#+id/ll_facebook"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
android:layout_marginTop="40dp"
android:layout_height="50dp">
<ImageView
android:layout_width="50dp"
android:src="#drawable/facebook"
android:id="#+id/iv_facebook"
android:layout_height="50dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Login with Facebook"
android:textSize="20dp"
android:textColor="#FFFFFF"
android:textStyle="bold"
android:id="#+id/tv_facebook"
android:layout_marginLeft="20dp"
android:gravity="center"
android:layout_gravity="center"
/>
</LinearLayout>
</LinearLayout>
MainActivity.java
package facebooklocation.facebooklocation;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.Signature;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import com.facebook.AccessToken;
import com.facebook.CallbackManager;
import com.facebook.FacebookCallback;
import com.facebook.FacebookException;
import com.facebook.FacebookSdk;
import com.facebook.GraphRequest;
import com.facebook.GraphResponse;
import com.facebook.HttpMethod;
import com.facebook.login.LoginManager;
import com.facebook.login.LoginResult;
import org.json.JSONObject;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
CallbackManager callbackManager;
ImageView iv_image, iv_facebook;
TextView tv_name, tv_email, tv_dob, tv_location, tv_facebook;
LinearLayout ll_facebook;
String str_facebookname, str_facebookemail, str_facebookid, str_birthday, str_location;
boolean boolean_login;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
getKeyHash();
listener();
}
private void init() {
iv_image = (ImageView) findViewById(R.id.iv_image);
iv_facebook = (ImageView) findViewById(R.id.iv_facebook);
tv_name = (TextView) findViewById(R.id.tv_name);
tv_email = (TextView) findViewById(R.id.tv_email);
tv_dob = (TextView) findViewById(R.id.tv_dob);
tv_location = (TextView) findViewById(R.id.tv_location);
tv_facebook = (TextView) findViewById(R.id.tv_facebook);
ll_facebook = (LinearLayout) findViewById(R.id.ll_facebook);
FacebookSdk.sdkInitialize(this.getApplicationContext());
}
private void listener() {
tv_facebook.setOnClickListener(this);
ll_facebook.setOnClickListener(this);
iv_facebook.setOnClickListener(this);
}
private void facebookLogin() {
callbackManager = CallbackManager.Factory.create();
LoginManager.getInstance().registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
Log.e("ONSUCCESS", "User ID: " + loginResult.getAccessToken().getUserId()
+ "\n" + "Auth Token: " + loginResult.getAccessToken().getToken()
);
GraphRequest request = GraphRequest.newMeRequest(loginResult.getAccessToken(),
new GraphRequest.GraphJSONObjectCallback() {
#Override
public void onCompleted(JSONObject object, GraphResponse response) {
try {
boolean_login = true;
tv_facebook.setText("Logout from Facebook");
Log.e("object", object.toString());
str_facebookname = object.getString("name");
try {
str_facebookemail = object.getString("email");
} catch (Exception e) {
str_facebookemail = "";
e.printStackTrace();
}
try {
str_facebookid = object.getString("id");
} catch (Exception e) {
str_facebookid = "";
e.printStackTrace();
}
try {
str_birthday = object.getString("birthday");
} catch (Exception e) {
str_birthday = "";
e.printStackTrace();
}
try {
JSONObject jsonobject_location = object.getJSONObject("location");
str_location = jsonobject_location.getString("name");
} catch (Exception e) {
str_location = "";
e.printStackTrace();
}
fn_profilepic();
} catch (Exception e) {
}
}
});
Bundle parameters = new Bundle();
parameters.putString("fields", "id, name, email,gender,birthday,location");
request.setParameters(parameters);
request.executeAsync();
}
#Override
public void onCancel() {
if (AccessToken.getCurrentAccessToken() == null) {
return; // already logged out
}
new GraphRequest(AccessToken.getCurrentAccessToken(), "/me/permissions/", null, HttpMethod.DELETE, new GraphRequest
.Callback() {
#Override
public void onCompleted(GraphResponse graphResponse) {
LoginManager.getInstance().logOut();
LoginManager.getInstance().logInWithReadPermissions(MainActivity.this, Arrays.asList("public_profile,email"));
facebookLogin();
}
}).executeAsync();
}
#Override
public void onError(FacebookException e) {
Log.e("ON ERROR", "Login attempt failed.");
AccessToken.setCurrentAccessToken(null);
LoginManager.getInstance().logInWithReadPermissions(MainActivity.this, Arrays.asList("public_profile,email,user_birthday"));
}
});
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
try {
callbackManager.onActivityResult(requestCode, resultCode, data);
} catch (Exception e) {
}
}
private void getKeyHash() {
// Add code to print out the key hash
try {
PackageInfo info = getPackageManager().getPackageInfo("facebooklocation.facebooklocation", PackageManager.GET_SIGNATURES);
for (Signature signature : info.signatures) {
MessageDigest md = MessageDigest.getInstance("SHA");
md.update(signature.toByteArray());
Log.d("KeyHash:", Base64.encodeToString(md.digest(), Base64.DEFAULT));
}
} catch (PackageManager.NameNotFoundException e) {
} catch (NoSuchAlgorithmException e) {
}
}
private void fn_profilepic() {
Bundle params = new Bundle();
params.putBoolean("redirect", false);
params.putString("type", "large");
new GraphRequest(
AccessToken.getCurrentAccessToken(),
"me/picture",
params,
HttpMethod.GET,
new GraphRequest.Callback() {
public void onCompleted(GraphResponse response) {
Log.e("Response 2", response + "");
try {
String str_facebookimage = (String) response.getJSONObject().getJSONObject("data").get("url");
Log.e("Picture", str_facebookimage);
Glide.with(MainActivity.this).load(str_facebookimage).skipMemoryCache(true).into(iv_image);
} catch (Exception e) {
e.printStackTrace();
}
tv_name.setText(str_facebookname);
tv_email.setText(str_facebookemail);
tv_dob.setText(str_birthday);
tv_location.setText(str_location);
}
}
).executeAsync();
}
#Override
public void onClick(View view) {
if (boolean_login) {
boolean_login = false;
LoginManager.getInstance().logOut();
tv_location.setText("");
tv_dob.setText("");
tv_email.setText("");
tv_name.setText("");
Glide.with(MainActivity.this).load(R.drawable.profile).into(iv_image);
tv_facebook.setText("Login with Facebook");
} else {
LoginManager.getInstance().logInWithReadPermissions(MainActivity.this, Arrays.asList("public_profile,email,user_birthday,user_location"));
facebookLogin();
}
}
#Override
protected void onDestroy() {
super.onDestroy();
LoginManager.getInstance().logOut();
}
}
Thanks