[Q] Android Getting Sound Levels - General Questions and Answers

Hello there
I'm a newbie in programming and I wanna build a sound recording application.
I have this code which is recording sound and puts a timestamp :
Code:
package com.tsop.tsp_recorder;
import android.R.layout;
import android.app.Activity;
import android.widget.HorizontalScrollView;
import android.widget.LinearLayout;
import android.os.Bundle;
import android.os.Environment;
import android.view.ViewGroup;
import android.widget.Button;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.MarginLayoutParams;
import android.content.Context;
import android.util.Log;
import android.media.MediaRecorder;
import android.media.MediaPlayer;
import java.io.IOException;
import java.util.Calendar;
public class MainActivity extends Activity
{
private static final String LOG_TAG = "AudioRecordTest";
private static String mFileName = null;
private RecordButton mRecordButton = null;
private MediaRecorder mRecorder = null;
private PlayButton mPlayButton = null;
private MediaPlayer mPlayer = null;
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(mFileName);
mPlayer.prepare();
mPlayer.start();
} catch (IOException e) {
Log.e(LOG_TAG, "prepare() failed");
}
}
private void stopPlaying() {
mPlayer.release();
mPlayer = null;
}
private void startRecording() {
mRecorder = new MediaRecorder();
mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
mRecorder.setOutputFile(mFileName);
mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
try {
mRecorder.prepare();
} catch (IOException e) {
Log.e(LOG_TAG, "prepare() failed");
}
mRecorder.start();
}
private void stopRecording() {
mRecorder.stop();
mRecorder.release();
mRecorder = null;
}
class RecordButton extends Button {
boolean mStartRecording = true;
OnClickListener clicker = new OnClickListener() {
public void onClick(View v) {
onRecord(mStartRecording);
if (mStartRecording) {
setText("Stop recording");
} else {
setText("Start recording");
}
mStartRecording = !mStartRecording;
}
};
public RecordButton(Context ctx) {
super(ctx);
setText("Start recording");
setOnClickListener(clicker);
}
}
class PlayButton extends Button {
boolean mStartPlaying = true;
OnClickListener clicker = new OnClickListener() {
public void onClick(View v) {
onPlay(mStartPlaying);
if (mStartPlaying) {
setText("Stop playing");
} else {
setText("Start playing");
}
mStartPlaying = !mStartPlaying;
}
};
public PlayButton(Context ctx) {
super(ctx);
setText("Start playing");
setOnClickListener(clicker);
}
}
public MainActivity() {
theDate date = new theDate();
String sDate = date.curDate();
String sTime = date.curTime();
mFileName = Environment.getExternalStorageDirectory().getAbsolutePath();
mFileName += "/TSP_Recordings/Date_"+sDate+"_Time_"+sTime+".3gp";
}
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
LinearLayout ll = new LinearLayout(this);
mRecordButton = new RecordButton(this);
ll.addView(mRecordButton,
new LinearLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT,
0));
mPlayButton = new PlayButton(this);
ll.addView(mPlayButton,
new LinearLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT,
0));
setContentView(ll);
}
@Override
public void onPause() {
super.onPause();
if (mRecorder != null) {
mRecorder.release();
mRecorder = null;
}
if (mPlayer != null) {
mPlayer.release();
mPlayer = null;
}
}
}
package com.tsop.tsp_recorder;
import java.util.Calendar;
public class theDate {
static Calendar c = Calendar.getInstance();
public static String curDate() {
int month = c.get(Calendar.MONTH) + 1;
String sDate = c.get(Calendar.DAY_OF_MONTH) + "-"
+ month
+ "-" + c.get(Calendar.YEAR);
return sDate;
}
public static String curTime() {
String sTime = c.get(Calendar.HOUR_OF_DAY)
+ "-" + c.get(Calendar.MINUTE) + "-"
+ c.get(Calendar.SECOND);
return sTime;
}
public static long duration() {
long dur = c.getTimeInMillis();
return dur;
}
}
I need to change it and make it messure the sound levels.I'll use the getMaxAmplitude method,but this method returns only the last result,before it was called.I think I should use a loop,but the start method is capturing and encoding continuously.
How can I get the current amplitude,for example in a period of 1 second,on my recording?
Thanks

I've edited my code into this :
Code:
package com.tsop.tsp_recorder;
import android.R.layout;
import android.app.Activity;
import android.widget.HorizontalScrollView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.os.Bundle;
import android.os.Environment;
import android.view.ViewGroup;
import android.widget.Button;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.MarginLayoutParams;
import android.content.Context;
import android.util.Log;
import android.media.MediaRecorder;
import android.media.MediaPlayer;
import java.io.IOException;
import java.util.Calendar;
public class MainActivity extends Activity
{
private static final String LOG_TAG = "AudioRecordTest";
private static String mFileName = null;
private RecordButton mRecordButton = null;
private MediaRecorder mRecorder = null;
private PlayButton mPlayButton = null;
private MediaPlayer mPlayer = null;
public int currentAmplitude;
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(mFileName);
mPlayer.prepare();
mPlayer.start();
} catch (IOException e) {
Log.e(LOG_TAG, "prepare() failed");
}
}
private void stopPlaying() {
mPlayer.release();
mPlayer = null;
}
private void startRecording() {
mRecorder = new MediaRecorder();
mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
mRecorder.setOutputFile(mFileName);
mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
try {
mRecorder.prepare();
} catch (IOException e) {
Log.e(LOG_TAG, "prepare() failed");
}
mRecorder.start();
getAmplitude();
}
private void stopRecording() {
mRecorder.stop();
mRecorder.release();
mRecorder = null;
}
public double getAmplitude() {
if (mRecorder != null) {
currentAmplitude = mRecorder.getMaxAmplitude();
return currentAmplitude;
}
else
return 0;
}
class RecordButton extends Button {
boolean mStartRecording = true;
OnClickListener clicker = new OnClickListener() {
public void onClick(View v) {
onRecord(mStartRecording);
if (mStartRecording) {
setText("Stop recording");
} else {
setText("Start recording");
}
mStartRecording = !mStartRecording;
}
};
public RecordButton(Context ctx) {
super(ctx);
setText("Start recording");
setOnClickListener(clicker);
}
}
class PlayButton extends Button {
boolean mStartPlaying = true;
OnClickListener clicker = new OnClickListener() {
public void onClick(View v) {
onPlay(mStartPlaying);
if (mStartPlaying) {
setText("Stop playing");
} else {
setText("Start playing");
}
mStartPlaying = !mStartPlaying;
}
};
public PlayButton(Context ctx) {
super(ctx);
setText("Start playing");
setOnClickListener(clicker);
}
}
public MainActivity() {
theDate date = new theDate();
String sDate = date.curDate();
String sTime = date.curTime();
mFileName = Environment.getExternalStorageDirectory().getAbsolutePath();
mFileName += "/TSP_Recordings/Date_"+sDate+"_Time_"+sTime+".3gp";
}
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
LinearLayout ll = new LinearLayout(this);
mRecordButton = new RecordButton(this);
ll.addView(mRecordButton,
new LinearLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT,
0));
mPlayButton = new PlayButton(this);
ll.addView(mPlayButton,
new LinearLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT,
0));
TextView tv = new TextView(this);
ll.addView(tv,
new LinearLayout.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT,
0));
tv.setText(Integer.toString(currentAmplitude));
setContentView(ll);
}
@Override
public void onPause() {
super.onPause();
if (mRecorder != null) {
mRecorder.release();
mRecorder = null;
}
if (mPlayer != null) {
mPlayer.release();
mPlayer = null;
}
}
}
But my result is 0 everytime.Any ideas?

