|
Thank you Jochen. Sorry it took so long for me to get back to you. I have been working a lot. I did not end up using the method that was used in that post, but it did lead me to the answer, so I will mark your post as the answer.
What I did is rework my code so that instead of trying to return a value from the asynchronous method, I simply call a new method if the condition matches what I am looking for.
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
Spacecraft listItem = (Spacecraft) lv.getItemAtPosition(position);
Level = listItem.getLevel();
EverPlayedNextLevel();
}
});
Next, make sure the point value for this level is not -1. -1 means the level is locked.
private void EverPlayedNextLevel(){
String Uid = acct.getId();
DatabaseReference db = FirebaseDatabase.getInstance().getReference();
Query query = db.child("levels/uid/" + Uid + "/" + Level);
query.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
if((long)dataSnapshot.getValue() != -1)
LaunchMainActivity();
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
So if it is not -1, launch the main activity by calling another method.
Thanks for your help.
|
|
|
|
|
If it's a class level variable then you should not be using it like a local. Use a local boolean to get your true or false value which you return to the caller of this method. However, you are trying to get the changed value from an event handler, which will only run when that specific event occurs, not when this method is called from outside. So, all in all this will never work the way you expect.
|
|
|
|
|
Thanks for your reply. I got it figured out. I posted my new code in reply to Jochen.
|
|
|
|
|
Hi guys
The scenario that I find myself is this:
Development Tools: Android 2.2.3 study
Phone: Xiaomi MI4 LTE Android 6.0.1 API 23
Soap Lib: Ksoap2-android-2.5.2.jar
I want to create an app that connects to a web service in c #
The web services server is defined as follows:
webservices1.asmx
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Data.SqlClient;
using System.Configuration;
using System.Web.Services.Protocols;
namespace WebServicesGPS
{
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
public class WebService1 : System.Web.Services.WebService
{
[WebMethod]
public string GetCoordinates(string car,string lat,string lng)
{
string retcode = "OK";
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["dbconnection"].ToString());
try
{
con.Open();
string sql_select = "Insert into GPSTrackerCar " +
"(data,car,lat,lng)" +
"values (" +
"GetDate()" +
"," + car +
"," + lat.ToString().Replace(",",".") +
"," + lng.ToString().Replace(",", ".") +
")";
SqlCommand cmd = new SqlCommand(sql_select, con);
int i = cmd.ExecuteNonQuery();
if (i != 1)
throw new Exception("Nessuna riga aggiornata");
}
catch(Exception ex)
{
retcode = ex.Message;
}
return retcode;
}
}
}
The Android client is very simple and has been defined as follows:
package com.callwebservices.callwebservices;
import android.content.Context;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import org.ksoap2.serialization.PropertyInfo;
public class MainActivity extends AppCompatActivity {
private static String SOAP_ACTION = "http://tempuri.org/GetCoordinates";
private static String WSDL_TARGET_NAMESPACE = "http://tempuri.org";
private static String OPERATION_NAME = "GetCoordinates";
private static String SOAP_ADDRESS = "myWebServices_URL";
EditText tvData1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Context context = this.getApplicationContext();
tvData1 = (EditText) findViewById(R.id.tvData1);
Button BtnStart = (Button) (findViewById(R.id.BtnStart));
BtnStart.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
SoapObject request = new SoapObject(WSDL_TARGET_NAMESPACE, OPERATION_NAME);
PropertyInfo propertyInfo = new PropertyInfo();
propertyInfo.type = PropertyInfo.STRING_CLASS;
String car = "a";
request.addAttribute("car",car);
propertyInfo = new PropertyInfo();
propertyInfo.type = PropertyInfo.STRING_CLASS;
String lat = "1";
request.addAttribute("lat",lat);
propertyInfo = new PropertyInfo();
propertyInfo.type = PropertyInfo.STRING_CLASS;
String lng = "1";
request.addAttribute("lat",lng);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.setOutputSoapObject(request);
HttpTransportSE httpTransport = new HttpTransportSE(SOAP_ADDRESS,9000);
httpTransport.debug = true;
try {
httpTransport.call(SOAP_ACTION, envelope);
Object response = envelope.getResponse();
tvData1.setText(response.toString());
} catch (Exception exception) {
tvData1.setText(exception.toString()+" Or enter number is not Available!");
}
}
});
}
}
The problem is that the event on_click of the button the result is an exception:
java.net.SocketTimeoutException
02-15 10:36:48.626 2774-4338/? I/ActivityManager: START u0 {act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] flg=0x10000000 cmp=com.callwebservices.callwebservices/.MainActivity} from uid 2000 on display 0
02-15 10:36:48.684 2774-4810/? I/ActivityManager: Start proc 14510:com.callwebservices.callwebservices/u0a144 for activity com.callwebservices.callwebservices/.MainActivity
02-15 10:36:48.809 4491-4547/? D/WtProcessController: set foreground process size 1 pid:14510pacakgeName:com.callwebservices.callwebservices
02-15 10:36:48.848 14510-14510/? W/System: ClassLoader referenced unknown path: /data/app/com.callwebservices.callwebservices-1/lib/arm
02-15 10:36:48.851 14510-14510/? I/InstantRun: Instant Run Runtime started. Android package is com.callwebservices.callwebservices, real application class is null.
02-15 10:36:48.961 14510-14510/? W/System: ClassLoader referenced unknown path: /data/app/com.callwebservices.callwebservices-1/lib/arm
02-15 10:36:49.363 14510-14529/com.callwebservices.callwebservices D/OpenGLRenderer: Use EGL_SWAP_BEHAVIOR_PRESERVED: true
02-15 10:36:49.368 14510-14510/com.callwebservices.callwebservices D/ActivityThreadInjector: clearCachedDrawables.
02-15 10:36:49.407 14510-14529/com.callwebservices.callwebservices I/Adreno-EGL: <qeglDrvAPI_eglInitialize:379>: EGL 1.4 QUALCOMM build: AU_LINUX_ANDROID_LA.BF.1.1.3_RB1.06.00.01.181.013_msm8974_refs/tags/AU_LINUX_ANDROID_LA.BF.1.1.3_RB1.06.00.01.181.013__release_AU (I48a9d37399)
OpenGL ES Shader Compiler Version: E031.29.00.00
Build Date: 11/17/16 Thu
Local Branch:
Remote Branch: refs/tags/AU_LINUX_ANDROID_LA.BF.1.1.3_RB1.06.00.01.181.013
Local Patches: NONE
Reconstruct Branch: NOTHING
02-15 10:36:49.409 14510-14529/com.callwebservices.callwebservices I/OpenGLRenderer: Initialized EGL, version 1.4
02-15 10:36:49.547 2774-2810/? I/ActivityManager: Displayed com.callwebservices.callwebservices/.MainActivity: +874ms
02-15 10:36:49.548 2774-2810/? I/Timeline: Timeline: Activity_windows_visible id: ActivityRecord{79e81e u0 com.callwebservices.callwebservices/.MainActivity t6491} time:181733619
02-15 10:37:00.067 4491-4547/? W/WtProcessController: do not trim { PackageName :com.callwebservices.callwebservices Pid: 14510 Uid: 10144 Start by: activity Score:90 Old score:90 state:0 mBackgroundTimeInMillis:1487151408690 WakelockCount:0 wakelogsize:0 ActivityDestroied:false Activity size: 1 PackageInfo:{WhetstonePackageInfo#PacakgeName:com.callwebservices.callwebservices uid:10144 uiMemoryThresold:0 nonUiMemoryThresold:0 Flag:1073747136,0x400014c0 [,TRIMHEAPS,SOFT_RESET,ZRAM,FLAG_DEAL_SCHEDULE] Type:0[] } tasknum:6491}
02-15 10:37:09.393 14510-14510/com.callwebservices.callwebservices W/System: ClassLoader referenced unknown path: /system/framework/tcmclient.jar
02-15 10:37:09.403 4455-4689/? I/XiaomiFirewall: firewall pkgName:com.callwebservices.callwebservices, result:0x0
filtering for the word: Socket in logcat:
-15 09:56:50.003 3877-3877/? D/wpa_supplicant: CTRL_IFACE monitor nt successfully to /data/misc/wifi/sockets/wpa_ctrl_2774-2\x00
02-15 09:56:50.152 4362-4362/? W/Binder:2774_8: type=1400 audit(0.0:65555): avc: denied { ioctl } for path="socket:[3659894]" dev="sockfs" ino=3659894
ioctlcmd=7704 scontext=u:r:system_server:s0 tcontext=u:r:system_server:s0 tclass=unix_stream_socket permissive=0
02-15 09:56:50.152 4362-4362/? W/Binder:2774_8: type=1400 audit(0.0:65556): avc: denied { ioctl } for path="socket:[3659894]" dev="sockfs" ino=3659894
ioctlcmd=7704 scontext=u:r:system_server:s0 tcontext=u:r:system_server:s0 tclass=unix_stream_socket permissive=0
Any suggestions?
Many thanks in advance
|
|
|
|
|
Your code is vulnerable to SQL Injection[^]. NEVER use string concatenation to build a SQL query. ALWAYS use a parameterized query.
Everything you wanted to know about SQL injection (but were afraid to ask) | Troy Hunt[^]
How can I explain SQL injection without technical jargon? | Information Security Stack Exchange[^]
Query Parameterization Cheat Sheet | OWASP[^]
try
{
using (var con = new SqlConnection(ConfigurationManager.ConnectionStrings["dbconnection"].ConnectionString))
using (var cmd = new SqlCommand("INSERT INTO GPSTrackerCar (data, car, lat, lng) VALUES (GetDate(), @car, @lat, @lng)", con))
{
cmd.Parameters.AddWithValue("@car", car);
cmd.Parameters.AddWithValue("@lat", lat);
cmd.Parameters.AddWithValue("@lng", lng);
con.Open();
cmd.ExecuteNonQuery();
return "OK";
}
}
catch(SqlException ex)
{
return ex.Message;
}
Also, if your lat and lng parameters represent latitude and longitude, you should use a more specific data type - for example, double .
And a method name starting with Get suggests that it's going to retrieve data, but your method is inserting data. I'd suggest changing the name to something like StoreCoordinates .
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
So I am trying o make an application which records some audio and then filters all the high-frequency sounds from it and then in turn play only that high- frequency sounds. I am doing so using a filter class i found online.
Now the problem I'm facing is, when i press the play button, nothing is played. Now i can't tell if it is filtering out everything and hence playing nothing or that the output file never gets the filtered part.
I am posting my code and the filter class code and would really appreciate if someone could help me out with it. Thanks.
MAIN CODE
package abc.com.please;
import android.content.pm.PackageManager;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.ByteBuffer;
import java.nio.FloatBuffer;
public class MainActivity extends AppCompatActivity {
private static MediaRecorder mediaRecorder = new MediaRecorder();
private static MediaPlayer mediaPlayer;
private static String audioFilePath;
private static Button stopButton;
private static Button playButton;
private static Button recordButton;
EditText box1;
EditText box2;
private boolean isRecording = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recordButton = (Button) findViewById(R.id.recordButton);
playButton = (Button) findViewById(R.id.playButton);
stopButton = (Button) findViewById(R.id.stopButton);
box1=(EditText) findViewById(R.id.editText);
box2=(EditText) findViewById(R.id.editText2);
if (!hasMicrophone())
{
stopButton.setEnabled(false);
playButton.setEnabled(false);
recordButton.setEnabled(false);
} else {
playButton.setEnabled(false);
stopButton.setEnabled(false);
}
audioFilePath =
Environment.getExternalStorageDirectory().getAbsolutePath()
+ "/myaudio.3gp";
recordButton.setOnClickListener(new View.OnClickListener(){
public void onClick (View v)
{
isRecording = true;
stopButton.setEnabled(true);
playButton.setEnabled(false);
recordButton.setEnabled(false);
try {
mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
mediaRecorder.setOutputFile(audioFilePath);
mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
mediaRecorder.prepare();
mediaRecorder.start();
}catch (Exception e) {
e.printStackTrace();
}
}
});
stopButton.setOnClickListener(new View.OnClickListener() {
public void onClick (View view)
{
stopButton.setEnabled(false);
playButton.setEnabled(true);
if (isRecording)
{
recordButton.setEnabled(false);
isRecording = false;
mediaRecorder.stop();
mediaRecorder.release();
recordButton.setEnabled(true);
}
else
{
Toast.makeText(getApplicationContext(),"Not recording",Toast.LENGTH_SHORT).show();
recordButton.setEnabled(true);
}
}});
playButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view)
{
try{
ByteArrayOutputStream out = new ByteArrayOutputStream();
BufferedInputStream in = new BufferedInputStream(new FileInputStream(audioFilePath.toString()));
int read;
byte[] buff = new byte[1024];
while ((read = in.read(buff)) > 0)
{
out.write(buff, 0, read);
}
out.flush();
byte[] audioBytes = out.toByteArray();
final FloatBuffer fb = ByteBuffer.wrap(audioBytes).asFloatBuffer();
final float[] dst = new float[fb.capacity()];
fb.get(dst);
Filter filter = new Filter(15000,44100, Filter.PassType.Highpass,1);
for (int i = 0; i <dst.length; i++)
{
filter.Update(dst[i]);
dst[i] = filter.getValue();
}
byte byteArray[] = new byte[dst.length*4];
ByteBuffer byteBuf = ByteBuffer.wrap(byteArray);
FloatBuffer floatBuf = byteBuf.asFloatBuffer();
floatBuf.put (dst);
File someFile = new File(audioFilePath);
String filepath= someFile.toString();
FileOutputStream fos = new FileOutputStream(someFile);
fos.write(byteArray);
fos.flush();
fos.close();
playButton.setEnabled(false);
recordButton.setEnabled(false);
stopButton.setEnabled(true);
try {
mediaPlayer = new MediaPlayer();
mediaPlayer.setDataSource(filepath);
mediaPlayer.prepare();
mediaPlayer.start();
} catch (Exception e) {
e.printStackTrace();
}
}catch(java.io.IOException e){
e.printStackTrace();
}
}
});
}
protected boolean hasMicrophone() {
PackageManager pmanager = this.getPackageManager();
return pmanager.hasSystemFeature(
PackageManager.FEATURE_MICROPHONE);
}
}
FILTER CLASS
package abc.com.please;
public class Filter {
private float resonance;
private float frequency;
private int sampleRate;
private PassType passType;
public float value;
private float c, a1, a2, a3, b1, b2;
private float[] inputHistory = new float[2];
private float[] outputHistory = new float[3];
public Filter(float frequency, int sampleRate, PassType passType, float resonance)
{
this.resonance = resonance;
this.frequency = frequency;
this.sampleRate = sampleRate;
this.passType = passType;
switch (passType)
{
case Lowpass:
c = 1.0f / (float)Math.tan(Math.PI * frequency / sampleRate);
a1 = 1.0f / (1.0f + resonance * c + c * c);
a2 = 2f * a1;
a3 = a1;
b1 = 2.0f * (1.0f - c * c) * a1;
b2 = (1.0f - resonance * c + c * c) * a1;
break;
case Highpass:
c = (float)Math.tan(Math.PI * frequency / sampleRate);
a1 = 1.0f / (1.0f + resonance * c + c * c);
a2 = -2f * a1;
a3 = a1;
b1 = 2.0f * (c * c - 1.0f) * a1;
b2 = (1.0f - resonance * c + c * c) * a1;
break;
}
}
public enum PassType
{
Highpass,
Lowpass,
}
public void Update(float newInput)
{
float newOutput = a1 * newInput + a2 * this.inputHistory[0] + a3 * this.inputHistory[1] - b1 * this.outputHistory[0] - b2 * this.outputHistory[1];
this.inputHistory[1] = this.inputHistory[0];
this.inputHistory[0] = newInput;
this.outputHistory[2] = this.outputHistory[1];
this.outputHistory[1] = this.outputHistory[0];
this.outputHistory[0] = newOutput;
}
public float getValue()
{
return this.outputHistory[0];
}
}
|
|
|
|
|
Himanshu Bhutani wrote: Now i can't tell if it is filtering out everything and hence playing nothing or that the output file never gets the filtered part. Have you stepped through the code using your debugger?
"One man's wage rise is another man's price increase." - Harold Wilson
"Fireproof doesn't mean the fire will never come. It means when the fire comes that you will be able to withstand it." - Michael Simmons
"You can easily judge the character of a man by how he treats those who can do nothing for him." - James D. Miles
|
|
|
|
|
I suggest that you add logging to your application using the default android log utility. This will make your investigation much easier. Using a debugger - as somebody else suggested - is a very valid approach, but where you are looking at real-time effects (which may or may not be relevant) there's no substitute for logging. You can do this as follows:
Add this import to your MainActivity and Filter classes:
import android.util.Log;
Then add this static variable as a class variable to each:
private static final String TAG = "Himanshu";
Now add some logging like this:
while ((read = in.read(buff)) > 0) {
Log.i(TAG, "Raw audio: " + read);
out.write(buff, 0, read);
}
out.flush();
byte[] audioBytes = out.toByteArray();
final FloatBuffer fb = ByteBuffer.wrap(audioBytes).asFloatBuffer();
final float[] dst = new float[fb.capacity()];
fb.get(dst);
Filter filter = new Filter(15000,44100, Filter.PassType.Highpass,1);
for (int i = 0; i <dst.length; i++) {
filter.Update(dst[i]);
dst[i] = filter.getValue();
Log.i(TAG, "Filtered audio: " + dst[i]);
}
etc etc..
In order to view your log you need to use adb. If you work in a windows environment you'd do this in a DOS command shell:
adb logcat Himanshu:* *:s -v time
Issue the above logcat command BEFORE starting your app and triggering the audio record & playback. This command is saying: Capture all log messages (.i, .d, .v, .w, .e etc.. i.e. of category: Information, Debug, Verbose, Warning and Error) and do NOT capture any other log messages, show log timestamps.
I didn't check all of the places in your code where that would also shed light on the problem. It's your code and I'm sure that you can quickly identify these places.
Actually I would have done a couple of other things also before going quite so far as you have:
1. Confirm that you can play audio samples, do this by creating a simple square wave, storing it in memory and squirting it out. You can use PCM at 16 kSamples/sec and a ~200 Hz waveform.
2. Capture recorded audio to a file and check that this is valid audio.
One other thing to mention is that you are using the AMR Narrow Band voice codec. This is not a generic audio encoding algorithm. AMR (NB) has been highly optimised for voice telephony, and as is the case for such codecs. This may be important because these codecs do not handle tones at all well and music isn't very well supported. I'm not sure what kind of audio you are dealing with. You may want to consider an alternative audio encoding format such as MP3 or plain/differential PCM.
|
|
|
|
|
I have created program that calculates day of week when entered date in format "January 7 2000" .Why do I get NullPointerException exception when I click button to calculate day of week?
Here is source code of app:
public class MainActivity extends AppCompatActivity
{
private int position;
private int value;
private Button button;
private EditText editText;
private TextView textView1,textView2;
private Spinner spinner,spinner2;
private ArrayAdapter<CharSequence> adapter;
private boolean isValid;
private Date date;
private int inMonth, inDay, inYear;
static boolean isDateValid(int month, int day, int year)
{
boolean validation = true;
int[] daysInMonth = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
if (month < 1 || month > 12)
{
validation = false;
}
if (day < 1 || day > daysInMonth[month - 1])
{
validation = false;
}
if (year < 1700 || year > 3000)
{
validation = false;
}
return validation;
}
static String zellerCalc(int month, int day, int year)
{
String dayOfWeek;
int m = -1;
int h = -1;
int q = day;
int k;
int j;
if (month == 1)
{
m = 13;
}
else if (month == 2)
{
m = 14;
}
else
{
m = month;
}
if (m == 13 || m == 14)
{
year--;
}
k = year % 100;
j = year / 100;
h = (q + (int)((13 * (m + 1)) / 5.0) + k + (int)(k / 4.0) + (int)(j / 4.0) + (5 * j)) % 7;
if (h == 0)
{
dayOfWeek = "Subota";
}
else if (h == 1)
{
dayOfWeek = "Nedelja";
}
else if (h == 2)
{
dayOfWeek = "Ponedeljak";
}
else if (h == 3)
{
dayOfWeek = "Utorak";
}
else if (h == 4)
{
dayOfWeek = "Sreda";
}
else if (h == 5)
{
dayOfWeek = "Četvrtak";
}
else
dayOfWeek = "Petak";
return dayOfWeek;
}
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
button = (Button) findViewById(R.id.button_calculate);
textView1 = (TextView) findViewById(R.id.textView_day);
textView2 = (TextView) findViewById(R.id.textView_year);
spinner = (Spinner) findViewById(R.id.spinner_month);
spinner2 = (Spinner) findViewById(R.id.spinner_day);
editText = (EditText) findViewById(R.id.editText_year);
adapter = ArrayAdapter.createFromResource(this,R.array.months,android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
adapter = ArrayAdapter.createFromResource(this,R.array.day,android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner2.setAdapter(adapter);
if (spinner2.getSelectedItemPosition() == 0)
value = 1;
if (spinner2.getSelectedItemPosition() == 1)
value = 2;
if (spinner2.getSelectedItemPosition() == 2)
value = 3;
if (spinner2.getSelectedItemPosition() == 3)
value = 4;
if (spinner2.getSelectedItemPosition() == 4)
value = 5;
if (spinner2.getSelectedItemPosition() == 5)
value = 6;
if (spinner2.getSelectedItemPosition() == 6)
value = 7;
if (spinner2.getSelectedItemPosition() == 7)
value = 8;
if (spinner2.getSelectedItemPosition() == 8)
value = 9;
if (spinner2.getSelectedItemPosition() == 9)
value = 10;
if (spinner2.getSelectedItemPosition() == 10)
value = 11;
if (spinner2.getSelectedItemPosition() == 11)
value = 12;
button.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View view)
{
String dayOfWeek;
boolean isValid;
Calendar c = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss");
String strDate = sdf.format(c.getTime());
do
{
try
{
String getdate = spinner.getItemAtPosition(position).toString() + value
+ textView2.getText().toString();
Date date = sdf.parse(getdate);
}
catch (ParseException ex)
{
}
isValid = isDateValid(date.getMonth(), date.getDay(), date.getYear());
if (isValid == false)
{
Toast.makeText(MainActivity.this,"You entered wrong date",Toast.LENGTH_SHORT).show();
}
}
while (isValid == false);
dayOfWeek = zellerCalc(date.getMonth(), date.getDay(), date.getYear());
textView1.setText(dayOfWeek);
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu)
{
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item)
{
int id = item.getItemId();
if (id == R.id.action_settings)
{
return true;
}
return super.onOptionsItemSelected(item);
}
}
Logcat:
02-07 12:32:16.349 3049-3049/com.example.pavle.dayofborn E/AndroidRuntime: FATAL EXCEPTION: main Process: com.example.pavle.dayofborn, PID: 3049 java.lang.NullPointerException at com.example.pavle.dayofborn.MainActivity$2.onClick(MainActivity.java:230) at android.view.View.performClick(View.java:4633) at android.view.View$PerformClick.run(View.java:19270) 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:5476) 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:1283) at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1099) at dalvik.system.NativeStart.main(Native Method)
//Line 230: isValid = isDateValid(date.getMonth(), date.getDay(), date.getYear());
|
|
|
|
|
Seriously? A NullPointerException is being thrown on line 230 because date is null . A simple walkthrough with the debugger would have revealed this.
"One man's wage rise is another man's price increase." - Harold Wilson
"Fireproof doesn't mean the fire will never come. It means when the fire comes that you will be able to withstand it." - Michael Simmons
"You can easily judge the character of a man by how he treats those who can do nothing for him." - James D. Miles
|
|
|
|
|
I have initialized Date date = new Date(); but now I get application has stopped working and error is still in the same line!!!
try
{
Date date = new Date();
String getdate = spinner.getItemAtPosition(position).toString() + value
+ textView2.getText().toString();
date = sdf.parse(getdate);
} catch (ParseException ex)
{
}
isValid = isDateValid(date.getMonth(), date.getDay(), date.getYear());
|
|
|
|
|
Pavlex4 wrote: I have initialized Date date = new Date(); Which is not the one being passed to isDateValid() .
"One man's wage rise is another man's price increase." - Harold Wilson
"Fireproof doesn't mean the fire will never come. It means when the fire comes that you will be able to withstand it." - Michael Simmons
"You can easily judge the character of a man by how he treats those who can do nothing for him." - James D. Miles
|
|
|
|
|
|
Maybe look at (or around) line 12.
"One man's wage rise is another man's price increase." - Harold Wilson
"Fireproof doesn't mean the fire will never come. It means when the fire comes that you will be able to withstand it." - Michael Simmons
"You can easily judge the character of a man by how he treats those who can do nothing for him." - James D. Miles
|
|
|
|
|
You mean this "private Date date;" ?
|
|
|
|
|
Correct.
"One man's wage rise is another man's price increase." - Harold Wilson
"Fireproof doesn't mean the fire will never come. It means when the fire comes that you will be able to withstand it." - Michael Simmons
"You can easily judge the character of a man by how he treats those who can do nothing for him." - James D. Miles
|
|
|
|
|
What is problem with that line?
|
|
|
|
|
|
I added date = new Date(); to button onclicklistener but when I click button inside app it gets pressed and stays like that and nothing happens!!!
button.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View view)
{
String dayOfWeek;
boolean isValid;
date = new Date();
Calendar c = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss");
String strDate = sdf.format(c.getTime());
|
|
|
|
|
You really need to make more effort to do some debugging of your code first. You have a problem which could be caused by any part of your code, so you need to do the troubleshooting to collect more information. Also you have a try/catch block in your code that reads:
try
{
String getdate = spinner.getItemAtPosition(position).toString() + value
+ textView2.getText().toString();
Date date = sdf.parse(getdate);
}
catch (ParseException ex)
{
}
Do not do this, you are just hiding any problems that may occur. Put some proper code in the catch block to help you find errors.
|
|
|
|
|
Can you not see that you have two Date objects (in separate scopes)?
"One man's wage rise is another man's price increase." - Harold Wilson
"Fireproof doesn't mean the fire will never come. It means when the fire comes that you will be able to withstand it." - Michael Simmons
"You can easily judge the character of a man by how he treats those who can do nothing for him." - James D. Miles
|
|
|
|
|
Why check your own code when you can get it done for free at CodeProject?
|
|
|
|
|
Where can I take my application and O/S program ideas too?
|
|
|
|
|
For the purpose of what?
"One man's wage rise is another man's price increase." - Harold Wilson
"Fireproof doesn't mean the fire will never come. It means when the fire comes that you will be able to withstand it." - Michael Simmons
"You can easily judge the character of a man by how he treats those who can do nothing for him." - James D. Miles
|
|
|
|
|
I have created app that detects otg cable using service. I have created button in action bar with icon,how to make if otg cable is connected hide that button if not connected it should show text and when clicked on it to get popup window with text and animation?
MainActivity.class
public class MainActivity extends AppCompatActivity
{
public void startOtgService()
{
startService(new Intent(MainActivity.this, OtgService.class));
}
public void stopOtgService()
{
stopService(new Intent(MainActivity.this, OtgService.class));
}
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View view)
{
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
Button startButton = (Button)this.findViewById(R.id.startButton);
Button stopButton = (Button)this.findViewById(R.id.stopButton);
startButton.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
startOtgService();
}
});
stopButton.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
stopOtgService();
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu)
{
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item)
{
int id = item.getItemId();
if (id == R.id.action_settings)
{
return true;
}
if(id == R.id.action_cable)
{
}
return super.onOptionsItemSelected(item);
}
}
OtgService.class
public class OtgService extends Service
{
private boolean mOtgConnected = false;
private Handler mHandler;
Timer taskTimer = new Timer();
TimerTask task = new TimerTask()
{
private int last_Length = -1;
@Override
public void run()
{
Context context = OtgService.this.getBaseContext();
File directory = new File("/sys/bus/usb/devices");
File[] contents = directory.listFiles();
int conn_length = contents.length;
if(conn_length ==last_Length)
{
return;
}
else
{
last_Length = conn_length;
}
if(conn_length == 0)
{
mOtgConnected = false;
mHandler.post(flagChangedTask);
}
else if (conn_length > 0)
{
mOtgConnected = true;
mHandler.post(flagChangedTask);
}
}
};
Runnable flagChangedTask = new Runnable()
{
@Override
public void run()
{
if (mOtgConnected)
Toast.makeText(OtgService.this,"otg connected",Toast.LENGTH_SHORT).show();
else
Toast.makeText(OtgService.this,"otg not connected",Toast.LENGTH_SHORT).show();
}
};
public OtgService()
{
}
private void onStartCompat(Intent intent)
{
Log.e("###", "Starting service!");
if (mHandler == null)
mHandler = new Handler(getMainLooper());
taskTimer.scheduleAtFixedRate(task, 0, 1000);
}
@Override
public void onStart(Intent intent, int startId)
{
onStartCompat(intent);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId)
{
onStartCompat(intent);
return START_STICKY;
}
@Override
public void onDestroy()
{
}
@Override
public IBinder onBind(Intent intent)
{
return null;
}
}
|
|
|
|
|