I am trying to pass a string named 'str' from Cbreceiver.class which extends broadcast receiver to an activity cbdata.java.but i cannot pass the value,i am not getting any errors either.Thank you.Help me with this please
**CbReceiver.class:**
package com.example.Lovisis;
import java.io.UnsupportedEncodingException;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsMessage;
import android.widget.Toast;
public class CbReceiver extends BroadcastReceiver
{
public static class SmsCbHeader {
public static final int PDU_HEADER_LENGTH = 6;
public final int geographicalScope;
public final int messageCode;
public final int updateNumber;
public final int messageIdentifier;
public final int dataCodingScheme;
public final int pageIndex;
public final int nrOfPages;
public SmsCbHeader(byte[] pdu) throws IllegalArgumentException {
if (pdu == null || pdu.length < PDU_HEADER_LENGTH) {
throw new IllegalArgumentException("Illegal PDU");
}
geographicalScope = (pdu[0] & 0xc0) >> 6;
messageCode = ((pdu[0] & 0x3f) << 4) | ((pdu[1] & 0xf0) >> 4);
updateNumber = pdu[1] & 0x0f;
messageIdentifier = (pdu[2] << 8) | pdu[3];
dataCodingScheme = pdu[4];
int pageIndex = (pdu[5] & 0xf0) >> 4;
int nrOfPages = pdu[5] & 0x0f;
if (pageIndex == 0 || nrOfPages == 0 || pageIndex > nrOfPages) {
pageIndex = 1;
nrOfPages = 1;
}
this.pageIndex = pageIndex;
this.nrOfPages = nrOfPages;
}
}
public static class SmsCbMessage {
public static final int GEOGRAPHICAL_SCOPE_CELL_WIDE_IMMEDIATE = 0;
public static final int GEOGRAPHICAL_SCOPE_PLMN_WIDE = 1;
public static final int GEOGRAPHICAL_SCOPE_LA_WIDE = 2;
public static final int GEOGRAPHICAL_SCOPE_CELL_WIDE = 3;
public static SmsCbMessage createFromPdu(byte[] pdu) {
try {
return new SmsCbMessage(pdu);
} catch (IllegalArgumentException e) {
return null;
}
}
private String[] LANGUAGE_CODES_GROUP_0 = {
"de", "en", "it", "fr", "es", "nl", "sv", "da", "pt", "fi", "no", "el", "tr", "hu",
"pl", null
};
private String[] LANGUAGE_CODES_GROUP_2 = {
"cs", "he", "ar", "ru", "is", null, null, null, null, null, null, null, null, null,
null, null
};
private static final char CARRIAGE_RETURN = 0x0d;
private SmsCbHeader mHeader;
private String mLanguage;
private String mBody;
private SmsCbMessage(byte[] pdu) throws IllegalArgumentException {
mHeader = new SmsCbHeader(pdu);
parseBody(pdu);
}
public int getGeographicalScope() {
return mHeader.geographicalScope;
}
public String getLanguageCode() {
return mLanguage;
}
public String getMessageBody() {
return mBody;
}
public int getMessageIdentifier() {
return mHeader.messageIdentifier;
}
public int getMessageCode() {
return mHeader.messageCode;
}
public int getUpdateNumber() {
return mHeader.updateNumber;
}
private void parseBody(byte[] pdu) {
int encoding;
boolean hasLanguageIndicator = false;
switch ((mHeader.dataCodingScheme & 0xf0) >> 4) {
case 0x00:
encoding = SmsMessage.ENCODING_7BIT;
mLanguage = LANGUAGE_CODES_GROUP_0[mHeader.dataCodingScheme & 0x0f];
break;
case 0x01:
hasLanguageIndicator = true;
if ((mHeader.dataCodingScheme & 0x0f) == 0x01) {
encoding = SmsMessage.ENCODING_16BIT;
} else {
encoding = SmsMessage.ENCODING_7BIT;
}
break;
case 0x02:
encoding = SmsMessage.ENCODING_7BIT;
mLanguage = LANGUAGE_CODES_GROUP_2[mHeader.dataCodingScheme & 0x0f];
break;
case 0x03:
encoding = SmsMessage.ENCODING_7BIT;
break;
case 0x04:
case 0x05:
switch ((mHeader.dataCodingScheme & 0x0c) >> 2) {
case 0x01:
encoding = SmsMessage.ENCODING_8BIT;
break;
case 0x02:
encoding = SmsMessage.ENCODING_16BIT;
break;
case 0x00:
default:
encoding = SmsMessage.ENCODING_7BIT;
break;
}
break;
case 0x06:
case 0x07:
case 0x09:
case 0x0e:
encoding = SmsMessage.ENCODING_UNKNOWN;
break;
case 0x0f:
if (((mHeader.dataCodingScheme & 0x04) >> 2) == 0x01) {
encoding = SmsMessage.ENCODING_8BIT;
} else {
encoding = SmsMessage.ENCODING_7BIT;
}
break;
default:
encoding = SmsMessage.ENCODING_7BIT;
break;
}
switch (encoding) {
case SmsMessage.ENCODING_7BIT:
if (hasLanguageIndicator && mBody != null && mBody.length() > 2) {
mLanguage = mBody.substring(0, 2);
mBody = mBody.substring(3);
}
break;
case SmsMessage.ENCODING_16BIT:
int offset = SmsCbHeader.PDU_HEADER_LENGTH;
if (hasLanguageIndicator && pdu.length >= SmsCbHeader.PDU_HEADER_LENGTH + 2) {
offset += 2;
}
try {
mBody = new String(pdu, offset, (pdu.length & 0xfffe) - offset, "utf-16");
} catch (UnsupportedEncodingException e) {
}
break;
default:
break;
}
if (mBody != null) {
for (int i = mBody.length() - 1; i >= 0; i--) {
if (mBody.charAt(i) != CARRIAGE_RETURN) {
mBody = mBody.substring(0, i + 1);
break;
}
}
} else {
mBody = "";
}
}
}
public String str;
public String str1="hello";
public void onReceive(Context context, Intent intent) {
//---get the CB message passed in---
Bundle bundle = intent.getExtras();
SmsCbMessage[] msgs = null;
//str = "";
if (bundle != null) {
//---retrieve the SMS message received---
Object[] pdus = (Object[]) bundle.get("pdus");
msgs = new SmsCbMessage[pdus.length];
for (int i=0; i<msgs.length; i++) {
msgs[i] = SmsCbMessage.createFromPdu((byte[])pdus[i]);
str += "CB :" +msgs[i].getGeographicalScope() + msgs[i].getMessageCode() + msgs[i].getMessageIdentifier() + msgs[i].getUpdateNumber();
//Toast.makeText(context, "" +str, Toast.LENGTH_LONG).show();
}
Toast.makeText(context,str, Toast.LENGTH_LONG).show();
Intent in=new Intent(CbReceiver.this,Cbdata.class);
in.putExtra("cb", str);
abortBroadcast();
}
}
private Context getApplicationContext() {
// TODO Auto-generated method stub
return null;
}
}
**Cbdata.java:**
Remove the OnRecieve() method Use
#Override
protected void onNewIntent(Intent intent) {
Log.d("YourActivity", "onNewIntent is called!");
memberFieldString = intent.getStringExtra("KEY");
super.onNewIntent(intent);
} // End of onNewIntent(Intent intent)
tell me weather its working or not
u can try by creating an object of class Cbreceiver in Cbdata...
eg.
Cbreceiver rec = new Cbreceiver(this);
then directly use the string as rec.str
Related
I have problem with my app. I created simple HostApduService app to comunicate with some reader. My service look:
public class CardService extends HostApduService {
private static final String LOYALTY_CARD_AID = "example id";
private static final String SELECT_APDU_HEADER = "00A40400";
public static final byte[] SELECT_OK = HexStringToByteArray("9000");
private static final byte[] UNKNOWN_CMD = HexStringToByteArray("0000");
private static final byte[] SELECT_APDU = BuildSelectApdu(LOYALTY_CARD_AID);
#Override
public byte[] processCommandApdu(byte[] bArr, Bundle bundle) {
if (!Arrays.equals(SELECT_APDU, bArr)) {
return UNKNOWN_CMD;
}
try {
return ConcatArrays(HexStringToByteArray(AccountStorage.GetAccount(this)), SELECT_OK);
} catch (Exception unused) {
return UNKNOWN_CMD;
}
}
public static byte[] BuildSelectApdu(String str) {
return HexStringToByteArray(SELECT_APDU_HEADER + String.format("%02X", new Object[]{Integer.valueOf(str.length() / 2)}) + str);
}
public static byte[] HexStringToByteArray(String str) throws IllegalArgumentException {
int length = str.length();
if (length % 2 != 1) {
byte[] bArr = new byte[(length / 2)];
for (int i = 0; i < length; i += 2) {
bArr[i / 2] = (byte) ((Character.digit(str.charAt(i), 16) << 4) + Character.digit(str.charAt(i + 1), 16));
}
return bArr;
}
throw new IllegalArgumentException("Hex string must have even number of characters");
}
public static byte[] ConcatArrays(byte[] bArr, byte[]... bArr2) {
int length = bArr.length;
for (byte[] length2 : bArr2) {
length += length2.length;
}
byte[] copyOf = Arrays.copyOf(bArr, length);
int length3 = bArr.length;
for (byte[] bArr3 : bArr2) {
System.arraycopy(bArr3, 0, copyOf, length3, bArr3.length);
length3 += bArr3.length;
}
return copyOf;
}
#Override
public void onDeactivated(int i) { }
}
My AccountStorage
public class AccountStorage {
private static final String DEFAULT_ACCOUNT_NUMBER = "000000000000";
private static final String PREF_ACCOUNT_NUMBER = "account_number";
private static String sAccount;
private static final Object sAccountLock = new Object();
public static void SetAccount(Context context, String str) {
synchronized (sAccountLock) {
PreferenceManager.getDefaultSharedPreferences(context).edit().putString(PREF_ACCOUNT_NUMBER, str).commit();
sAccount = str;
}
}
public static String GetAccount(Context context) {
String str;
synchronized (sAccountLock) {
if (sAccount == null) {
sAccount = PreferenceManager.getDefaultSharedPreferences(context).getString(PREF_ACCOUNT_NUMBER, DEFAULT_ACCOUNT_NUMBER);
}
str = sAccount;
}
return str;
}
}
And my activity
public class MainActivity extends AppCompatActivity implements ActivityCompat.OnRequestPermissionsResultCallback {
String id = "00000";
private boolean mPermision;
private TextView hexText;
private TextView idText;
Button btnStartService;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (Build.VERSION.SDK_INT >= 23) {
ArrayList arrayList = new ArrayList();
if (ContextCompat.checkSelfPermission(getBaseContext(), "android.permission.READ_PHONE_STATE") != 0) {
arrayList.add("android.permission.READ_PHONE_STATE");
}
if (arrayList.size() > 0) {
ActivityCompat.requestPermissions(this, (String[]) arrayList.toArray(new String[0]), 112);
} else {
this.mPermision = true;
}
}
if (this.mPermision) {
id = convertToUID(Settings.Secure.getString(getContentResolver(), Settings.Secure.ANDROID_ID));
}
AccountStorage.SetAccount(this, id);
idText = findViewById(R.id.androidID);
hexText = findViewById(R.id.hex);
btnStartService = findViewById(R.id.buttonStartService);
idText.setText("UID:");
hexText.setText(id);
if (AccountStorage.GetAccount(this).equals("00000")) {
if (btnStartService != null) {
btnStartService.setVisibility(View.VISIBLE);
}
} else {
if (btnStartService != null) {
btnStartService.setVisibility(View.GONE);
}
}
btnStartService.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AccountStorage.SetAccount(getApplicationContext(), id);
hexText.setText(id);
if (AccountStorage.GetAccount(getApplicationContext()).equals("00000")) {
btnStartService.setVisibility(View.VISIBLE);
} else {
btnStartService.setVisibility(View.GONE);
}
}
});
}
#Override
public void onRequestPermissionsResult(int i, #NonNull String[] strArr, #NonNull int[] iArr) {
if (i != 112) {
return;
}
if (iArr.length == 1 && iArr[0] == 0) {
id = convertToUID(Settings.Secure.getString(getContentResolver(), Settings.Secure.ANDROID_ID));
this.mPermision = true;
return;
}
this.mPermision = false;
}
public static String convertToUID(String str) {
boolean z;
byte[] bArr;
byte[] bArr2 = new byte[6];
String iMEIDeviceId = str;
if (iMEIDeviceId.length() == 15) {
int i = 0;
while (true) {
if (i < 14) {
char charAt = iMEIDeviceId.charAt(i);
if (charAt < '0' && charAt > '9') {
z = true;
break;
}
i++;
} else {
break;
}
}
}
z = false;
if (z) {
bArr = ByteBuffer.allocate(8).putLong(Long.parseLong(iMEIDeviceId.substring(0, 14))).array();
} else {
try {
bArr = HexStringToByteArray(iMEIDeviceId);
} catch (Exception unused) {
bArr = new byte[]{-125, 21, 66, -68, -89, 58};
}
}
bArr2[0] = (byte) (bArr[5] ^ 58);
bArr2[1] = (byte) (bArr[1] ^ 21);
bArr2[2] = (byte) (bArr[3] ^ -68);
bArr2[3] = (byte) (bArr[0] ^ -125);
bArr2[4] = (byte) (bArr[4] ^ -89);
bArr2[5] = (byte) (bArr[2] ^ 66);
return ByteArrayToHexString(bArr2);
}
public static byte[] HexStringToByteArray(String str) throws IllegalArgumentException {
int length = str.length();
if (length % 2 != 1) {
byte[] bArr = new byte[(length / 2)];
for (int i = 0; i < length; i += 2) {
bArr[i / 2] = (byte) ((Character.digit(str.charAt(i), 16) << 4) + Character.digit(str.charAt(i + 1), 16));
}
return bArr;
}
throw new IllegalArgumentException("Hex string must have even number of characters");
}
public static String ByteArrayToHexString(byte[] bytes) {
final char[] hexArray = {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
char[] hexChars = new char[bytes.length * 2]; // Each byte has two hex characters (nibbles)
int v;
for (int j = 0; j < bytes.length; j++) {
v = bytes[j] & 0xFF; // Cast bytes[j] to int, treating as unsigned value
hexChars[j * 2] = hexArray[v >>> 4]; // Select hex character from upper nibble
hexChars[j * 2 + 1] = hexArray[v & 0x0F]; // Select hex character from lower nibble
}
return new String(hexChars);
}
}
My app works well when it is installed first time. After I uninstall it and install again it stopping communicating with device. I need to restart my phone and then it again works. I dont know where is the problem. Anyone can help me?
In my MainActivity.Java, I have an onClickListener in a button that will show an Alert Dialog when it's clicked
scanbtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
View scanPopup = getLayoutInflater().inflate(R.layout.scan_tab, null);
forScan.setView(scanPopup);
dialog = forScan.create();
dialog.show();
}
});
This is is the ScanTab.Java wherein the AlertDialog will have its functions
package com.example.AppDraft1.activity;
import android.app.PendingIntent;
import android.content.Intent;
import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.nfc.tech.MifareClassic;
import android.nfc.tech.MifareUltralight;
import android.os.Bundle;
import android.os.Parcelable;
import android.provider.Settings;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import com.example.AppDraft1.MainActivity;
import com.example.AppDraft1.R;
import com.example.AppDraft1.parser.NdefMessageParser;
import com.example.AppDraft1.record.ParsedNdefRecord;
import java.util.List;
public class ScanTab extends AppCompatActivity {
private NfcAdapter nfcAdapter;
private PendingIntent pendingIntent;
private TextView text;
private String first, surname, id;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.scan_tab);
text = (TextView) findViewById(R.id.text);
nfcAdapter = NfcAdapter.getDefaultAdapter(this);
if (nfcAdapter == null) {
Toast.makeText(this, "No NFC", Toast.LENGTH_SHORT).show();
finish();
return;
}
pendingIntent = PendingIntent.getActivity(this, 0,
new Intent(this, this.getClass())
.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
}
#Override
protected void onResume() {
super.onResume();
if (nfcAdapter != null) {
if (!nfcAdapter.isEnabled())
showWirelessSettings();
nfcAdapter.enableForegroundDispatch(this, pendingIntent, null, null);
}
}
#Override
protected void onPause() {
super.onPause();
if (nfcAdapter != null){
nfcAdapter.disableForegroundDispatch(this);
}
}
#Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
setIntent(intent);
resolveIntent(intent);
}
private void resolveIntent(Intent intent) {
String action = intent.getAction();
if (NfcAdapter.ACTION_TAG_DISCOVERED.equals(action)
|| NfcAdapter.ACTION_TECH_DISCOVERED.equals(action)
|| NfcAdapter.ACTION_NDEF_DISCOVERED.equals(action)) {
Parcelable[] rawMsgs = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
NdefMessage[] msgs;
if (rawMsgs != null) {
msgs = new NdefMessage[rawMsgs.length];
for (int i = 0; i < rawMsgs.length; i++) {
msgs[i] = (NdefMessage) rawMsgs[i];
}
} else {
byte[] empty = new byte[0];
byte[] id = intent.getByteArrayExtra(NfcAdapter.EXTRA_ID);
Tag tag = (Tag) intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
byte[] payload = dumpTagData(tag).getBytes();
NdefRecord record = new NdefRecord(NdefRecord.TNF_UNKNOWN, empty, id, payload);
NdefMessage msg = new NdefMessage(new NdefRecord[] {record});
msgs = new NdefMessage[] {msg};
}
displayMsgs(msgs);
}
}
private void displayMsgs(NdefMessage[] msgs) {
if (msgs == null || msgs.length == 0)
return;
StringBuilder builder = new StringBuilder();
List<ParsedNdefRecord> records = NdefMessageParser.parse(msgs[0]);
final int size = records.size();
for (int i = 0; i < size; i++) {
ParsedNdefRecord record = records.get(i);
String str = record.str();
builder.append(str).append("\n");
}
text.setText(builder.toString());
Toast.makeText(this, "NFC Tag Detected", Toast.LENGTH_SHORT).show();
sndData();
}
public void sndData(){
String theText = text.getText().toString();
//split data
String[] split = theText.split("/",3);
first = split[0]; //first name
surname = split[1]; //surname
id = split[2]; //id number
Intent intent = new Intent(ScanTab.this, MainActivity.class);
intent.putExtra("FName", first);
intent.putExtra("SName", surname);
intent.putExtra("ID", id);
startActivity(intent);
}
private void showWirelessSettings() {
Toast.makeText(this, "You need to enable NFC", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(Settings.ACTION_WIRELESS_SETTINGS);
startActivity(intent);
}
private String dumpTagData(Tag tag) {
StringBuilder sb = new StringBuilder();
byte[] id = tag.getId();
sb.append("ID (hex): ").append(toHex(id)).append('\n');
sb.append("ID (reversed hex): ").append(toReversedHex(id)).append('\n');
sb.append("ID (dec): ").append(toDec(id)).append('\n');
sb.append("ID (reversed dec): ").append(toReversedDec(id)).append('\n');
String prefix = "android.nfc.tech.";
sb.append("Technologies: ");
for (String tech : tag.getTechList()) {
sb.append(tech.substring(prefix.length()));
sb.append(", ");
}
sb.delete(sb.length() - 2, sb.length());
for (String tech : tag.getTechList()) {
if (tech.equals(MifareClassic.class.getName())) {
sb.append('\n');
String type = "Unknown";
try {
MifareClassic mifareTag = MifareClassic.get(tag);
switch (mifareTag.getType()) {
case MifareClassic.TYPE_CLASSIC:
type = "Classic";
break;
case MifareClassic.TYPE_PLUS:
type = "Plus";
break;
case MifareClassic.TYPE_PRO:
type = "Pro";
break;
}
sb.append("Mifare Classic type: ");
sb.append(type);
sb.append('\n');
sb.append("Mifare size: ");
sb.append(mifareTag.getSize() + " bytes");
sb.append('\n');
sb.append("Mifare sectors: ");
sb.append(mifareTag.getSectorCount());
sb.append('\n');
sb.append("Mifare blocks: ");
sb.append(mifareTag.getBlockCount());
} catch (Exception e) {
sb.append("Mifare classic error: " + e.getMessage());
}
}
if (tech.equals(MifareUltralight.class.getName())) {
sb.append('\n');
MifareUltralight mifareUlTag = MifareUltralight.get(tag);
String type = "Unknown";
switch (mifareUlTag.getType()) {
case MifareUltralight.TYPE_ULTRALIGHT:
type = "Ultralight";
break;
case MifareUltralight.TYPE_ULTRALIGHT_C:
type = "Ultralight C";
break;
}
sb.append("Mifare Ultralight type: ");
sb.append(type);
}
}
return sb.toString();
}
private String toHex(byte[] bytes) {
StringBuilder sb = new StringBuilder();
for (int i = bytes.length - 1; i >= 0; --i) {
int b = bytes[i] & 0xff;
if (b < 0x10)
sb.append('0');
sb.append(Integer.toHexString(b));
if (i > 0) {
sb.append(" ");
}
}
return sb.toString();
}
private String toReversedHex(byte[] bytes) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < bytes.length; ++i) {
if (i > 0) {
sb.append(" ");
}
int b = bytes[i] & 0xff;
if (b < 0x10)
sb.append('0');
sb.append(Integer.toHexString(b));
}
return sb.toString();
}
private long toDec(byte[] bytes) {
long result = 0;
long factor = 1;
for (int i = 0; i < bytes.length; ++i) {
long value = bytes[i] & 0xffl;
result += value * factor;
factor *= 256l;
}
return result;
}
private long toReversedDec(byte[] bytes) {
long result = 0;
long factor = 1;
for (int i = bytes.length - 1; i >= 0; --i) {
long value = bytes[i] & 0xffl;
result += value * factor;
factor *= 256l;
}
return result;
}
}
When I tested it, the view is working but the functions are absent. How do I embed or make the functions work in the AlertDialog?
Alert Dialogs are meant to 'alert' the user of something, or run code based on input from user in case of input dialog.
If you want to run code in the alert dialog, you can run it before setView of dialog.
Additionally it is not recommended to block user from interacting with app using an Alert Dialog.
If you want to run code from one activity in another, in your case run code in ScanActivity from MainActivity the best way I can think of is Activity RESULTS API which replaced StartActivityForResult [read here]
But I would just recommended you start ScanActivity and show the dialog from there, then you can easily call all methods of ScanActivity.
i have downloaded a android game program from internet and i tried to run it gives error on Method and goto statement.
i know goto statement is not support in java..
i dont know they are any other tool or language .
i want to know which technology or tool or language they are used.
this is the code
package com.infraredpixel.drop.activities;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.graphics.RectF;
import android.hardware.Sensor;
import android.hardware.SensorManager;
import android.opengl.GLSurfaceView;
import android.os.*;
import android.util.Log;
import android.view.*;
import com.infraredpixel.drop.*;
import java.lang.reflect.Method;
import java.util.List;
// Referenced classes of package com.infraredpixel.drop.activities:
// ProfilingActivity, DebugActivity, MainMenuActivity
public class OpenGLDropActivity extends Activity
{
public OpenGLDropActivity()
{
}
private int getDefaultRotation()
{
int i;
WindowManager windowmanager;
Method amethod[];
String s;
int j;
i = 0;
windowmanager = (WindowManager)getSystemService("window");
amethod = windowmanager.getDefaultDisplay().getClass().getDeclaredMethods();
s = new String("getRotation");
j = amethod.length;
_L2:
Method method = null;
Display display;
if(i < j)
{
label0:
{
Method method1 = amethod[i];
Log.d("Methods", method1.getName());
if(!method1.getName().equals(s))
break label0;
method = method1;
}
}
display = windowmanager.getDefaultDisplay();
if(method != null)
{
int k;
try
{
k = ((Integer)method.invoke(display, new Object[0])).intValue();
}
catch(Exception exception)
{
return 0;
}
return k;
} else
{
return display.getOrientation();
}
i++;
if(true){ goto _L2;} else{ goto _L1;}
_L1:
}
protected void handleScore()
{
int i;
int j;
SharedPreferences sharedpreferences;
int k;
String s;
i = (int)(0.49F + (float)_StatusManager.dropDist());
j = (int)(0.49F + (float)_StatusManager.getStars());
sharedpreferences = getSharedPreferences("DropSettings", 0);
k = sharedpreferences.getInt("highScore", -1);
s = "";
if(2 != _ControlMode) goto _L2; else goto _L1;
_L1:
s = "tiltHighScore";
_L4:
int l = sharedpreferences.getInt(s, 0);
if(i + j > k && i + j > l)
{
_DeathDetector.setCurrentHighScore(i + j);
android.content.SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putInt("highScore", -1);
editor.putInt(s, i + j);
editor.commit();
}
return;
_L2:
if(1 == _ControlMode || _ControlMode == 0)
s = "touchHighScore";
if(true) goto _L4; else goto _L3
_L3:
}
public void onCreate(Bundle bundle)
{
SharedPreferences sharedpreferences;
super.onCreate(bundle);
sharedpreferences = getSharedPreferences("DropSettings", 0);
spriteRenderer = new GLRenderer(getApplicationContext());
int i = sharedpreferences.getInt("fullScreenWidth", 480);
widthPixels = i;
int j = sharedpreferences.getInt("fullScreenHeight", 640);
RectF rectf = new RectF(0.0F, j, i, 0.0F);
boolean flag = sharedpreferences.getBoolean("useVibration", true);
boolean flag1 = sharedpreferences.getBoolean("godMode", false);
int k = sharedpreferences.getInt("ballType", 0);
int l = Math.max(sharedpreferences.getInt("highScore", 0), Math.max(sharedpreferences.getInt("tiltHighScore", 0), sharedpreferences.getInt("touchHighScore", 0)));
_ControlMode = sharedpreferences.getInt("controlMode", 2);
boolean flag2 = sharedpreferences.getBoolean("testModeDropSettings", false);
boolean flag3 = sharedpreferences.getBoolean("testModeMainSettings", false);
DropSettingsGroup adropsettingsgroup[];
DropManager dropmanager;
Handler handler;
Runnable runnable;
boolean flag4;
boolean flag5;
boolean flag6;
Runnable runnable1;
int k1;
float f;
float f1;
float f2;
float f3;
float f4;
float f5;
if(flag2)
{
adropsettingsgroup = new DropSettingsGroup[1];
adropsettingsgroup[0] = new DropSettingsGroup();
adropsettingsgroup[0].scrollSpeed = -sharedpreferences.getInt("scrollSpeed", getResources().getInteger(0x7f010000));
adropsettingsgroup[0].platformHeight = sharedpreferences.getInt("platformHeight", getResources().getInteger(0x7f050006));
adropsettingsgroup[0].platformHoleWidth = 70;
adropsettingsgroup[0].yAccel = sharedpreferences.getInt("yAcceleration", getResources().getInteger(0x7f050001));
adropsettingsgroup[0].yMaxSpeed = sharedpreferences.getInt("yMaxSpeed", getResources().getInteger(0x7f050002));
adropsettingsgroup[0].yBounce = 0.7F;
adropsettingsgroup[0].xAccel = sharedpreferences.getInt("xAcceleration", getResources().getInteger(0x7f050003));
adropsettingsgroup[0].xMaxSpeed = sharedpreferences.getInt("xMaxSpeed", getResources().getInteger(0x7f050004));
adropsettingsgroup[0].xBounce = sharedpreferences.getFloat("xBounce", 0.5F);
adropsettingsgroup[0].duration = 20F;
adropsettingsgroup[0].transitionTiles = false;
} else
if(_ControlMode == 0 || _ControlMode == 1)
adropsettingsgroup = DropSettingsGroup.getTestSettingsA();
else
adropsettingsgroup = DropSettingsGroup.getTestSettingsB();
dropmanager = new DropManager(rectf, adropsettingsgroup);
_DropManager = dropmanager;
if(flag)
_DropManager.init(spriteRenderer, getBaseContext(), k, (float)widthPixels / 320F, (Vibrator)getSystemService("vibrator"));
else
_DropManager.init(spriteRenderer, getBaseContext(), k, (float)widthPixels / 320F, null);
_StatusManager = new StatusManager();
_StatusManager.init(spriteRenderer, getBaseContext(), (float)widthPixels / 320F, rectf);
_GameOverLayer = new GameOverLayer();
_GameOverLayer.init(spriteRenderer, rectf);
handler = new Handler();
runnable = new Runnable() {
public void run()
{
handleScore();
}
final OpenGLDropActivity this$0;
{
this$0 = OpenGLDropActivity.this;
super();
}
}
;
_DeathDetector = new DeathDetector(rectf, _DropManager, _StatusManager, _GameOverLayer, handler, runnable);
_DeathDetector.setCurrentHighScore(l);
if(_ControlMode != 0) goto _L2; else goto _L1
_L1:
ControlComponent.inAirMovementFactor = 0.3F;
ControlComponent.inAirMemoryMovementFactor = 0.08F;
DropManager.speed = 1.0F;
_L4:
if(flag3)
{
k1 = sharedpreferences.getInt("movingAverageValue", 10);
f = sharedpreferences.getFloat("sensorCutoffX", 5F);
f1 = sharedpreferences.getFloat("inAirBreak", 0.3F);
f2 = sharedpreferences.getFloat("inAirMemory", 0.08F);
f3 = sharedpreferences.getFloat("gameSpeed", 1.0F);
f4 = sharedpreferences.getFloat("tiltAccelFactor", 1.0F);
f5 = sharedpreferences.getFloat("tiltAccelDiffFactor", 1.0F);
MySensorEventListener.SENSOR_CUTOFF_X = f;
MySensorEventListener.kFilteringFactor = 1.0F / (float)k1;
MySensorEventListener.accelFactor = f4;
MySensorEventListener.diffFactor = f5;
ControlComponent.inAirMovementFactor = 1.0F - f1;
ControlComponent.inAirMemoryMovementFactor = f2;
DropManager.speed = f3;
}
flag4 = sharedpreferences.getBoolean("canUseDrawTexture", true);
flag5 = sharedpreferences.getBoolean("canUseVBO", true);
GLSprite.shouldUseDrawTexture = flag4;
spriteRenderer.setVertMode(flag5);
ProfileRecorder.sSingleton.resetAll();
_StatusManager.setBall(_DropManager.getBall());
_DropManager.getCollisionComponent().setStatusManager(_StatusManager);
_ControlComponent = _DropManager.getControlComponent();
spriteRenderer.endInit();
simulationRuntime = new MainLoop();
if(!flag1)
simulationRuntime.addGameObject(_DeathDetector);
simulationRuntime.addGameObject(_DropManager);
simulationRuntime.addGameObject(_StatusManager);
simulationRuntime.addGameObject(_GameOverLayer);
setContentView(0x7f030001);
flag6 = sharedpreferences.getBoolean("glSafeMode", false);
mGLSurfaceView = (GLSurfaceView)findViewById(0x7f08001f);
mGLSurfaceView.setRenderer(spriteRenderer);
mGLSurfaceView.setEvent(simulationRuntime);
mGLSurfaceView.setSafeMode(flag6);
runnable1 = new Runnable() {
public void run()
{
android.content.SharedPreferences.Editor editor = getSharedPreferences("DropSettings", 0).edit();
editor.putString("testError", mGLSurfaceView.getLastError());
editor.commit();
Intent intent = new Intent(getApplicationContext(), com/infraredpixel/drop/activities/MainMenuActivity);
intent.putExtra("justCrashed", true);
startActivity(intent);
finish();
}
final OpenGLDropActivity this$0;
{
this$0 = OpenGLDropActivity.this;
super();
}
}
;
mGLSurfaceView.setErrorMethod(runnable1);
sResetFlag = false;
Runtime.getRuntime().gc();
return;
_L2:
if(_ControlMode == 1)
{
ControlComponent.inAirMovementFactor = 0.3F;
ControlComponent.inAirMemoryMovementFactor = 0.08F;
DropManager.speed = 1.0F;
} else
if(_ControlMode == 2)
{
mWakeLock = ((PowerManager)getSystemService("power")).newWakeLock(10, "Drop");
mWakeLock.acquire();
SensorManager sensormanager = (SensorManager)getSystemService("sensor");
List list = sensormanager.getSensorList(1);
int i1 = list.size();
Sensor sensor = null;
if(i1 > 0)
sensor = (Sensor)list.get(0);
int j1 = getDefaultRotation();
MySensorEventListener mysensoreventlistener = new MySensorEventListener(_DropManager, _DeathDetector, j1);
_MyMotionListener = mysensoreventlistener;
sensormanager.registerListener(_MyMotionListener, sensor, 1);
MySensorEventListener.SENSOR_CUTOFF_X = 8.3F + 4.5F * (1.0F - sharedpreferences.getFloat("tiltSensitivity", 0.3F));
MySensorEventListener.kFilteringFactor = 1.0F;
ControlComponent.inAirMovementFactor = 1.0F;
ControlComponent.inAirMemoryMovementFactor = 0.0F;
DropManager.speed = 1.0F;
MySensorEventListener.accelFactor = 1.0F;
MySensorEventListener.diffFactor = 2.0F;
}
if(true) goto _L4; else goto _L3
_L3:
}
public boolean onCreateOptionsMenu(Menu menu)
{
if(!TESTING)
{
return super.onCreateOptionsMenu(menu);
} else
{
menu.add(0, 1, 0, "profile");
menu.add(0, 2, 0, "debug/test");
menu.add(0, 3, 0, "main menu");
menu.add(0, 4, 0, "pause/resume");
return true;
}
}
protected void onDestroy()
{
if(mWakeLock != null && mWakeLock.isHeld())
{
mWakeLock.release();
mWakeLock = null;
}
SensorManager sensormanager = (SensorManager)getSystemService("sensor");
if(_MyMotionListener != null)
{
sensormanager.unregisterListener(_MyMotionListener);
_MyMotionListener = null;
}
mGLSurfaceView = null;
_DropManager = null;
_StatusManager = null;
_DeathDetector = null;
_GameOverLayer = null;
simulationRuntime = null;
_ControlComponent = null;
super.onDestroy();
}
public boolean onKeyDown(int i, KeyEvent keyevent)
{
if(_ControlMode == 1)
{
if(i == 82 || i == 21)
{
_ControlComponent.autoBreak = false;
_ControlComponent.moveLeft();
_LeftPressed = true;
return true;
}
if(i == 84 || i == 22)
{
_ControlComponent.autoBreak = false;
_ControlComponent.moveRight();
_RightPressed = true;
return true;
} else
{
return super.onKeyDown(i, keyevent);
}
} else
{
return super.onKeyDown(i, keyevent);
}
}
public boolean onKeyUp(int i, KeyEvent keyevent)
{
if(_ControlMode != 1)
break MISSING_BLOCK_LABEL_102;
if(i != 82 && i != 21) goto _L2; else goto _L1
_L1:
boolean flag;
_LeftPressed = false;
flag = true;
_L5:
if(!_LeftPressed && !_RightPressed)
_ControlComponent.stopMovement();
if(!_DeathDetector.getDeathOccured())
_DropManager.start();
if(flag)
return true;
else
return super.onKeyUp(i, keyevent);
_L2:
if(i == 84) goto _L4; else goto _L3
_L3:
flag = false;
if(i != 22) goto _L5; else goto _L4
_L4:
_RightPressed = false;
flag = true;
goto _L5
return super.onKeyUp(i, keyevent);
}
public boolean onOptionsItemSelected(MenuItem menuitem)
{
switch(menuitem.getItemId())
{
default:
return false;
case 1: // '\001'
finish();
startActivity(new Intent(mGLSurfaceView.getContext(), com/infraredpixel/drop/activities/ProfilingActivity));
return true;
case 2: // '\002'
finish();
startActivity(new Intent(mGLSurfaceView.getContext(), com/infraredpixel/drop/activities/DebugActivity));
return true;
case 3: // '\003'
finish();
startActivity(new Intent(mGLSurfaceView.getContext(), com/infraredpixel/drop/activities/MainMenuActivity));
return true;
case 4: // '\004'
break;
}
if(simulationRuntime.isPaused())
{
simulationRuntime.unPause();
mGLSurfaceView.onResume();
} else
{
simulationRuntime.pause();
mGLSurfaceView.onPause();
}
return true;
}
protected void onPause()
{
mGLSurfaceView.onPause();
if(mWakeLock != null && mWakeLock.isHeld())
mWakeLock.release();
if(_ControlMode == 2)
{
SensorManager sensormanager = (SensorManager)getSystemService("sensor");
if(_MyMotionListener != null)
sensormanager.unregisterListener(_MyMotionListener);
}
super.onPause();
}
protected void onResume()
{
mGLSurfaceView.onResume();
if(sResetFlag)
{
handleScore();
_DropManager.reset();
sResetFlag = false;
}
if(mWakeLock != null && !mWakeLock.isHeld())
mWakeLock.acquire();
if(_ControlMode == 2)
{
SensorManager sensormanager = (SensorManager)getSystemService("sensor");
List list = sensormanager.getSensorList(1);
int i = list.size();
Sensor sensor = null;
if(i > 0)
sensor = (Sensor)list.get(0);
sensormanager.registerListener(_MyMotionListener, sensor, 1);
}
super.onResume();
}
protected void onStart()
{
super.onStart();
}
public boolean onTouchEvent(MotionEvent motionevent)
{
if(!_GameOverLayer.isEnabled()) goto _L2; else goto _L1
_L1:
boolean flag;
int k = motionevent.getAction();
flag = false;
if(k == 0)
{
_GameOverLayer.doNextStep();
flag = true;
}
_L4:
int i;
ControlComponent controlcomponent;
int j;
float f;
try
{
Thread.sleep(20L);
}
catch(InterruptedException interruptedexception)
{
interruptedexception.printStackTrace();
return flag;
}
return flag;
_L2:
i = _ControlMode;
flag = false;
if(i == 0)
{
controlcomponent = _ControlComponent;
flag = false;
if(controlcomponent != null)
{
j = motionevent.getAction();
f = motionevent.getX();
if(j == 2)
{
if((float)(widthPixels / 2) < f)
_ControlComponent.moveRight();
else
_ControlComponent.moveLeft();
flag = true;
} else
if(j == 0)
{
if((float)(widthPixels / 2) < f)
_ControlComponent.moveRight();
else
_ControlComponent.moveLeft();
if(!_DeathDetector.getDeathOccured())
_DropManager.start();
flag = true;
} else
{
flag = false;
if(j == 1)
{
_ControlComponent.stopMovement();
flag = true;
}
}
}
}
if(true) goto _L4; else goto _L3
_L3:
}
public boolean onTrackballEvent(MotionEvent motionevent)
{
if(_ControlMode == 1)
{
if(!_DeathDetector.getDeathOccured())
_DropManager.start();
float f = motionevent.getX();
_ControlComponent.autoBreak = true;
_ControlComponent.moveSideways(3.5F * f);
return true;
} else
{
return super.onTrackballEvent(motionevent);
}
}
public static final int CONTROL_MODE_KEYS = 1;
public static final int CONTROL_MODE_TILT = 2;
public static final int CONTROL_MODE_TOUCH = 0;
public static final String PREFS_NAME = "DropSettings";
private static boolean TESTING = false;
protected static boolean sResetFlag;
private ControlComponent _ControlComponent;
private int _ControlMode;
DeathDetector _DeathDetector;
DropManager _DropManager;
private GameOverLayer _GameOverLayer;
private boolean _LeftPressed;
MySensorEventListener _MyMotionListener;
private boolean _RightPressed;
StatusManager _StatusManager;
private GLSurfaceView mGLSurfaceView;
protected android.os.PowerManager.WakeLock mWakeLock;
MainLoop simulationRuntime;
private GLRenderer spriteRenderer;
private int widthPixels;
}
the program gives many error..
What you have here is not real Java, and you should not be using it as an example to learn Java programming from.
So what actually is this stuff?
It looks to me like someone has attempted to decompile an Android app, and the decompiler was unable to turn some of the code back into real Java. Instead, the decompiler has inserted goto "statements" in an attempt to convey the meaning of the code to the (human) reader.
This is obviously the output of a decompilation. While this is a good way to gain specific insight into programs, it's not beginner-level material just like #Jägermeister said, because jads lack the clarity and brevity of standard Java source code.
For example, the goto keyword is not supported on the source code side of the JDK, but it is used inside the byte code in the form of jump instructions. Breaks, continues, loops, ifs etc. may be turned into jumps in surjective ways. The decompiler cannot restore the original construct and resorts to just putting the gotos and labels in the jad. It's up to the programmer to restore reasonable, compilable flow constructs.
That said, the comprehensive answer to your question would be: it's java, but rather an image of the byte code stuff, not a strict restoration of the source code, and requires a manual touch-up to be compilable again.
I dont understand why my app keep crashing. THe google analytics keeps saying that this crash is the most common on my app and i cant fix it. I have looked over the code multiple times and dont know how to fix the issue.
Here is error:
java.lang.IllegalStateException: Could not execute method of the activity
at android.view.View$1.onClick(View.java:3969)
at android.view.View.performClick(View.java:4640)
at android.view.View$PerformClick.run(View.java:19421)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5579)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1268)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1084)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.reflect.InvocationTargetException
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at android.view.View$1.onClick(View.java:3964)
... 11 more
Caused by: java.lang.NullPointerException
at com.soloinc.meip.RecordRap.onClick(RecordRap.java:371)
... 14 more
Here is recordrap
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_record_rap);
//instrument name from previous activity
instrument_file_name = getIntent().getExtras().getString("instrument_file_name");
instrument_title = getIntent().getExtras().getString("instrument_title");
TextView tv = (TextView) findViewById(R.id.instrument_title);
tv.setText(instrument_title);
//getting buffer size for our audio specification
bufferSize = AudioRecord.getMinBufferSize(RECORDER_SAMPLERATE,RECORDER_CHANNELS,RECORDER_AUDIO_ENCODING);
//setting listeners for seek bars
seekBar1 = (SeekBar)(findViewById(R.id.seekBar1));
seekBar1.setOnSeekBarChangeListener(osbcl);
seekBar2 = (SeekBar)(findViewById(R.id.seekBar2));
seekBar2.setOnSeekBarChangeListener(osbcl);
// Get the AudioManager
AudioManager audioManager =
(AudioManager)this.getSystemService(Context.AUDIO_SERVICE);
// Set the volume of played media to maximum.
audioManager.setStreamVolume (
AudioManager.STREAM_MUSIC,
audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC),
0);
//saving beats data in List
if(savedInstanceState == null)
new SaveInputStreamTask(this).execute();
}
#Override
public void onStart() {
super.onStart();
// The rest of your onStart() code.
EasyTracker.getInstance(this).activityStart(this); // Add this method.
}
#Override
public void onStop() {
super.onStop();
// The rest of your onStop() code.
EasyTracker.getInstance(this).activityStop(this); // Add this method.
}
//Listener for seek bars
final SeekBar.OnSeekBarChangeListener osbcl = new SeekBar.OnSeekBarChangeListener() {
#Override
public void onStopTrackingTouch(SeekBar arg0) {
if(arg0.getId() == R.id.seekBar1)
{
seekBar1Value = arg0.getProgress();
Toast.makeText(getApplicationContext(), "Beat Volume:"+seekBar1Value, Toast.LENGTH_SHORT).show();
}
else
{
seekBar2Value = arg0.getProgress();
Toast.makeText(getApplicationContext(), "Lyrics Volume:"+seekBar2Value, Toast.LENGTH_SHORT).show();
}
simultaneousPlay();//whenever volume value changes play audios again to show change in volume level
}
#Override
public void onStartTrackingTouch(SeekBar arg0) {}
#Override
public void onProgressChanged(SeekBar arg0, int arg1, boolean arg2) {}
};
//initializing mediaplayer for playing beat
private void initializePlayer()
{
try
{
//int resID=getResources().getIdentifier(instrument_file_name.substring(0,instrument_file_name.length()-4), "raw", getPackageName());
player = MediaPlayer.create(this,Uri.parse(instrument_file_name));
player.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer arg0) {
isPlayingInstrument = false;
}
});
}
catch(Exception e)
{
System.out.print(e.getMessage());
}
}
//return file name with current millisecond
private String getFilename()
{
String filepath = Environment.getExternalStorageDirectory().getPath();
File file = new File(filepath,MEIP_FOLDER);
if(!file.exists()){
file.mkdirs();
}
String temp = file.getAbsolutePath() + "/" + mixed_file_name + MEIP_FILE_EXT_WAV;
recorded_rap_file_name = temp;
return temp;
}
//return temporary fileName
private String getTempFilename()
{
String filepath = Environment.getExternalStorageDirectory().getPath();
File file = new File(filepath,MEIP_FOLDER);
if(!file.exists()){
file.mkdirs();
}
return (file.getAbsolutePath() + "/" + MEIP_TEMP_FILE);
}
//This function records user voice
private void startRecording()
{
recorder = new AudioRecord(MediaRecorder.AudioSource.MIC,RECORDER_SAMPLERATE, RECORDER_CHANNELS,RECORDER_AUDIO_ENCODING, bufferSize);
recorder.startRecording();
isRecording = true;
recordingThread = new Thread(new Runnable() {
#Override
public void run()
{
saveLyricsPCMData(recorder);
//writePCMDataToFile(getTempFilename(),recorder);
}
},"AudioRecorder Thread");
recordingThread.start();
}
//this function saves recording PCM data to temp file
private void saveLyricsPCMData(AudioRecord ar)
{
short data[] = new short[bufferSize];
lyricsShortList.clear();
int read = 0;
while(isRecording)
{
read = ar.read(data, 0, bufferSize);
if(AudioRecord.ERROR_INVALID_OPERATION != read)
{
for(int k = 0; k < read; k++)
{
lyricsShortList.add(data[k]);
}
}
}
}
//this function executes when user stop recording
private void stopRecording()
{
if(null != recorder)
{
isRecording = false;
recorder.stop();
recorder.release();
recorder = null;
recordingThread = null;
}
//writePCMToWaveFile(getTempFilename(),getFilename());
//deleteTempFile();
}
//this function writes wav file header to out
private void WriteWaveFileHeader(FileOutputStream out, long totalAudioLen,long totalDataLen, long longSampleRate, int channels,long byteRate) throws IOException
{
byte[] header = new byte[44];
header[0] = 'R'; // RIFF/WAVE header
header[1] = 'I';
header[2] = 'F';
header[3] = 'F';
header[4] = (byte) (totalAudioLen & 0xff);
header[5] = (byte) ((totalAudioLen >> 8) & 0xff);
header[6] = (byte) ((totalAudioLen >> 16) & 0xff);
header[7] = (byte) ((totalAudioLen >> 24) & 0xff);
header[8] = 'W';
header[9] = 'A';
header[10] = 'V';
header[11] = 'E';
header[12] = 'f'; // 'fmt ' chunk
header[13] = 'm';
header[14] = 't';
header[15] = ' ';
header[16] = 16; // 4 bytes: size of 'fmt ' chunk
header[17] = 0;
header[18] = 0;
header[19] = 0;
header[20] = 1; // format = 1
header[21] = 0;
header[22] = (byte) channels;
header[23] = 0;
header[24] = (byte) (longSampleRate & 0xff);
header[25] = (byte) ((longSampleRate >> 8) & 0xff);
header[26] = (byte) ((longSampleRate >> 16) & 0xff);
header[27] = (byte) ((longSampleRate >> 24) & 0xff);
header[28] = (byte) (byteRate & 0xff);
header[29] = (byte) ((byteRate >> 8) & 0xff);
header[30] = (byte) ((byteRate >> 16) & 0xff);
header[31] = (byte) ((byteRate >> 24) & 0xff);
header[32] = (byte) ((RECORDER_BPP*channels) / 8); // block align
header[33] = 0;
header[34] = RECORDER_BPP; // bits per sample
header[35] = 0;
header[36] = 'd';
header[37] = 'a';
header[38] = 't';
header[39] = 'a';
header[40] = (byte) (totalDataLen & 0xff);
header[41] = (byte) ((totalDataLen >> 8) & 0xff);
header[42] = (byte) ((totalDataLen >> 16) & 0xff);
header[43] = (byte) ((totalDataLen >> 24) & 0xff);
out.write(header, 0, 44);
}
//onClick listeners for all the buttons
#Override
public void onClick(View view)
{
final Chronometer myChronometer = (Chronometer)findViewById(R.id.chronometer);
switch(view.getId())
{
case R.id.play_button:
if(isPlayingInstrument == false)
{
if(player == null){initializePlayer();}
isPlayingInstrument = true;
player.start();
myChronometer.setBase(SystemClock.elapsedRealtime());
}
break;
case R.id.pause_button:
line 366 player.pause();
isPlayingInstrument = false;
break;
case R.id.stop_button:
line 371 player.stop();
player = null;
isPlayingInstrument = false;
play_thread_running = false;
break;
case R.id.start_recording_button:
if(isRecording == false)
{
((ImageButton)findViewById(R.id.start_recording_button)).setImageResource(R.drawable.button_pause);
startRecording();
myChronometer.start();
}
break;
case R.id.stop_recording_button:
stopRecording();
myChronometer.stop();
play_thread_running = false;
((ImageButton)findViewById(R.id.start_recording_button)).setImageResource(R.drawable.button_record);
break;
case R.id.mix_and_play_button:
simultaneousPlay();
break;
case R.id.save_recording_button:
showDialog();
break;
case R.id.share_button:
share();
break;
}
}
public void share(){
if( mixed_file_name == null || mixed_file_name.equals(""))
{
Toast.makeText(this, "Save Your Song First!", Toast.LENGTH_SHORT).show();
return;
}
Bundle data = new Bundle();
data.putString("SHAREFILE", getFilename());
Message msg = mShareHandler.obtainMessage();
msg.setData(data);
mShareHandler.sendMessage(msg);
}
//play beat and lyrics simultaneously
public void simultaneousPlay()
{
if(play_thread_running == true){play_thread_running = false;}
try
{
beat_playing_thread = new Thread(new Runnable() {
#Override
public void run() {
play(buildShortArray(beatsShortList),seekBar1Value);
}
});
lyrics_playing_thread = new Thread(new Runnable() {
#Override
public void run() {
play(buildShortArray(lyricsShortList),seekBar2Value);
}
});
beat_playing_thread.start();
lyrics_playing_thread.start();
}
catch(Exception ex)
{
ex.printStackTrace();
}
}
//play an audio file
private void play(final short[] soundData, final int volume)
{
short[] output = new short[soundData.length];
// find the max:
float max = 0;
for (int i = 44; i < output.length; i++)
{
if (Math.abs((soundData[i])) > max)
{
max = Math.abs((soundData[i]));
}
}
// now find the result, with scaling:
float a,c;
for (int i = 44; i < output.length; i++)
{
a = (float)(soundData[i]);
c = Math.round(Short.MAX_VALUE * (a)/ max);
if (c > Short.MAX_VALUE)
c = Short.MAX_VALUE;
if (c < Short.MIN_VALUE)
c = Short.MIN_VALUE;
output[i] = (short) c;
}
AudioTrack audioTrack = new AudioTrack(AudioManager.STREAM_MUSIC, 22050, AudioFormat.CHANNEL_CONFIGURATION_MONO, AudioFormat.ENCODING_PCM_16BIT, bufferSize, AudioTrack.MODE_STREAM);
play_thread_running = true;
audioTrack.play();
audioTrack.setStereoVolume((float)(volume/100.0f), (float)(volume/100.0f));
int bufferSize = 512;
ShortBuffer sb = ShortBuffer.wrap(output);
short[] buffer = new short[bufferSize];
for(int i = 0 ; i < output.length-512 && play_thread_running == true; i = i+512)
{
sb.get(buffer, 0, 512);
audioTrack.write(buffer, 0, 512);
}
}
//this function mix audios
private byte[] mixSound() throws IOException
{
completeStreams(beatsShortList,lyricsShortList);
short[] output = new short[beatsShortList.size()];
// find the max:
float max = 0;
for (int i = 44; i < output.length; i++)
{
if (Math.abs((beatsShortList.get(i)*(seekBar1Value/100.0f)) + (lyricsShortList.get(i)*(seekBar2Value/100.0f))) > max)
{
max = Math.abs((beatsShortList.get(i)*(seekBar1Value/100.0f)) + (lyricsShortList.get(i)*(seekBar2Value/100.0f)));
}
}
// now find the result, with scaling:
float a, b, c;
for (int i = 44; i < output.length; i++) {
a = beatsShortList.get(i)*(seekBar1Value/100.0f);
b = lyricsShortList.get(i)*(seekBar2Value/100.0f);
c = Math.round(Short.MAX_VALUE * (a + b)/ max);
if (c > Short.MAX_VALUE)
c = Short.MAX_VALUE;
if (c < Short.MIN_VALUE)
c = Short.MIN_VALUE;
output[i] = (short) c;
}
ByteBuffer bb = ByteBuffer.allocate(output.length * 2);
bb.order(ByteOrder.LITTLE_ENDIAN);
bb.asShortBuffer().put(output);
byte[] bytes = bb.array();
return bytes;
}
//convert inputstream to byte array
public static byte[] getBytesFromInputStream(InputStream is)
{
ByteArrayOutputStream os = new ByteArrayOutputStream();
try
{
byte[] buffer = new byte[0xFFFF];
for (int len; (len = is.read(buffer)) != -1;)
os.write(buffer, 0, len);
os.flush();
return os.toByteArray();
}
catch (IOException e)
{
return null;
}
}
public void saveInputStream(InputStream is) throws IOException
{
int n = 0;
DataInputStream in1;
in1 = new DataInputStream(is);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try
{
while ((n = in1.read()) != -1)
{
bos.write(n);
}
}
catch (IOException e)
{
e.printStackTrace();
}
ByteBuffer bb = ByteBuffer.wrap(bos.toByteArray());
bb.order(ByteOrder.LITTLE_ENDIAN);
ShortBuffer sb = bb.asShortBuffer();
for (int i = 0; i < sb.capacity(); i++) {
beatsShortList.add(sb.get(i));
}
}
//add zeros to shorter audio
public void completeStreams(List<Short> l1,List<Short> l2)
{
if(l1.size() > l2.size())
{
while(l1.size() != l2.size())
{
l2.add((short)0);
}
}
if(l2.size() > l1.size())
{
while(l1.size() != l2.size())
{
l1.add((short)0);
}
}
}
//converts short list to short array
public short[] buildShortArray(List<Short> list)
{
short[] arr = new short[list.size()];
for(int i = 0; i < list.size(); i++)
{
arr[i] = list.get(i);
}
return arr;
}
//overriding back button functionality
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK)) {
Log.d(this.getClass().getName(), "back button pressed");
if(player != null)
player.stop();
play_thread_running = false;
//beat_playing_thread.stop();
//lyrics_playing_thread.stop();
return super.onKeyDown(keyCode, event);
}
return true;
}
public void showDialog()
{
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle("What's Your Song Name!");
alert.setMessage("Song Name");
// Set an EditText view to get user input
final EditText input = new EditText(this);
alert.setView(input);
alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
mixed_file_name = input.getText().toString();
new SaveFileTask(RecordRap.this).execute();
//progress = ProgressDialog.show(getApplicationContext(), "", "Mixing and Saving...");
}
});
alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// Canceled.
}
});
Here's a small re-factoring to address at least part of your NPE problem. I have no idea if this functionally correct since I'm not looking at your entire application but it should point you in the right direction. For the play logic, I'm assuming that sometimes your initializePlayer() method fails to set player to a non-null value based on your bug reports.
case R.id.play_button:
if(isPlayingInstrument == false) {
if(player == null)
initializePlayer();
if(player != null) {
isPlayingInstrument = true;
player.start();
myChronometer.setBase(SystemClock.elapsedRealtime());
}
}
break;
case R.id.pause_button:
if(player != null) {
player.pause();
isPlayingInstrument = false;
}
break;
case R.id.stop_button:
if(player != null) {
player.stop();
player = null;
isPlayingInstrument = false;
play_thread_running = false;
}
break;
I made a calendar like it is shown on the screenshot.. but I need to do that week start with monday instead of sunday... i tied to do Calendar cal = Calendar.getInstanty(); cal.setFirstDayOfWeek(Calendar.MONDAY);
but this didn't help.. any ideas?
Thanks you
import java.util.Calendar;
import java.util.Locale;
import android.content.Context;
import android.graphics.Color;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.text.format.DateFormat;
import android.text.format.DateUtils;
public class CalendarView extends LinearLayout {
public CalendarView(Context context) {
super(context);
init(context);
}
public CalendarView(Context context, AttributeSet attrs) {
super(context, attrs);
init(context);
}
public interface OnMonthChangedListener {
public void onMonthChanged(CalendarView view);
}
public void setOnMonthChangedListener(OnMonthChangedListener l) {
_onMonthChangedListener = l;
}
public interface OnSelectedDayChangedListener {
public void onSelectedDayChanged(CalendarView view);
}
public void setOnSelectedDayChangedListener(OnSelectedDayChangedListener l) {
_onSelectedDayChangedListener = l;
}
public Calendar getVisibleStartDate() {
return _calendar.getVisibleStartDate();
}
public Calendar getVisibleEndDate() {
return _calendar.getVisibleEndDate();
}
public Calendar getSelectedDay() {
return _calendar.getSelectedDay();
}
private void init(Context context) {
View v = LayoutInflater.from(context).inflate(R.layout.calendar, this, true);
_calendar = new CalendarWrapper();
_days = (TableLayout) v.findViewById(R.id.days);
_up = (TextView) v.findViewById(R.id.up);
_prev = (Button) v.findViewById(R.id.previous);
_next = (Button) v.findViewById(R.id.next);
refreshCurrentDate();
// Days Table
String[] shortWeekDayNames = _calendar.getShortDayNames();
for (int i = 0; i < 7; i++) { // Rows
TableRow tr = (TableRow) _days.getChildAt(i);
for (int j = 0; j < 7; j++) { // Columns
Boolean header = i == 0; // First row is weekday headers
TextView tv = (TextView) tr.getChildAt(j);
if (header)
tv.setText(shortWeekDayNames[j]);
else
tv.setOnClickListener(_dayClicked);
}
}
refreshDayCells();
// Listeners
_calendar.setOnDateChangedListener(_dateChanged);
_prev.setOnClickListener(_incrementClicked);
_next.setOnClickListener(_incrementClicked);
setView(MONTH_VIEW);
}
private OnClickListener _incrementClicked = new OnClickListener() {
public void onClick(View v) {
int inc = (v == _next ? 1 : -1);
if (_currentView == MONTH_VIEW)
_calendar.addMonth(inc);
else if (_currentView == DAY_VIEW) {
_calendar.addDay(inc);
invokeSelectedDayChangedListener();
}
else if (_currentView == YEAR_VIEW) {
_currentYear += inc;
refreshUpText();
}
}
};
private OnDateChangedListener _dateChanged = new OnDateChangedListener() {
public void onDateChanged(CalendarWrapper sc) {
Boolean monthChanged = _currentYear != sc.getYear() || _currentMonth != sc.getMonth();
if (monthChanged) {
refreshDayCells();
invokeMonthChangedListener();
}
refreshCurrentDate();
refreshUpText();
}
};
private OnClickListener _dayClicked = new OnClickListener() {
public void onClick(View v) {
}
};
private void refreshDayCells() {
int[] dayGrid = _calendar.get7x6DayArray();
int monthAdd = -1;
int row = 1; // Skip weekday header row
int col = 0;
for (int i = 0; i < dayGrid.length; i++) {
int day = dayGrid[i];
if (day == 1)
monthAdd++;
TableRow tr = (TableRow) _days.getChildAt(row);
TextView tv = (TextView) tr.getChildAt(col);
//Clear current markers, if any.
tv.setBackgroundDrawable(null);
tv.setWidth(0);
tv.setTextSize(12);
tv.setText(dayGrid[i] + " 100€");
tv.setBackgroundColor(Color.WHITE);
if (monthAdd == 0)
tv.setTextColor(Color.BLACK);
else
tv.setTextColor(Color.LTGRAY);
tv.setTag(new int[] { monthAdd, dayGrid[i] });
col++;
if (col == 7) {
col = 0;
row++;
}
}
}
private void setView(int view) {
if (_currentView != view) {
_currentView = view;
_days.setVisibility(_currentView == MONTH_VIEW ? View.VISIBLE : View.GONE);
refreshUpText();
}
}
private void refreshUpText() {
switch (_currentView) {
case MONTH_VIEW:
_up.setText(_calendar.toString("MMMM yyyy"));
break;
case YEAR_VIEW:
_up.setText(_currentYear + "");
break;
case CENTURY_VIEW:
_up.setText("CENTURY_VIEW");
break;
case DECADE_VIEW:
_up.setText("DECADE_VIEW");
break;
case DAY_VIEW:
_up.setText(_calendar.toString("EEEE, MMMM dd, yyyy"));
break;
case ITEM_VIEW:
_up.setText("ITEM_VIEW");
break;
default:
break;
}
}
private void refreshCurrentDate() {
_currentYear = _calendar.getYear();
_currentMonth = _calendar.getMonth();
_calendar.getDay();
int month = cal.get(Calendar.MONTH);
int year = cal.get(Calendar.YEAR);
if(month == _calendar.getMonth() && year== _calendar.getYear()){_prev.setVisibility(INVISIBLE);}
else {_prev.setVisibility(VISIBLE);}
}
private void invokeMonthChangedListener() {
if (_onMonthChangedListener != null)
_onMonthChangedListener.onMonthChanged(this);
}
private void invokeSelectedDayChangedListener() {
if (_onSelectedDayChangedListener != null)
_onSelectedDayChangedListener.onSelectedDayChanged(this);
}
private final int CENTURY_VIEW = 5;
private final int DECADE_VIEW = 4;
private final int YEAR_VIEW = 3;
private final int MONTH_VIEW = 2;
private final int DAY_VIEW = 1;
private final int ITEM_VIEW = 0;
private CalendarWrapper _calendar;
private TableLayout _days;
private TextView _up;
private Button _prev;
private Button _next;
// private Spinner sailFromSpinner;
private OnMonthChangedListener _onMonthChangedListener;
private OnSelectedDayChangedListener _onSelectedDayChangedListener;
private int _currentView;
private int _currentYear;
private int _currentMonth;
public Calendar cal = Calendar.getInstance();
}
class CalendarWrapper {
public interface OnDateChangedListener {
public void onDateChanged(CalendarWrapper sc);
}
public CalendarWrapper() {
_calendar = Calendar.getInstance();
_shortDayNames = new String[_calendar.getActualMaximum(Calendar.DAY_OF_WEEK)];
_shortMonthNames = new String[_calendar.getActualMaximum(Calendar.MONTH) + 1]; // Months are 0-based so size is Max + 1
for (int i = 0; i < _shortDayNames.length; i++) {
_shortDayNames[i] = DateUtils.getDayOfWeekString(i +1 , DateUtils.LENGTH_SHORT);
}
for (int i = 0; i < _shortMonthNames.length; i++) {
_shortMonthNames[i] = DateUtils.getMonthString(i, DateUtils.LENGTH_SHORT);
}
}
public int getYear() {
return _calendar.get(Calendar.YEAR);
}
public int getMonth() {
return _calendar.get(Calendar.MONTH);
}
public int getDayOfWeek() {
return _calendar.get(Calendar.DAY_OF_WEEK);
}
public int getDay() {
return _calendar.get(Calendar.DAY_OF_MONTH);
}
public void setYear(int value) {
_calendar.set(Calendar.YEAR, value);
invokeDateChangedListener();
}
public void setYearAndMonth(int year, int month) {
_calendar.set(Calendar.YEAR, year);
_calendar.set(Calendar.MONTH, month);
invokeDateChangedListener();
}
public void setMonth(int value) {
_calendar.set(Calendar.MONTH, value);
invokeDateChangedListener();
}
public void setDay(int value) {
_calendar.set(Calendar.DAY_OF_MONTH, value);
invokeDateChangedListener();
}
public void addYear(int value) {
if(value != 0) {
_calendar.add(Calendar.YEAR, value);
invokeDateChangedListener();
}
}
public void addMonth(int value) {
if(value != 0) {
_calendar.add(Calendar.MONTH, value);
invokeDateChangedListener();
}
}
public void addMonthSetDay(int monthAdd, int day) {
_calendar.add(Calendar.MONTH, monthAdd);
_calendar.set(Calendar.DAY_OF_MONTH, day);
invokeDateChangedListener();
}
public void addDay(int value) {
if(value != 0) {
_calendar.add(Calendar.DAY_OF_MONTH, value);
invokeDateChangedListener();
}
}
public String[] getShortDayNames() {
return _shortDayNames;
}
public String[] getShortMonthNames() {
return _shortMonthNames;
}
public int[] get7x6DayArray() {
_visibleStartDate = null;
_visibleEndDate = null;
int[] days = new int[42];
Calendar tempCal = (Calendar) _calendar.clone();
tempCal.setFirstDayOfWeek(2);
tempCal.set(Calendar.DAY_OF_MONTH, 1);
int dayOfWeekOn1st = tempCal.get(Calendar.DAY_OF_WEEK);
int maxDay = tempCal.getActualMaximum(Calendar.DAY_OF_MONTH);
int previousMonthCount = dayOfWeekOn1st - 1;
int index = 0;
if (previousMonthCount > 0) {
tempCal.set(Calendar.DAY_OF_MONTH, -1);
int previousMonthMax = tempCal.getActualMaximum(Calendar.DAY_OF_MONTH);
for (int i = previousMonthCount; i > 0; i--) {
int day = previousMonthMax - i + 1;
if(i == previousMonthCount) {
_visibleStartDate = (Calendar)tempCal.clone();
// _visibleStartDate.setFirstDayOfWeek(2);
_visibleStartDate.set(Calendar.DAY_OF_MONTH, day);
}
days[index] = day;
index++;
}
}
for (int i = 0; i < maxDay; i++) {
if(i == 0 && _visibleStartDate == null)
_visibleStartDate = (Calendar)tempCal.clone();
days[index] = (i + 1);
index++;
}
int nextMonthDay = 1;
for (int i = index; i < days.length; i++) {
if(i == index)
days[index] = nextMonthDay;
nextMonthDay++;
index++;
}
_visibleEndDate = (Calendar) _calendar.clone();
_visibleEndDate.add(Calendar.MONTH, 1);
_visibleEndDate.set(Calendar.DAY_OF_MONTH, days[41]);
return days;
}
public Calendar getSelectedDay() {
return (Calendar)_calendar.clone();
}
public Calendar getVisibleStartDate() {
return (Calendar) _visibleStartDate.clone();
}
public Calendar getVisibleEndDate() {
return (Calendar) _visibleEndDate.clone();
}
public void setOnDateChangedListener(OnDateChangedListener l) {
_onDateChangedListener = l;
}
public String toString(CharSequence format) {
return DateFormat.format(format, _calendar).toString();
}
private void invokeDateChangedListener() {
if (_onDateChangedListener != null)
_onDateChangedListener.onDateChanged(this);
}
private Calendar _calendar;
private String[] _shortDayNames;
private String[] _shortMonthNames;
private OnDateChangedListener _onDateChangedListener;
private Calendar _visibleStartDate;
private Calendar _visibleEndDate;
}
Don't know if I'm right, don't have android / java to test right now.
By seems that you do some math on _calendar, then clone it inside the get7x6DayArray, set to begin on Monday in that clone, them return the days[] to be show. But you never set the _calendar to begin on Monday, so you get the "shortWeekDayNames" begining with the Sunday (that's problably what your locale is set).
EDIT: taking a closer look to your question: in your CalendarWrapper you create an Array to hold the name of the days of the week: _shortDayNames.
Then you do a loop to fill the array with the short names: you loop from 0-6, getting the 1-7 days' names.
If you look closer at this and this, you'll see that Sunday is always the value 1: calendar.SUNDAY = 1, so _shortDayNames[0] will always get the String that corresponds to the "1" value, which is always Sunday. So your calendar will always be shown to begin with "Sunday" when you display it.
Isn't that the problem ?