Related

One smali code but 2 different in Java source

hi everyone
i'm very noob in android because i'm a Java EE developer.
ok i have one apk file that i want to change the source code in to JAVA.
i decompiled the apk file in two ways:
first, i used apktool ,dex2jar, jd-ui and then i got this java code :
Code:
package com.sunglab.bigbanghd;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.SharedPreferences;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.*;
//import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.ImageButton;
public class MainActivity
extends Activity
implements SensorEventListener
{
public static final int Amazon = 1;
public static final int Google = 0;
public static boolean IsthatPlaying = true;
public static final int Samsung = 3;
public static final int Tstore = 2;
public static MediaPlayer mPlayer;
public static int store = WallpaperSettings.store;
public int MusicNumber = 0;
Handler handler;
Intent intent;
GL2JNIView.Renderer mRenderer;
private GL2JNIView mView;
Sensor m_ot_sensor;
SensorManager m_sensor_manager;
ImageButton menu_Button;
public void abc(int paramInt)
{
switch (paramInt)
{
}
do
{
do
{
do
{
do
{
do
{
return;
Log.e("else", "Playing 0");
mPlayer.reset();
mPlayer = MediaPlayer.create(this, 2131034112);
mPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener()
{
public void onCompletion(MediaPlayer paramAnonymousMediaPlayer)
{
if (MainActivity.mPlayer.isPlaying()) {
Log.e("else", "finish but playing");
}
for (;;)
{
MainActivity localMainActivity = MainActivity.this;
localMainActivity.MusicNumber = (1 + localMainActivity.MusicNumber);
if (MainActivity.this.MusicNumber == 5) {
MainActivity.this.MusicNumber = 0;
}
MainActivity.this.abc(MainActivity.this.MusicNumber);
return;
Log.e("else", "finish");
}
}
});
} while (!IsthatPlaying);
mPlayer.start();
return;
Log.e("else", "Playing 1");
mPlayer.reset();
mPlayer = MediaPlayer.create(this, 2131034113);
mPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener()
{
public void onCompletion(MediaPlayer paramAnonymousMediaPlayer)
{
if (MainActivity.mPlayer.isPlaying()) {
Log.e("else", "finish but playing");
}
for (;;)
{
MainActivity localMainActivity = MainActivity.this;
localMainActivity.MusicNumber = (1 + localMainActivity.MusicNumber);
if (MainActivity.this.MusicNumber == 5) {
MainActivity.this.MusicNumber = 0;
}
MainActivity.this.abc(MainActivity.this.MusicNumber);
return;
Log.e("else", "finish");
}
}
});
} while (!IsthatPlaying);
mPlayer.start();
return;
Log.e("else", "Playing 2");
mPlayer.reset();
mPlayer = MediaPlayer.create(this, 2131034114);
mPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener()
{
public void onCompletion(MediaPlayer paramAnonymousMediaPlayer)
{
if (MainActivity.mPlayer.isPlaying()) {
Log.e("else", "finish but playing");
}
for (;;)
{
MainActivity localMainActivity = MainActivity.this;
localMainActivity.MusicNumber = (1 + localMainActivity.MusicNumber);
if (MainActivity.this.MusicNumber == 5) {
MainActivity.this.MusicNumber = 0;
}
MainActivity.this.abc(MainActivity.this.MusicNumber);
return;
Log.e("else", "finish");
}
}
});
} while (!IsthatPlaying);
mPlayer.start();
return;
Log.e("else", "Playing 3");
mPlayer.reset();
mPlayer = MediaPlayer.create(this, 2131034115);
mPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener()
{
public void onCompletion(MediaPlayer paramAnonymousMediaPlayer)
{
if (MainActivity.mPlayer.isPlaying()) {
Log.e("else", "finish but playing");
}
for (;;)
{
MainActivity localMainActivity = MainActivity.this;
localMainActivity.MusicNumber = (1 + localMainActivity.MusicNumber);
if (MainActivity.this.MusicNumber == 5) {
MainActivity.this.MusicNumber = 0;
}
MainActivity.this.abc(MainActivity.this.MusicNumber);
return;
Log.e("else", "finish");
}
}
});
} while (!IsthatPlaying);
mPlayer.start();
return;
Log.e("else", "Playing 4");
mPlayer.reset();
mPlayer = MediaPlayer.create(this, 2131034116);
mPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener()
{
public void onCompletion(MediaPlayer paramAnonymousMediaPlayer)
{
if (MainActivity.mPlayer.isPlaying()) {
Log.e("else", "finish but playing");
}
for (;;)
{
MainActivity localMainActivity = MainActivity.this;
localMainActivity.MusicNumber = (1 + localMainActivity.MusicNumber);
if (MainActivity.this.MusicNumber == 5) {
MainActivity.this.MusicNumber = 0;
}
MainActivity.this.abc(MainActivity.this.MusicNumber);
return;
Log.e("else", "finish");
}
}
});
} while (!IsthatPlaying);
mPlayer.start();
}
public void onAccuracyChanged(Sensor paramSensor, int paramInt)
{
Log.e("Sensor working", "Good ratated2s");
}
public void onBackPressed()
{
Log.e("omg", "Back key");
AlertDialog.Builder localBuilder = new AlertDialog.Builder(this);
localBuilder.setIcon(2130837507);
if ((store == 2) || (store == 3)) {
localBuilder.setTitle("이 앱을 종료 하시겠습니까?");
}
for (;;)
{
localBuilder.setCancelable(false);
if ((store != 2) && (store != 3)) {
localBuilder.setPositiveButton("More Apps", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface paramAnonymousDialogInterface, int paramAnonymousInt)
{
switch (MainActivity.store)
{
}
for (;;)
{
MainActivity.this.startActivity(MainActivity.this.intent);
return;
MainActivity.this.intent = new Intent("android.intent.action.VIEW", Uri.parse("xxxx"));
continue;
MainActivity.this.intent = new Intent("android.intent.action.VIEW", Uri.parse("xxx"));
}
}
});
}
localBuilder.setNeutralButton("Cancel", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface paramAnonymousDialogInterface, int paramAnonymousInt)
{
paramAnonymousDialogInterface.cancel();
}
});
localBuilder.setNegativeButton("Exit", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface paramAnonymousDialogInterface, int paramAnonymousInt)
{
MainActivity.this.finish();
}
});
localBuilder.show();
return;
localBuilder.setTitle("Do you need More SungLab Apps ?");
}
}
public void onCreate(Bundle paramBundle)
{
super.onCreate(paramBundle);
Log.e("gg", "onCreate");
this.m_sensor_manager = ((SensorManager)getSystemService("sensor"));
this.m_ot_sensor = this.m_sensor_manager.getDefaultSensor(3);
this.mView = new GL2JNIView(getApplication());
setContentView(this.mView);
SharedPreferences localSharedPreferences = getSharedPreferences("wallpaperSet", 0);
int i = localSharedPreferences.getInt("THICK", 5);
int j = localSharedPreferences.getInt("TAIL", 7);
int k = localSharedPreferences.getInt("NUMBER", 5999);
int m = localSharedPreferences.getInt("COLORS", 0);
if (Boolean.valueOf(localSharedPreferences.getBoolean("MUSIC", true)).booleanValue()) {}
for (IsthatPlaying = true;; IsthatPlaying = false)
{
GL2JNIView.Renderer.number = k + 1;
GL2JNIView.Renderer.tail = 0.99F - (0.2F - 0.02F * j);
GL2JNIView.Renderer.thick = 1.0F + 0.4F * i;
GL2JNIView.Renderer.colors = m;
addContentView(((LayoutInflater)getSystemService("layout_inflater")).inflate(2130903040, null), new ViewGroup.LayoutParams(-1, -1));
getWindow().setFlags(128, 128);
mPlayer = MediaPlayer.create(this, 2131034112);
if (!IsthatPlaying) {
mPlayer.pause();
}
mPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener()
{
public void onCompletion(MediaPlayer paramAnonymousMediaPlayer)
{
if (MainActivity.mPlayer.isPlaying()) {
Log.e("else", "finish but playing");
}
for (;;)
{
MainActivity localMainActivity = MainActivity.this;
localMainActivity.MusicNumber = (1 + localMainActivity.MusicNumber);
if (MainActivity.this.MusicNumber == 5) {
MainActivity.this.MusicNumber = 0;
}
MainActivity.this.abc(MainActivity.this.MusicNumber);
return;
Log.e("else", "finish");
}
}
});
this.menu_Button = ((ImageButton)findViewById(2131296256));
this.menu_Button.setOnClickListener(new View.OnClickListener()
{
public void onClick(View paramAnonymousView)
{
MainActivity.this.startActivity(new Intent(MainActivity.this, WallpaperSettings.class));
}
});
return;
}
}
protected void onDestroy()
{
super.onDestroy();
this.mView = null;
if (mPlayer.isPlaying()) {
mPlayer.stop();
}
mPlayer.release();
mPlayer = null;
Log.e("omg", "Destroy");
}
public void onHomePressed()
{
Log.e("omg", "Home key");
}
protected void onPause()
{
super.onPause();
this.mView.onPause();
if (IsthatPlaying) {
mPlayer.pause();
}
this.m_sensor_manager.unregisterListener(this);
Log.e("omg", "onPause");
}
protected void onResume()
{
super.onResume();
this.mView.onResume();
Log.e("omg", "onResume");
if (Boolean.valueOf(getSharedPreferences("wallpaperSet", 0).getBoolean("MUSIC", true)).booleanValue())
{
IsthatPlaying = true;
if (!IsthatPlaying) {
break label82;
}
mPlayer.start();
}
for (;;)
{
this.m_sensor_manager.registerListener(this, this.m_ot_sensor, 2);
return;
IsthatPlaying = false;
break;
label82:
mPlayer.pause();
}
}
public void onSensorChanged(SensorEvent paramSensorEvent)
{
if (paramSensorEvent.sensor.getType() == 3)
{
if ((int)paramSensorEvent.values[2] > 45) {
GL2JNIView.Renderer.DefinallyROTATION = -90;
}
}
else {
return;
}
if ((int)paramSensorEvent.values[2] < -45)
{
GL2JNIView.Renderer.DefinallyROTATION = 90;
return;
}
GL2JNIView.Renderer.DefinallyROTATION = 0;
}
public boolean onTouchEvent(MotionEvent paramMotionEvent)
{
int i = paramMotionEvent.getPointerCount();
int j = 0;
if (j >= i) {
switch (paramMotionEvent.getAction())
{
}
}
for (;;)
{
return true;
GL2JNIView.TouchMoveNumber(paramMotionEvent.getX(j), paramMotionEvent.getY(j), j, paramMotionEvent.getPointerCount());
j++;
break;
GL2JNIView.TouchUpNumber();
continue;
GL2JNIView.TouchDownNumber();
continue;
GL2JNIView.TouchDownNumber();
}
}
}
/* Location: C:\jd-gui-windows-1.4.0\classes_dex2jar.jar!\com\sunglab\bigbanghd\MainActivity.class
* Java compiler version: 6 (50.0)
* JD-Core Version: 0.7.1
*/
and the second way i used backSmali tool and jd-ui , i got this JAVA code:
Code:
/**
* Generated by smali2java 1.0.0.558
* Copyright (C) 2013 Hensence.com
*/
package com.sunglab.bigbanghd;
import android.app.Activity;
import android.hardware.SensorEventListener;
import android.media.MediaPlayer;
import android.os.Handler;
import android.content.Intent;
import android.hardware.Sensor;
import android.hardware.SensorManager;
import android.widget.ImageButton;
import android.util.Log;
import android.content.Context;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.app.Application;
import android.view.View;
import android.content.SharedPreferences;
import android.view.LayoutInflater;
import android.view.ViewGroup;
import android.view.Window;
import android.hardware.SensorEvent;
import android.view.MotionEvent;
public class MainActivity extends Activity implements SensorEventListener {
public static final int Amazon = 0x1;
public static final int Google = 0x0;
public int MusicNumber;
public static final int Samsung = 0x3;
public static final int Tstore = 0x2;
Handler handler;
Intent intent;
public static MediaPlayer mPlayer;
GL2JNIView.Renderer mRenderer;
private GL2JNIView mView;
Sensor m_ot_sensor;
SensorManager m_sensor_manager;
ImageButton menu_Button;
public static int store = WallpaperSettings.store;
public static boolean IsthatPlaying = 0x1;
public void onCreate(Bundle p1) {
super.onCreate(p1);
Log.e("gg", "onCreate");
m_sensor_manager = (SensorManager)getSystemService("sensor");
m_ot_sensor = m_sensor_manager.getDefaultSensor(0x3);
mView = new GL2JNIView(getApplication());
setContentView(mView);
SharedPreferences "preferences" = getSharedPreferences("wallpaperSet", 0x0);
int "thickness" = "preferences".getInt("THICK", 0x5);
int "tails" = "preferences".getInt("TAIL", 0x7);
int "particleNumber" = "preferences".getInt("NUMBER", 0x176f);
int "colors" = "preferences".getInt("COLORS", 0x0);
Boolean "music" = Boolean.valueOf("preferences".getBoolean("MUSIC", true));
if("music".booleanValue()) {
IsthatPlaying = 0x1;
} else {
IsthatPlaying = 0x0;
}
GL2JNIView.Renderer.number = ("particleNumber" + 0x1);
GL2JNIView.Renderer.tail = (0x3f7d70a4 # 0.99f - (0x3e4ccccd # 0.2f - ((float)"tails" * 0x3ca3d70a # 0.02f)));
GL2JNIView.Renderer.thick = (0.0f + ((float)"thickness" * 0x3ecccccd # 0.4f));
GL2JNIView.Renderer.colors = "colors";
LayoutInflater "vi" = (LayoutInflater)getSystemService("layout_inflater");
View "v" = "vi".inflate(0x0, 0x0);
addContentView("v", new ViewGroup.LayoutParams(-0x1, -0x1));
getWindow().setFlags(0x80, 0x80);
mPlayer = MediaPlayer.create(this, 0x0);
if(!IsthatPlaying) {
mPlayer.pause();
}
mPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener(this) {
1(MainActivity p1) {
}
public void onCompletion(MediaPlayer p1) {
if(MainActivity.mPlayer.isPlaying()) {
Log.e("else", "finish but playing");
} else {
Log.e("else", "finish");
}
MusicNumber = (MusicNumber + 0x1);
if(MusicNumber == 0x5) {
MusicNumber = 0x0;
}
abc(MusicNumber);
}
});
menu_Button = (ImageButton)findViewById(0x0);
menu_Button.setOnClickListener(new View.OnClickListener(this) {
2(MainActivity p1) {
}
public void onClick(View p1) {
startActivity(new Intent(this$0, WallpaperSettings.class));
}
});
}
public void abc(int p1) {
switch(p1) {
case 0:
{
Log.e("else", "Playing 0");
mPlayer.reset();
mPlayer = MediaPlayer.create(this, 0x0);
mPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener(this) {
3(MainActivity p1) {
}
public void onCompletion(MediaPlayer p1) {
if(MainActivity.mPlayer.isPlaying()) {
Log.e("else", "finish but playing");
} else {
Log.e("else", "finish");
}
MusicNumber = (MusicNumber + 0x1);
if(MusicNumber == 0x5) {
MusicNumber = 0x0;
}
abc(MusicNumber);
}
});
if(IsthatPlaying) {
mPlayer.start();
}
return;
}
case 1:
{
Log.e("else", "Playing 1");
mPlayer.reset();
mPlayer = MediaPlayer.create(this, 0x7f050001);
mPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener(this) {
4(MainActivity p1) {
}
public void onCompletion(MediaPlayer p1) {
if(MainActivity.mPlayer.isPlaying()) {
Log.e("else", "finish but playing");
} else {
Log.e("else", "finish");
}
MusicNumber = (MusicNumber + 0x1);
if(MusicNumber == 0x5) {
MusicNumber = 0x0;
}
abc(MusicNumber);
}
});
if(IsthatPlaying) {
mPlayer.start();
}
return;
}
case 2:
{
Log.e("else", "Playing 2");
mPlayer.reset();
mPlayer = MediaPlayer.create(this, 0x7f050002);
mPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener(this) {
5(MainActivity p1) {
}
public void onCompletion(MediaPlayer p1) {
if(MainActivity.mPlayer.isPlaying()) {
Log.e("else", "finish but playing");
} else {
Log.e("else", "finish");
}
MusicNumber = (MusicNumber + 0x1);
if(MusicNumber == 0x5) {
MusicNumber = 0x0;
}
abc(MusicNumber);
}
});
if(IsthatPlaying) {
mPlayer.start();
}
return;
}
case 3:
{
Log.e("else", "Playing 3");
mPlayer.reset();
mPlayer = MediaPlayer.create(this, 0x7f050003);
mPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener(this) {
6(MainActivity p1) {
}
public void onCompletion(MediaPlayer p1) {
if(MainActivity.mPlayer.isPlaying()) {
Log.e("else", "finish but playing");
} else {
Log.e("else", "finish");
}
MusicNumber = (MusicNumber + 0x1);
if(MusicNumber == 0x5) {
MusicNumber = 0x0;
}
abc(MusicNumber);
}
});
if(IsthatPlaying) {
mPlayer.start();
}
return;
}
case 4:
{
Log.e("else", "Playing 4");
mPlayer.reset();
mPlayer = MediaPlayer.create(this, 0x7f050004);
mPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener(this) {
7(MainActivity p1) {
}
public void onCompletion(MediaPlayer p1) {
if(MainActivity.mPlayer.isPlaying()) {
Log.e("else", "finish but playing");
} else {
Log.e("else", "finish");
}
MusicNumber = (MusicNumber + 0x1);
if(MusicNumber == 0x5) {
MusicNumber = 0x0;
}
abc(MusicNumber);
}
});
if(IsthatPlaying) {
mPlayer.start();
break;
}
}
}
}
protected void onPause() {
super.onPause();
mView.onPause();
if(IsthatPlaying) {
mPlayer.pause();
}
m_sensor_manager.unregisterListener(this);
Log.e("omg", "onPause");
}
protected void onResume() {
super.onResume();
mView.onResume();
Log.e("omg", "onResume");
SharedPreferences "preferences" = getSharedPreferences("wallpaperSet", 0x0);
Boolean "music" = Boolean.valueOf("preferences".getBoolean("MUSIC", true));
if("music".booleanValue()) {
IsthatPlaying = 0x1;
} else {
IsthatPlaying = 0x0;
}
if(IsthatPlaying) {
mPlayer.start();
} else {
mPlayer.pause();
}
m_sensor_manager.registerListener(this, m_ot_sensor, 0x2);
}
public void onSensorChanged(SensorEvent p1) {
if(p1.sensor.getType() == 0x3) {
if((int)p1.values[0x2] > 0x2d) {
GL2JNIView.Renderer.DefinallyROTATION = -0x5a;
return;
}
if((int)p1.values[0x2] < -0x2d) {
GL2JNIView.Renderer.DefinallyROTATION = 0x5a;
return;
}
GL2JNIView.Renderer.DefinallyROTATION = 0x0;
}
}
public void onAccuracyChanged(Sensor p1, int p2) {
Log.e("Sensor working", "Good ratated2s");
}
protected void onDestroy() {
super.onDestroy();
mView = 0x0;
if(mPlayer.isPlaying()) {
mPlayer.stop();
}
mPlayer.release();
mPlayer = 0x0;
Log.e("omg", "Destroy");
}
public void onBackPressed() {
Log.e("omg", "Back key");
AlertDialog.Builder "d" = new AlertDialog.Builder(this);
"d".setIcon(0x7f020003);
if((store == 0x2) || (store == 0x3)) {
"d".setTitle("\uc774 \uc571\uc744 \uc885\ub8cc \ud558\uc2dc\uaca0\uc2b5\ub2c8\uae4c?");
} else {
"d".setTitle("Do you need More SungLab Apps ?");
}
"d".setCancelable(false);
if((store != 0x2) && (store != 0x3)) {
"d".setPositiveButton("More Apps", new DialogInterface.OnClickListener(this) {
8(MainActivity p1) {
}
public void onClick(DialogInterface p1, int p2) {
switch(MainActivity.store) {
case 0:
{
new Intent("android.intent.action.VIEW", Uri.parse("xx"));
intent = localIntent1;
break;
}
case 1:
{
new Intent("android.intent.action.VIEW", Uri.parse("xxxx"));
intent = localIntent2;
break;
}
}
startActivity(intent);
}
});
}
"d".setNeutralButton("Cancel", new DialogInterface.OnClickListener(this) {
9(MainActivity p1) {
}
public void onClick(DialogInterface p1, int p2) {
p1.cancel();
}
});
"d".setNegativeButton("Exit", new DialogInterface.OnClickListener(this) {
10(MainActivity p1) {
}
public void onClick(DialogInterface p1, int p2) {
finish();
}
});
"d".show();
}
public void onHomePressed() {
Log.e("omg", "Home key");
}
public boolean onTouchEvent(MotionEvent p1) {
int "pointerCount" = p1.getPointerCount();
for(int "i" = 0x0; "i" >= "pointerCount"; "i" = "i" + 0x1) {
}
GL2JNIView.TouchMoveNumber(p1.getX("i"), p1.getY("i"), "i", p1.getPointerCount());
switch(p1.getAction()) {
case 1:
{
GL2JNIView.TouchUpNumber();
break;
}
case 0:
{
GL2JNIView.TouchDownNumber();
break;
}
case 5:
{
GL2JNIView.TouchDownNumber();
break;
}
case 2:
case 3:
case 4:
{
return true;
}
}
}
}
now i have a question why both of java codes are not the same?? for example, in the first one, we have some (do while) loops but in the second way we don't have them???
and as you can see, in the first one some lines seem wrong (in abc() method or it has written for( ;; ) ).
And also in the second one, in abc() method, we have switch case but in the first one we don't have it.
i want to edit some lines and codes but it seems the original decompiled code doesn't work.

How to Get the Current Location using Google Play Services in android

I'm trying to get the current GPS location from an android smartphone but I'm having some issues, because I didn't get any latitude and longitude.
I've used Google Play Services library because the other methods didn't work. Here's the code:
Code:
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.os.Bundle;
import android.app.Activity;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.widget.TextView;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
public class AroundMeActivity extends Activity implements
GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener {
private GoogleApiClient mGoogleApiClient;
private TextView mLatitudeText;
private TextView mLongitudeText;
private Location mLastLocation;
private boolean mRequestingLocationUpdates = true;
private LocationRequest mLocationRequest;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_around_me);
mLatitudeText = (TextView) findViewById(R.id.location_text);
mLongitudeText = (TextView) findViewById(R.id.activity_text);
// Create an instance of GoogleAPIClient.
if (mGoogleApiClient == null) {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
}
@Override
public void onConnected(Bundle connectionHint) {
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
mLastLocation = LocationServices.FusedLocationApi.getLastLocation(
mGoogleApiClient);
if (mLastLocation != null) {
mLatitudeText.setText(String.valueOf(mLastLocation.getLatitude()));
mLongitudeText.setText(String.valueOf(mLastLocation.getLongitude()));
}
return;
}
if (mRequestingLocationUpdates) {
startLocationUpdates();
}
}
protected void startLocationUpdates() {
if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
LocationServices.FusedLocationApi.requestLocationUpdates(
mGoogleApiClient, mLocationRequest, (com.google.android.gms.location.LocationListener) this);
return;
}
}
@Override
public void onConnectionSuspended(int i) {
}
protected void onStart() {
mGoogleApiClient.connect();
super.onStart();
}
protected void onStop() {
mGoogleApiClient.disconnect();
super.onStop();
}
@Override
protected void onPause() {
super.onPause();
stopLocationUpdates();
}
protected void stopLocationUpdates() {
LocationServices.FusedLocationApi.removeLocationUpdates(
mGoogleApiClient, (com.google.android.gms.location.LocationListener) this);
}
@Override
public void onResume() {
super.onResume();
if (mGoogleApiClient.isConnected() && !mRequestingLocationUpdates) {
startLocationUpdates();
}
}
@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
}
@Override
public void onLocationChanged(Location location) {
mLastLocation = location;
//mLastUpdateTime = DateFormat.getTimeInstance().format(new Date());
updateUI();
}
private void updateUI() {
mLatitudeText.setText(String.valueOf(mLastLocation.getLatitude()));
mLongitudeText.setText(String.valueOf(mLastLocation.getLongitude()));
//mLastUpdateTimeTextView.setText(mLastUpdateTime);
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onProviderDisabled(String provider) {
}
protected void createLocationRequest() {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(10000);
mLocationRequest.setFastestInterval(5000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
}
}
Has anyone encountered the same issue and can help me?
Thank you in advance guys!!

Not working context menu item in fragment

Code:
public class ThreeFragment extends Fragment {
public View ThreeFragmentView = null;
public static TextView internalMemoryInfo;
public static Button IntBtn;
public ThreeFragment() {
// Required empty public constructor
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
if (ThreeFragmentView == null) ThreeFragmentView = inflater.inflate(R.layout.fragment_three, container, false);
internalMemoryInfo = (TextView) ThreeFragmentView.findViewById(R.id.textViewInternalMemoryInfo);
IntBtn = (Button) ThreeFragmentView.findViewById(R.id.InternalBtn);
return ThreeFragmentView;
}
public static void showText(String text) {
internalMemoryInfo.setText(text);
}
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
registerForContextMenu(IntBtn);
}
@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
switch (v.getId()){
case R.id.InternalBtn:
menu.setHeaderTitle("Internal Memory Menu");
menu.add(0, ClearCacheMet, 0, "Clear Cache");
menu.add(0, Common, 0, "Go to Common Tab");
menu.add(0, ITEM_CANCEL, 0, "Cancel");
break;
}
}
@Override
public boolean onContextItemSelected(MenuItem item) {
switch (item.getItemId()) {
case ClearCacheMet:
ClearCache(); <-------This not working
break;
case Common:
tabLayout.getTabAt(0).select(); <-------This working
break;
case ITEM_CANCEL:
ins.closeContextMenu(); <-------This working
break;
}
return true;
}
public static boolean deleteDir(File dir){
if (dir != null && dir.isDirectory()) {
String[] children = dir.list();
for (int i = 0; i < children.length; i++) {
boolean success = deleteDir(new File(dir, children[i]));
if (!success) {
return false;
}
}
}
return dir.delete();
}
public static void ClearCache() {
File cache = ins.getCacheDir();
File appDir = new File(cache.getParent());
if (appDir.exists()) {
String[] children = appDir.list();
for (String s : children) {
if (!s.equals("lib")) {
deleteDir(new File(appDir, s));
}
}
}
try{
/*if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
((ActivityManager) ins.getSystemService(Context.ACTIVITY_SERVICE)).clearApplicationUserData();
} else {*/
File externalcache = ins.getExternalCacheDir();
File externalappDir = new File(externalcache.getParent());
if (externalappDir.exists()) {
String[] children = externalappDir.list();
for (String s : children) {
if (!s.equals("lib")) {
deleteDir(new File(externalappDir, s));
}
}
} else {
Log.d(TAG, "No externalappDir");
}
/*}*/
} catch (Exception e) {
Log.d(TAG, "MainActivity in ClearCache");
}
}
I have fragment(ThreeFragment) with button(InternalBtn) that have a context menu. Context menu registered with registerForContextMenu(IntBtn); Menu item ClearCacheMet not working. I cannot see neither Toast.makeText().show(); nor Log.d(TAG, "ClearCache"); Common and ITEM_CANCEL items working. I cannot understand why? Please help me.
Toast.makeText(getActivity(), "Called !", Toast.LENGTH_SHORT).show(); not called in ClearCache() function. ClearCacheMet and Common were initialized in other fragment.
public class OneFragment extends Fragment {
public View OneFragmentView = null;
public static final int Common = 25;
public static final int ClearCacheMet = 50;

Error while uploading image in my Android App.

I made Instagram type application in Android Studio, but whenever I try to upload image in my app, it uploads to my profile picture. I checked my intents and they are really perfect. First file is GalleryFragment.java in which we will select the photo which we want to upload and Second file is NextActivity.java which is used to Share the image to profile. But in GalleryFragment.java I have intent getActivity() to NextActivity.java and AccountSettingsActivity.java in which we can change out profile picture. But whenever I click on Next it doesn't take me to NextActivity.java but to the AccountSettingsActivity.java and updates my profile picture. If there is Firebase error so tell me. And the same issue is occurred when I try to upload photo from camera inside the application and it doesn't do anything. I have posted 3 files.
GalleryFragment.java
Code:
package darthvader.com.pictagram.Share;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Environment;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.Spinner;
import android.widget.TextView;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.listener.ImageLoadingListener;
import java.util.ArrayList;
import java.util.Objects;
import darthvader.com.pictagram.Profile.AccountSettingsActivity;
import darthvader.com.pictagram.R;
import darthvader.com.pictagram.Utils.FilePaths;
import darthvader.com.pictagram.Utils.FileSearch;
import darthvader.com.pictagram.Utils.GridImageAdapter;
public class GalleryFragment extends Fragment {
private static final String TAG = "GalleryFragment";
//constants
private static final int NUM_GRID_COLUMNS = 3;
//widgets
private GridView gridView;
private ImageView galleryImage;
private ProgressBar mProgressBar;
private Spinner directorySpinner;
//vars
private ArrayList<String> directories;
private String mAppend = "file:/";
private String mSelectedImage;
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_gallery, container, false);
galleryImage = view.findViewById(R.id.galleryImageView);
gridView = view.findViewById(R.id.gridView);
directorySpinner = view.findViewById(R.id.spinnerDirectory);
mProgressBar = view.findViewById(R.id.progressBar);
mProgressBar.setVisibility(View.GONE);
directories = new ArrayList<>();
Log.d(TAG, "onCreateView: started.");
ImageView shareClose = view.findViewById(R.id.ivCloseShare);
shareClose.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.d(TAG, "onClick: closing the gallery fragment.");
Objects.requireNonNull(getActivity()).finish();
}
});
TextView nextScreen = view.findViewById(R.id.tvNext);
nextScreen.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.d(TAG, "onClick: navigating to the final share screen.");
if(isRootTask()){
Intent intent = new Intent(getActivity(), NextActivity.class);
intent.putExtra(getString(R.string.selected_image), mSelectedImage);
startActivity(intent);
}else{
Intent intent = new Intent(getActivity(), AccountSettingsActivity.class);
intent.putExtra(getString(R.string.selected_image), mSelectedImage);
intent.putExtra(getString(R.string.return_to_fragment), getString(R.string.edit_profile_fragment));
startActivity(intent);
getActivity().finish();
}
}
});
init();
return view;
}
private boolean isRootTask(){
return ((ShareActivity) getActivity()).getTask() == 0;
}
private void init(){
FilePaths filePaths = new FilePaths();
//check for other folders indide "/storage/emulated/0/pictures"
if (FileSearch.getDirectoryPaths(filePaths.PICTURES) != null) {
directories = FileSearch.getDirectoryPaths(filePaths.PICTURES);
}
directories.add(filePaths.CAMERA);
ArrayList<String> directoryNames = new ArrayList<>();
for (int i = 0; i < directories.size(); i++) {
Log.d(TAG, "init: directory: " + directories.get(i));
int index = directories.get(i).lastIndexOf("/");
String string = directories.get(i).substring(index);
directoryNames.add(string);
}
ArrayAdapter<String> adapter = new ArrayAdapter<>(Objects.requireNonNull(getActivity()),
android.R.layout.simple_spinner_item, directoryNames);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
directorySpinner.setAdapter(adapter);
directorySpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
Log.d(TAG, "onItemClick: selected: " + directories.get(position));
//setup our image grid for the directory chosen
setupGridView(directories.get(position));
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
private void setupGridView(String selectedDirectory){
Log.d(TAG, "setupGridView: directory chosen: " + selectedDirectory);
final ArrayList<String> imgURLs = FileSearch.getFilePaths(selectedDirectory);
//set the grid column width
int gridWidth = getResources().getDisplayMetrics().widthPixels;
int imageWidth = gridWidth/NUM_GRID_COLUMNS;
gridView.setColumnWidth(imageWidth);
//use the grid adapter to adapter the images to gridview
GridImageAdapter adapter = new GridImageAdapter(getActivity(), R.layout.layout_grid_imageview, mAppend, imgURLs);
gridView.setAdapter(adapter);
//set the first image to be displayed when the activity fragment view is inflated
try{
setImage(imgURLs.get(0), galleryImage, mAppend);
mSelectedImage = imgURLs.get(0);
}catch (ArrayIndexOutOfBoundsException e){
Log.e(TAG, "setupGridView: ArrayIndexOutOfBoundsException: " +e.getMessage() );
}
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Log.d(TAG, "onItemClick: selected an image: " + imgURLs.get(position));
setImage(imgURLs.get(position), galleryImage, mAppend);
mSelectedImage = imgURLs.get(position);
}
});
}
private void setImage(String imgURL, ImageView image, String append){
Log.d(TAG, "setImage: setting image");
ImageLoader imageLoader = ImageLoader.getInstance();
imageLoader.displayImage(append + imgURL, image, new ImageLoadingListener() {
@Override
public void onLoadingStarted(String imageUri, View view) {
mProgressBar.setVisibility(View.VISIBLE);
}
@Override
public void onLoadingFailed(String imageUri, View view, FailReason failReason) {
mProgressBar.setVisibility(View.INVISIBLE);
}
@Override
public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
mProgressBar.setVisibility(View.INVISIBLE);
}
@Override
public void onLoadingCancelled(String imageUri, View view) {
mProgressBar.setVisibility(View.INVISIBLE);
}
});
}
}
NextActivity.java
Code:
package darthvader.com.pictagram.Share;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.Query;
import com.google.firebase.database.ValueEventListener;
import darthvader.com.pictagram.R;
import darthvader.com.pictagram.Utils.FirebaseMethods;
import darthvader.com.pictagram.Utils.UniversalImageLoader;
import darthvader.com.pictagram.models.User;
public class NextActivity extends AppCompatActivity {
private static final String TAG = "NextActivity";
//firebase
private FirebaseAuth mAuth;
private FirebaseAuth.AuthStateListener mAuthListener;
private FirebaseDatabase mFirebaseDatabase;
private DatabaseReference myRef;
private FirebaseMethods mFirebaseMethods;
//widgets
private EditText mCaption;
//vars
private String mAppend = "file:/";
private int imageCount = 0;
private String imgUrl;
private Bitmap bitmap;
private Intent intent;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_next);
mFirebaseMethods = new FirebaseMethods(NextActivity.this);
mCaption = findViewById(R.id.caption);
setupFirebaseAuth();
ImageView backArrow = findViewById(R.id.ivBackArrow);
backArrow.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.d(TAG, "onClick: closing the activity");
finish();
}
});
TextView share = findViewById(R.id.tvShare);
share.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.d(TAG, "onClick: navigating to the final share screen.");
//upload the image to firebase
Toast.makeText(NextActivity.this, "Attempting to upload new photo", Toast.LENGTH_SHORT).show();
String caption = mCaption.getText().toString();
if(intent.hasExtra(getString(R.string.selected_image))){
imgUrl = intent.getStringExtra(getString(R.string.selected_image));
mFirebaseMethods.uploadNewPhoto(getString(R.string.new_photo), caption, imageCount, imgUrl,null);
}
else if(intent.hasExtra(getString(R.string.selected_bitmap))){
bitmap = intent.getParcelableExtra(getString(R.string.selected_bitmap));
mFirebaseMethods.uploadNewPhoto(getString(R.string.new_photo), caption, imageCount, null,bitmap);
}
}
});
setImage();
}
private void someMethod(){
/*
Step 1)
Create a data model for Photos
Step 2)
Add properties to the Photo Objects (caption, date, imageUrl, photo_id, tags, user_id)
Step 3)
Count the number of photos that the user already has.
Step 4)
a) Upload the photo to Firebase Storage
b) insert into 'photos' node
c) insert into 'user_photos' node
*/
}
/**
* gets the image url from the incoming intent and displays the chosen image
*/
private void setImage(){
intent = getIntent();
ImageView image = findViewById(R.id.imageShare);
if(intent.hasExtra(getString(R.string.selected_image))){
imgUrl = intent.getStringExtra(getString(R.string.selected_image));
Log.d(TAG, "setImage: got new image url: " + imgUrl);
UniversalImageLoader.setImage(imgUrl, image, null, mAppend);
}
else if(intent.hasExtra(getString(R.string.selected_bitmap))){
bitmap = intent.getParcelableExtra(getString(R.string.selected_bitmap));
Log.d(TAG, "setImage: got new bitmap");
image.setImageBitmap(bitmap);
}
}
/*
------------------------------------ Firebase ---------------------------------------------
*/
/**
* Setup the firebase auth object
*/
private void setupFirebaseAuth(){
Log.d(TAG, "setupFirebaseAuth: setting up firebase auth.");
mAuth = FirebaseAuth.getInstance();
mFirebaseDatabase = FirebaseDatabase.getInstance();
myRef = mFirebaseDatabase.getReference();
Log.d(TAG, "onDataChange: image count: " + imageCount);
mAuthListener = new FirebaseAuth.AuthStateListener() {
@Override
public void onAuthStateChanged(@NonNull FirebaseAuth firebaseAuth) {
FirebaseUser user = firebaseAuth.getCurrentUser();
if (user != null) {
// User is signed in
Log.d(TAG, "onAuthStateChanged:signed_in:" + user.getUid());
} else {
// User is signed out
Log.d(TAG, "onAuthStateChanged:signed_out");
}
// ...
}
};
myRef.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
imageCount = mFirebaseMethods.getImageCount(dataSnapshot);
Log.d(TAG, "onDataChange: image count: " + imageCount);
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
@Override
public void onStart() {
super.onStart();
mAuth.addAuthStateListener(mAuthListener);
}
@Override
public void onStop() {
super.onStop();
if (mAuthListener != null) {
mAuth.removeAuthStateListener(mAuthListener);
}
}
}
PhotoFragment.java
Code:
package darthvader.com.pictagram.Share;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import java.util.Objects;
import darthvader.com.pictagram.Profile.AccountSettingsActivity;
import darthvader.com.pictagram.R;
import darthvader.com.pictagram.Utils.Permissions;
public class PhotoFragment extends Fragment {
private static final String TAG = "PhotoFragment";
//constant
private static final int PHOTO_FRAGMENT_NUM = 1;
private static final int GALLERY_FRAGMENT_NUM = 2;
private static final int CAMERA_REQUEST_CODE = 5;
@Nullable
@Override
public View onCreateView(final LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_photo, container, false);
Log.d(TAG, "onCreateView: started.");
Button btnLaunchCamera = (Button) view.findViewById(R.id.btnLaunchCamera);
btnLaunchCamera.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.d(TAG, "onClick: launching camera.");
if(((ShareActivity)getActivity()).getCurrentTabNumber() == PHOTO_FRAGMENT_NUM){
if(((ShareActivity)getActivity()).checkPermissions(Permissions.CAMERA_PERMISSION[0])){
Log.d(TAG, "onClick: starting camera");
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_REQUEST_CODE);
}else{
Intent intent = new Intent(getActivity(), ShareActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
}
}
}
});
return view;
}
private boolean isRootTask(){
if(((ShareActivity)getActivity()).getTask() == 0){
return true;
}
else{
return false;
}
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == CAMERA_REQUEST_CODE){
Log.d(TAG, "onActivityResult: done taking a photo.");
Log.d(TAG, "onActivityResult: attempting to navigate to final share screen.");
Bitmap bitmap;
bitmap = (Bitmap) Objects.requireNonNull(data.getExtras()).get("data");
if(isRootTask()){
try{
Log.d(TAG, "onActivityResult: received new bitmap from camera: " + bitmap);
Intent intent = new Intent(getActivity(), NextActivity.class);
intent.putExtra(getString(R.string.selected_bitmap), bitmap);
startActivity(intent);
}catch (NullPointerException e){
Log.d(TAG, "onActivityResult: NullPointerException: " + e.getMessage());
}
}else{
try{
Log.d(TAG, "onActivityResult: received new bitmap from camera: " + bitmap);
Intent intent = new Intent(getActivity(), AccountSettingsActivity.class);
intent.putExtra(getString(R.string.selected_bitmap), bitmap);
intent.putExtra(getString(R.string.return_to_fragment), getString(R.string.edit_profile_fragment));
startActivity(intent);
getActivity().finish();
}catch (NullPointerException e){
Log.d(TAG, "onActivityResult: NullPointerException: " + e.getMessage());
}
}
}
}
}

Is RecyclerView refreshed when AlertDialog's positive button gets pressed

My MainActivity has a RecyclerView adapter, and data to this RecyclerView is added through a AlertDialog which passes the entered text to the MainActivity. The recycler view gets refreshed somehow when the positive button in the dialog is pressed even though I never call notifyItemInserted() or notifyDatasetChange() after passing the new input. I want to know how this happens, my guess is the recyclerview is somehow refreshed after the positive button is pressed in the dialog box.
Custom AlertDialog Code:
Code:
public class CustomDialog extends AppCompatDialogFragment {
OnNoteAddedListener onNoteAddedListener;
public interface OnNoteAddedListener {
public void onClick(String note);
}
public CustomDialog(OnNoteAddedListener onNoteAddedListener) {
this.onNoteAddedListener = onNoteAddedListener;
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
// Get the layout inflater
final LayoutInflater inflater = getActivity().getLayoutInflater();
final View dialogLayout = inflater.inflate(R.layout.dialog_box, null);
// Inflate and set the layout for the dialog
// Pass null as the parent view because its going in the dialog layout
builder.setView(dialogLayout).setPositiveButton("Ok", new DialogInterface.OnClickListener() {@Override
public void onClick(DialogInterface dialog, int id) {
EditText addNote = dialogLayout.findViewById(R.id.note_text);
String note = addNote.getText().toString();
onNoteAddedListener.onClick(note);
}
}).setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
CustomDialog.this.getDialog().cancel();
}
});
return builder.create();
}
}
Adapter code:
Code:
class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder>
{
private static final String TAG = "RecyclerViewAdapter";
private List<String> notesList;
private Context mContext;
private SendPositionConnector sendPositionConnector;
public interface SendPositionConnector
{
public void sendPosition(int position);
}
public RecyclerViewAdapter(List<String> notesList, Context mContext)
{
this.notesList = notesList;
this.mContext = mContext;
this.sendPositionConnector = (MainActivity)mContext;
}
@NonNull
@Override
public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType)
{
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.layout_listitem, parent, false);
ViewHolder holder = new ViewHolder(view);
return holder;
}
@Override
public void onBindViewHolder(@NonNull ViewHolder viewHolder, final int position)
{
Log.d(TAG, "onBindViewHandler: called");
viewHolder.noteContent.setText(notesList.get(position));
viewHolder.parentLayout.setOnLongClickListener(new View.OnLongClickListener(){
@Override
public boolean onLongClick(View view)
{
Log.d(TAG, "onLongClick: long clicked on");
sendPositionConnector.sendPosition(position);
return false;
}
});
}
@Override
public int getItemCount()
{
return notesList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder
{
TextView noteContent;
RelativeLayout parentLayout;
ImageView bullet;
public ViewHolder(@NonNull View itemView)
{
super(itemView);
bullet = itemView.findViewById(R.id.bullet);
noteContent = itemView.findViewById(R.id.text_content);
parentLayout = itemView.findViewById(R.id.parent_layout);
}
}
}
Main Activity:
Code:
public class MainActivity extends AppCompatActivity implements RecyclerViewAdapter.SendPositionConnector
{
private static final String TAG = "MainActivity";
private List<String> notesList = new ArrayList<>();
private RecyclerView recyclerView;
private RecyclerViewAdapter adapter;
private int position;
public AgentAsyncTask agentAsyncTask;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = findViewById(R.id.my_recycler_view);
registerForContextMenu(recyclerView);
recyclerView.setLayoutManager(new LinearLayoutManager(this));
agentAsyncTask = new AgentAsyncTask(notesList, getApplicationContext(), true, new AgentAsyncTask.OnRead(){
@Override
public void onRead(List<String> notesList)
{
if(!notesList.isEmpty())
MainActivity.this.notesList = notesList;
adapter = new RecyclerViewAdapter(notesList, MainActivity.this);
recyclerView.setAdapter(adapter);
}
});
agentAsyncTask.execute();
}
@Override
public boolean onCreateOptionsMenu(Menu menu)
{
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.add_menu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item)
{
// Handle item selection
switch (item.getItemId())
{
case R.id.add_note:
showDialogBox(item);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
@Override
protected void onStop()
{
super.onStop();
new AgentAsyncTask(notesList, getApplicationContext(), false, new AgentAsyncTask.OnRead(){
@Override
public void onRead(List<String> notesList)
{
if(!notesList.isEmpty())
MainActivity.this.notesList = notesList;
}
}).execute();
}
@Override
protected void onDestroy()
{
super.onDestroy();
}
private boolean showDialogBox(MenuItem menuItem)
{
AppCompatDialogFragment dialogFragment = new CustomDialog(new CustomDialog.OnNoteAddedListener(){
@Override
public void onClick(String note)
{
Log.d(TAG, "onClick: "+ note);
notesList.add(note);
}
});
dialogFragment.show(getSupportFragmentManager(),"Adding");
return true;
}
@Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo)
{
super.onCreateContextMenu(menu, v, menuInfo);
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.context_menu, menu);
}
@Override
public boolean onContextItemSelected(MenuItem menuItem)
{
switch(menuItem.getItemId())
{
case R.id.delete:
notesList.remove(position);
adapter.notifyItemRemoved(position);
adapter.notifyItemRangeChanged(position, notesList.size());
return true;
default:
return false;
}
}
@Override
public void sendPosition(int position)
{
this.position = position;
}
private static class AgentAsyncTask extends AsyncTask<Void, Void, List<String>>
{
private List<String> notesList;
private boolean flag;
OnRead onRead;
Context context;
AppDataBase dataBase;
private static final String TAG = "AgentAsyncTask";
public interface OnRead
{
public void onRead(List<String> notesList);
}
private AgentAsyncTask(List<String> notesList,Context context,boolean flag, OnRead onRead)
{
this.notesList = notesList;
this.onRead = onRead;
this.flag = flag;
this.context = context;
}
@Override
protected List<String> doInBackground(Void... params)
{
dataBase = Room.databaseBuilder(context, AppDataBase.class, "database-name").build();
if(!flag)
{
Gson gson = new Gson();
Type type = new TypeToken<List<String>>() {}.getType();
String json = gson.toJson(notesList, type);
Log.d(TAG, "doInBackground: "+json);
Notes notes = new Notes();
notes.setNoteContent(json);
notes.setUid(1);
dataBase.notesDao().insertNotes(notes);
return notesList;
}
else
{
Gson gson = new Gson();
String notesListContent = dataBase.notesDao().getNotes();
if(dataBase.notesDao().getCount() != 0)
{
notesList = gson.fromJson(notesListContent, new TypeToken<List<String>>()
{
}.getType());
}
else
{
return notesList;
}
return notesList;
}
}
@Override
protected void onPostExecute(List<String> notesList)
{
super.onPostExecute(notesList);
if(flag)
onRead.onRead(notesList);
}
}
}

Categories

Resources