No errors occur within when emulator is run on my android phone. Not sure if that the correct http:192.168....... When I run the app i enter the data and it says connecting to server but then says unfortunately the app crashed. Any Ideas.
BackgroundTask
package com.example.om.fitnessproject;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.AsyncTask;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
public class BackgroundTask extends AsyncTask<String, Void, String > {
String register_url = "https://192.168.0.4/Fitnessplus/register.php";
Context ctx;
ProgressDialog progressDialog;
Activity activity;
AlertDialog.Builder builder;
public BackgroundTask(Context ctx){
this.ctx = ctx;
activity = (Activity)ctx;
}
#Override
protected void onPreExecute() {
builder = new AlertDialog.Builder(activity);
progressDialog = new ProgressDialog(ctx);
progressDialog.setTitle("Please wait");
progressDialog.setMessage("Connecting to server");
progressDialog.setIndeterminate(true);
progressDialog.setCancelable(false);
progressDialog.show();
}
#Override
protected String doInBackground(String... params) {
String method = params [0];
if(method.equals("register"))
{
try {
URL url = new URL(register_url);
HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
OutputStream outputStream = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream,"UTF-8"));
String name = params[1];
String email = params[2];
String password = params[3];
String data = URLEncoder.encode("name","UTF- 8")+"="+URLEncoder.encode(name,"UTF-8")+"&"+
URLEncoder.encode("email","UTF-8")+"="+URLEncoder.encode(email, "UTF-8")+"&"+
URLEncoder.encode("password","UTF-8")+"="+URLEncoder.encode(password,"UTF-8");
bufferedWriter.write(data);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
StringBuilder stringBuilder = new StringBuilder();
String line = "";
while ((line=bufferedReader.readLine())!=null)
{
stringBuilder.append(line+"\n");
}
httpURLConnection.disconnect();
Thread.sleep(5000);
return stringBuilder.toString().trim();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
#Override
protected void onPostExecute(String json) {
try {
progressDialog.dismiss();
JSONObject jsonObject = new JSONObject(json);
JSONArray jsonArray = jsonObject.getJSONArray("server_response");
JSONObject JO = jsonArray.getJSONObject(0);
String code = JO.getString("code");
String message = JO.getString("message");
if (code.equals("reg_true"))
{
showDialog("Registration Success", message,code);
}
else if(code.equals("reg_false"))
{
showDialog("Registration failed", message, code);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
public void showDialog(String title,String message,String code)
{
builder.setTitle(title);
if(code.equals("reg_true")||code.equals("reg_false"))
{
builder.setMessage(message);
builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
activity.finish();
}
});
AlertDialog alertDialog = builder.create();
alertDialog.show();
}
}
}
register
package com.example.om.fitnessproject;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class register extends AppCompatActivity {
EditText Name, Email, Pass, ConPass;
Button reg_button;
AlertDialog.Builder builder;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_register);
Name = (EditText)findViewById(R.id.reg_name);
Email = (EditText)findViewById(R.id.reg_email);
Pass = (EditText)findViewById(R.id.reg_password);
ConPass = (EditText)findViewById(R.id.reg_con_password);
reg_button = (Button)findViewById(R.id.reg_button);
reg_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (Name.getText().toString().equals("") || Email.getText().toString().equals("") || Pass.getText().toString().equals("")) {
builder = new AlertDialog.Builder(register.this);
builder.setTitle("Something went wrong");
builder.setMessage("Please fill in all the field");
builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
AlertDialog alertDialog = builder.create();
alertDialog.show();
} else if (!(Pass.getText().toString().equals(ConPass.getText().toString()))) {
builder = new AlertDialog.Builder(register.this);
builder.setTitle("Something went wrong");
builder.setMessage("Your passwords are not matching");
builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
Pass.setText("");
ConPass.setText("");
}
});
AlertDialog alertDialog = builder.create();
alertDialog.show();
}
else {
BackgroundTask backgroundTask = new BackgroundTask(register.this);
backgroundTask.execute("register",Name.getText().toString(),Email.getText().toString(),Pass.getText().toString());
}
}
});
}
}
Trace
04-18 20:42:35.360 26137-26137/? I/art: Late-enabling -Xcheck:jni
04-18 20:42:35.532 26137-26137/com.example.kieranbroom.fitnessproject W/System: ClassLoader referenced unknown path: /data/app/com.example.kieranbroom.fitnessproject-1/lib/arm64
04-18 20:42:36.458 26137-26209/com.example.kieranbroom.fitnessproject D/OpenGLRenderer: Use EGL_SWAP_BEHAVIOR_PRESERVED: true
04-18 20:42:36.520 26137-26209/com.example.kieranbroom.fitnessproject I/Adreno: QUALCOMM build : 63c06b2, I8366cd0437
Build Date : 10/21/15
OpenGL ES Shader Compiler Version: XE031.05.13.02
Local Branch :
Remote Branch : quic/LA.BF64.1.2.9_v2
Remote Branch : NONE
Reconstruct Branch : NOTHING
04-18 20:42:36.526 26137-26209/com.example.kieranbroom.fitnessproject I/OpenGLRenderer: Initialized EGL, version 1.4
04-18 20:42:59.950 26137-26209/com.example.kieranbroom.fitnessproject D/OpenGLRenderer: endAllStagingAnimators on 0x7f9623f800 (RippleDrawable) with handle 0x7f96234220
04-18 20:43:05.999 26137-26700/com.example.kieranbroom.fitnessproject W/System.err: javax.net.ssl.SSLHandshakeException: java.security.cert.CertPathValidatorException: Trust anchor for certification path not found.
04-18 20:43:05.999 26137-26700/com.example.kieranbroom.fitnessproject W/System.err: at com.android.org.conscrypt.OpenSSLSocketImpl.startHandshake(OpenSSLSocketImp l.java:328)
04-18 20:43:05.999 26137-26700/com.example.kieranbroom.fitnessproject W/System.err: at com.android.okhttp.internal.http.SocketConnector.connectTls(SocketConnector.java:103)
04-18 20:43:05.999 26137-26700/com.example.kieranbroom.fitnessproject W/System.err: at com.android.okhttp.Connection.connect(Connection.java:143)
04-18 20:43:05.999 26137-26700/com.example.kieranbroom.fitnessproject W/System.err: at com.android.okhttp.Connection.connectAndSetOwner(Connection.java:185)
04-18 20:43:05.999 26137-26700/com.example.kieranbroom.fitnessproject W/System.err: at com.android.okhttp.OkHttpClient$1.connectAndSetOwner(OkHttpClient.java:128)
04-18 20:43:06.000 26137-26700/com.example.kieranbroom.fitnessproject W/System.err: at com.android.okhttp.internal.http.HttpEngine.nextConnection(HttpEngine.java: 341)
04-18 20:43:06.000 26137-26700/com.example.kieranbroom.fitnessproject W/System.err: at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:330)
04-18 20:43:06.000 26137-26700/com.example.kieranbroom.fitnessproject W/System.err: at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:248)
04-18 20:43:06.000 26137-26700/com.example.kieranbroom.fitnessproject W/System.err: at com.android.okhttp.internal.huc.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:437)
04-18 20:43:06.000 26137-26700/com.example.kieranbroom.fitnessproject W/System.err: at com.android.okhttp.internal.huc.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:114)
04-18 20:43:06.000 26137-26700/com.example.kieranbroom.fitnessproject W/System.err: at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getOutputStream(HttpURLConnectionImpl.java:245)
04-18 20:43:06.000 26137-26700/com.example.kieranbroom.fitnessproject W/System.err: at com.android.okhttp.internal.huc.DelegatingHttpsURLConnection.getOutputStream(DelegatingHttpsURLConnection.java:218)
04-18 20:43:06.000 26137-26700/com.example.kieranbroom.fitnessproject W/System.err: at com.android.okhttp.internal.huc.HttpsURLConnectionImpl.getOutputStream(HttpsURLConnectionImpl.java)
04-18 20:43:06.000 26137-26700/com.example.kieranbroom.fitnessproject W/System.err: at com.example.kieranbroom.fitnessproject.BackgroundTask.doInBackground(BackgroundTask.java:64)
04-18 20:43:06.000 26137-26700/com.example.kieranbroom.fitnessproject W/System.err: at com.example.kieranbroom.fitnessproject.BackgroundTask.doInBackground(BackgroundTask.java:26)
04-18 20:43:06.000 26137-26700/com.example.kieranbroom.fitnessproject W/System.err: at android.os.AsyncTask$2.call(AsyncTask.java:295)
04-18 20:43:06.001 26137-26700/com.example.kieranbroom.fitnessproject W/System.err: at java.util.concurrent.FutureTask.run(FutureTask.java:237)
04-18 20:43:06.001 26137-26700/com.example.kieranbroom.fitnessproject W/System.err: at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:234)
04-18 20:43:06.001 26137-26700/com.example.kieranbroom.fitnessproject W/System.err: at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1113)
04-18 20:43:06.001 26137-26700/com.example.kieranbroom.fitnessproject W/System.err: at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:588)
04-18 20:43:06.001 26137-26700/com.example.kieranbroom.fitnessproject W/System.err: at java.lang.Thread.run(Thread.java:818)
04-18 20:43:06.001 26137-26700/com.example.kieranbroom.fitnessproject W/System.err: Caused by: java.security.cert.CertificateException: java.security.cert.CertPathValidatorException: Trust anchor for certification path not found.
04-18 20:43:06.001 26137-26700/com.example.kieranbroom.fitnessproject W/System.err: at com.android.org.conscrypt.TrustManagerImpl.checkTrusted(TrustManagerImpl.java:318)
04-18 20:43:06.001 26137-26700/com.example.kieranbroom.fitnessproject W/System.err: at com.android.org.conscrypt.TrustManagerImpl.checkServerTrusted(TrustManagerImpl.java:219)
04-18 20:43:06.001 26137-26700/com.example.kieranbroom.fitnessproject W/System.err: at com.android.org.conscrypt.Platform.checkServerTrusted(Platform.java:115)
04-18 20:43:06.001 26137-26700/com.example.kieranbroom.fitnessproject W/System.err: at com.android.org.conscrypt.OpenSSLSocketImpl.verifyCertificateChain(OpenSSLSocketImpl.java:556)
04-18 20:43:06.001 26137-26700/com.example.kieranbroom.fitnessproject W/System.err: at com.android.org.conscrypt.NativeCrypto.SSL_do_handshake(Native Method)
04-18 20:43:06.001 26137-26700/com.example.kieranbroom.fitnessproject W/System.err: at com.android.org.conscrypt.OpenSSLSocketImpl.startHandshake(OpenSSLSocketImpl.java:324)
04-18 20:43:06.001 26137-26700/com.example.kieranbroom.fitnessproject W/System.err: ... 20 more
04-18 20:43:06.001 26137-26700/com.example.kieranbroom.fitnessproject W/System.err: Caused by: java.security.cert.CertPathValidatorException: Trust anchor for certification path not found.
04-18 20:43:06.002 26137-26700/com.example.kieranbroom.fitnessproject W/System.err: ... 26 more
04-18 20:43:06.010 26137-26137/com.example.kieranbroom.fitnessproject D/AndroidRuntime: Shutting down VM
04-18 20:43:06.010 26137-26137/com.example.kieranbroom.fitnessproject E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.kieranbroom.fitnessproject, PID: 26137
java.lang.NullPointerException: Attempt to invoke virtual method 'int java.lang.String.length()' on a null object reference
at org.json.JSONTokener.nextCleanInternal(JSONTokener.java:116)
at org.json.JSONTokener.nextValue(JSONTokener.java:94)
at org.json.JSONObject.<init>(JSONObject.java:156)
at org.json.JSONObject.<init>(JSONObject.java:173)
at com.example.kieranbroom.fitnessproject.BackgroundTask.onPostExecute(BackgroundTask.java:115)
at com.example.kieranbroom.fitnessproject.BackgroundTask.onPostExecute(BackgroundTask.java:26)
at android.os.AsyncTask.finish(AsyncTask.java:651)
at android.os.AsyncTask.-wrap1(AsyncTask.java)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:668)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Related
I know there are a few of these on SO already but none of them really were able to help my issue, but when I am running the code and start recording audio and then press my stop button it always fails because it is in the wrong state. I am not sure how I would go about fixing my states for this.
Here is my MainActivity.java code:
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.widget.Button;
import android.widget.RadioGroup;
import android.widget.Toast;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import java.io.IOException;
import static android.Manifest.permission.RECORD_AUDIO;
import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;
public class MainActivity extends AppCompatActivity {
Button buttonStartRecording, buttonStopRecording, buttonPlayLastRecordAudio,
buttonStopPlayingRecording;
String AudioSavePathInDevice = null;
MediaRecorder mediaRecorder;
public static final int RequestPermissionCode = 1;
MediaPlayer mediaPlayer;
AudioManager audioManager;
boolean isAudioPlayInSameDevice = true;
// AudioRouter audioRouter;
RadioGroup mRadioGroup;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buttonStartRecording = (Button) findViewById(R.id.start_recording);
buttonStopRecording = (Button) findViewById(R.id.stop_rec);
buttonPlayLastRecordAudio = (Button) findViewById(R.id.play_last_rec);
buttonStopPlayingRecording = (Button) findViewById(R.id.stop_playing_btn);
// mRadioGroup = (RadioGroup) findViewById(R.id.radioGroup);
buttonStopRecording.setEnabled(false);
buttonPlayLastRecordAudio.setEnabled(false);
buttonStopPlayingRecording.setEnabled(false);
buttonStartRecording.setOnClickListener(new View.OnClickListener() {
#RequiresApi(api = Build.VERSION_CODES.O)
#Override
public void onClick(View view) {
// Check audio permission
if (checkPermission()) {
AudioSavePathInDevice =
Environment.getExternalStorageDirectory().getAbsolutePath() + "/" + "AudioRecording.3gp";
// Start Media recorder
MediaRecorderReady();
try {
mediaRecorder.prepare();
mediaRecorder.start();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
buttonStartRecording.setEnabled(false);
buttonStopRecording.setEnabled(true);
Toast.makeText(MainActivity.this, "Recording started",
Toast.LENGTH_LONG).show();
} else {
requestPermission();
}
}
});
buttonStopRecording.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
buttonStopRecording.setEnabled(false);
buttonPlayLastRecordAudio.setEnabled(true);
buttonStartRecording.setEnabled(true);
buttonStopPlayingRecording.setEnabled(false);
// Stop Media recorder
mediaRecorder.stop();
Toast.makeText(MainActivity.this, "Recording Completed",
Toast.LENGTH_LONG).show();
}
});
buttonPlayLastRecordAudio.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) throws IllegalArgumentException,
SecurityException, IllegalStateException {
int selectedId = 1;
if (selectedId == 1) {
isAudioPlayInSameDevice = true;
} else {
isAudioPlayInSameDevice = false;
}
// if you want to play audio on your Mobile speaker then set isAudioPlayInSameDevice true
// and if you want to play audio to connected device then set isAudioPlayInSameDevice false.
if (isAudioPlayInSameDevice) {
audioManager.setMode(audioManager.STREAM_MUSIC);
audioManager.setSpeakerphoneOn(true);
} else {
audioManager.setSpeakerphoneOn(false);
audioManager.setMode(audioManager.MODE_NORMAL);
}
audioManager.setBluetoothScoOn(false);
audioManager.stopBluetoothSco();
buttonStopRecording.setEnabled(false);
buttonStartRecording.setEnabled(false);
buttonStopPlayingRecording.setEnabled(true);
mediaPlayer = new MediaPlayer();
try {
// Start media player
System.out.println("Recorded Audio Path-" + AudioSavePathInDevice);
mediaPlayer.setDataSource(AudioSavePathInDevice);
if (isAudioPlayInSameDevice) {
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
}
mediaPlayer.prepare();
mediaPlayer.start();
} catch (IOException e) {
e.printStackTrace();
}
Toast.makeText(MainActivity.this, "Recording Playing",
Toast.LENGTH_LONG).show();
}
});
buttonStopPlayingRecording.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
buttonStopRecording.setEnabled(false);
buttonStartRecording.setEnabled(true);
buttonStopPlayingRecording.setEnabled(false);
buttonPlayLastRecordAudio.setEnabled(true);
if (mediaPlayer != null) {
// Stop Media Player
mediaPlayer.stop();
mediaPlayer.release();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
MediaRecorderReady();
}
}
}
});
}
private BroadcastReceiver mBluetoothScoReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
int state = intent.getIntExtra(AudioManager.EXTRA_SCO_AUDIO_STATE, -1);
System.out.println("ANDROID Audio SCO state: " + state);
if (AudioManager.SCO_AUDIO_STATE_CONNECTED == state) {
/*
* Now the connection has been established to the bluetooth device.
* Record audio or whatever (on another thread).With AudioRecord you can record with an object created like this:
* new AudioRecord(MediaRecorder.AudioSource.MIC, 8000, AudioFormat.CHANNEL_CONFIGURATION_MONO,
* AudioFormat.ENCODING_PCM_16BIT, audioBufferSize);
*
* After finishing, don't forget to unregister this receiver and
* to stop the bluetooth connection with am.stopBluetoothSco();
*/
}
}
};
#RequiresApi(api = Build.VERSION_CODES.O)
public void MediaRecorderReady() {
mediaRecorder = new MediaRecorder();
mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_2_TS);
mediaRecorder.setAudioEncoder(MediaRecorder.OutputFormat.AMR_NB);
mediaRecorder.setOutputFile(AudioSavePathInDevice);
}
#Override
protected void onResume() {
super.onResume();
IntentFilter intentFilter = new IntentFilter(AudioManager.ACTION_SCO_AUDIO_STATE_UPDATED);
registerReceiver(mBluetoothScoReceiver, intentFilter);
audioManager = (AudioManager) getApplicationContext().getSystemService(getApplicationContext().AUDIO_SERVICE);
// Start Bluetooth SCO.
audioManager.setMode(audioManager.MODE_NORMAL);
audioManager.setBluetoothScoOn(true);
audioManager.startBluetoothSco();
// Stop Speaker.
audioManager.setSpeakerphoneOn(false);
}
#Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(mBluetoothScoReceiver);
// Stop Bluetooth SCO.
audioManager.stopBluetoothSco();
audioManager.setMode(audioManager.MODE_NORMAL);
audioManager.setBluetoothScoOn(false);
// Start Speaker.
audioManager.setSpeakerphoneOn(true);
}
private void requestPermission() {
ActivityCompat.requestPermissions(MainActivity.this, new
String[]{WRITE_EXTERNAL_STORAGE, RECORD_AUDIO}, RequestPermissionCode);
}
#Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
switch (requestCode) {
case RequestPermissionCode:
if (grantResults.length > 0) {
boolean StoragePermission = grantResults[0] ==
PackageManager.PERMISSION_GRANTED;
boolean RecordPermission = grantResults[1] ==
PackageManager.PERMISSION_GRANTED;
// if (StoragePermission && RecordPermission) {
// Toast.makeText(BluetoothAudioRecorder.this, "Permission Granted",
// Toast.LENGTH_LONG).show();
// } else {
// Toast.makeText(BluetoothAudioRecorder.this,"Permission Denied",Toast.LENGTH_LONG).show();
// }
}
break;
}
}
public boolean checkPermission() {
int result = ContextCompat.checkSelfPermission(getApplicationContext(),
WRITE_EXTERNAL_STORAGE);
int result1 = ContextCompat.checkSelfPermission(getApplicationContext(),
RECORD_AUDIO);
return result == PackageManager.PERMISSION_GRANTED &&
result1 == PackageManager.PERMISSION_GRANTED;
}
}
And then my logcat of when the error occurs:
2019-11-24 11:26:54.440 29627-29683/com.example.esense_application E/libc: Access denied finding property "vendor.gralloc.disable_ahardware_buffer"
2019-11-24 11:26:54.435 29627-29627/com.example.esense_application W/RenderThread: type=1400 audit(0.0:17779): avc: denied { read } for name="u:object_r:vendor_default_prop:s0" dev="tmpfs" ino=24699 scontext=u:r:untrusted_app:s0:c7,c257,c512,c768 tcontext=u:object_r:vendor_default_prop:s0 tclass=file permissive=0
2019-11-24 11:26:54.487 29627-29627/com.example.esense_application I/System.out: ANDROID Audio SCO state: 1
2019-11-24 11:26:54.487 29627-29627/com.example.esense_application I/System.out: ANDROID Audio SCO state: 2
2019-11-24 11:26:54.868 29627-29627/com.example.esense_application I/System.out: ANDROID Audio SCO state: 1
2019-11-24 11:26:57.769 29627-29627/com.example.esense_application I/System.out: ANDROID Audio SCO state: 1
2019-11-24 11:27:00.647 29627-29627/com.example.esense_application W/System.err: java.io.FileNotFoundException: /storage/emulated/0/AudioRecording.3gp: open failed: EACCES (Permission denied)
2019-11-24 11:27:00.647 29627-29627/com.example.esense_application W/System.err: at libcore.io.IoBridge.open(IoBridge.java:496)
2019-11-24 11:27:00.647 29627-29627/com.example.esense_application W/System.err: at java.io.RandomAccessFile.<init>(RandomAccessFile.java:289)
2019-11-24 11:27:00.647 29627-29627/com.example.esense_application W/System.err: at java.io.RandomAccessFile.<init>(RandomAccessFile.java:152)
2019-11-24 11:27:00.647 29627-29627/com.example.esense_application W/System.err: at android.media.MediaRecorder.prepare(MediaRecorder.java:1046)
2019-11-24 11:27:00.647 29627-29627/com.example.esense_application W/System.err: at com.example.esense_application.MainActivity$1.onClick(MainActivity.java:67)
2019-11-24 11:27:00.647 29627-29627/com.example.esense_application W/System.err: at android.view.View.performClick(View.java:7140)
2019-11-24 11:27:00.647 29627-29627/com.example.esense_application W/System.err: at android.view.View.performClickInternal(View.java:7117)
2019-11-24 11:27:00.647 29627-29627/com.example.esense_application W/System.err: at android.view.View.access$3500(View.java:801)
2019-11-24 11:27:00.647 29627-29627/com.example.esense_application W/System.err: at android.view.View$PerformClick.run(View.java:27351)
2019-11-24 11:27:00.647 29627-29627/com.example.esense_application W/System.err: at android.os.Handler.handleCallback(Handler.java:883)
2019-11-24 11:27:00.648 29627-29627/com.example.esense_application W/System.err: at android.os.Handler.dispatchMessage(Handler.java:100)
2019-11-24 11:27:00.648 29627-29627/com.example.esense_application W/System.err: at android.os.Looper.loop(Looper.java:214)
2019-11-24 11:27:00.648 29627-29627/com.example.esense_application W/System.err: at android.app.ActivityThread.main(ActivityThread.java:7356)
2019-11-24 11:27:00.648 29627-29627/com.example.esense_application W/System.err: at java.lang.reflect.Method.invoke(Native Method)
2019-11-24 11:27:00.648 29627-29627/com.example.esense_application W/System.err: at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
2019-11-24 11:27:00.648 29627-29627/com.example.esense_application W/System.err: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)
2019-11-24 11:27:00.648 29627-29627/com.example.esense_application W/System.err: Caused by: android.system.ErrnoException: open failed: EACCES (Permission denied)
2019-11-24 11:27:00.648 29627-29627/com.example.esense_application W/System.err: at libcore.io.Linux.open(Native Method)
2019-11-24 11:27:00.648 29627-29627/com.example.esense_application W/System.err: at libcore.io.ForwardingOs.open(ForwardingOs.java:167)
2019-11-24 11:27:00.648 29627-29627/com.example.esense_application W/System.err: at libcore.io.BlockGuardOs.open(BlockGuardOs.java:252)
2019-11-24 11:27:00.648 29627-29627/com.example.esense_application W/System.err: at libcore.io.ForwardingOs.open(ForwardingOs.java:167)
2019-11-24 11:27:00.648 29627-29627/com.example.esense_application W/System.err: at android.app.ActivityThread$AndroidOs.open(ActivityThread.java:7255)
2019-11-24 11:27:00.648 29627-29627/com.example.esense_application W/System.err: at libcore.io.IoBridge.open(IoBridge.java:482)
2019-11-24 11:27:00.648 29627-29627/com.example.esense_application W/System.err: ... 15 more
2019-11-24 11:27:03.528 29627-29627/com.example.esense_application E/MediaRecorder: stop called in an invalid state: 4
2019-11-24 11:27:03.528 29627-29627/com.example.esense_application D/AndroidRuntime: Shutting down VM
2019-11-24 11:27:03.529 29627-29627/com.example.esense_application E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.esense_application, PID: 29627
java.lang.IllegalStateException
at android.media.MediaRecorder.stop(Native Method)
at com.example.esense_application.MainActivity$2.onClick(MainActivity.java:98)
at android.view.View.performClick(View.java:7140)
at android.view.View.performClickInternal(View.java:7117)
at android.view.View.access$3500(View.java:801)
at android.view.View$PerformClick.run(View.java:27351)
at android.os.Handler.handleCallback(Handler.java:883)
at android.os.Handler.dispatchMessage(Handler.java:100)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7356)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)
2019-11-24 11:27:03.540 29627-29627/com.example.esense_application I/Process: Sending signal. PID: 29627 SIG: 9
Your MediaRecorder is throwing when you try to stop() it because it has never entered the "recording" state. In fact, it never even entered the "prepared" state, because your call to prepare() did not complete successfully.
SOLUTION
Do not allow a call to start() until the prepare() call has returned (without throwing).
Do not allow a call to stop() until the start() call has returned (without throwing).
Make sure you have chosen a valid location for your output file. Try using getExternalFilesDir( null ) instead of Environment.getExternalStorageDirectory(). The bad file path is the reason your prepare() call is currently failing with an EACCESS.
As you can see, swallowing exceptions without addressing their root cause (i.e., just doing a e.printStackTrace() and carrying on), can rapidly lead to problems -- even in rough code used for learning/experimentation. If you are going to add an exception handler, it is better to provide real error handling -- and always make sure you understand why an exception is being thrown.
I am new on android and working on my android app's login activity for which em using php mysql with volley library. But every time I run my app on emulator it shows the message Unfortunately, app has stopped. Here the login activity code is:
package com.example.u.locationtracker;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Map;
public class MainActivity extends AppCompatActivity {
private EditText pass1, email1;
private Button login;
private TextView link_reg;
private ProgressBar loading;
private String URL_LOGIN= "http://192.168.1.1/register.php";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
email1= (EditText) findViewById(R.id.etemail1);
pass1= (EditText) findViewById(R.id.etpassl);
loading= (ProgressBar) findViewById(R.id.loading1);
link_reg= (TextView) findViewById(R.id.signup);
login= (Button) findViewById(R.id.btnlogin);
login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String mEmail= email1.getText().toString().trim();
String mpass= pass1.getText().toString().trim();
if(!mEmail.isEmpty() || !mpass.isEmpty()){
Login(mEmail, mpass);
}else{
email1.setError("Please Enter Email...!");
pass1.setError("Please Enter Password...!");
}
}
});
link_reg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent it= new Intent(MainActivity.this, Register.class);
startActivity(it);
}
});
}
private void Login(final String email, final String pass) {
loading.setVisibility(View.VISIBLE);
login.setVisibility(View.GONE);
StringRequest stringRequest= new StringRequest(Request.Method.POST, URL_LOGIN,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try{
JSONObject jsonObject= new JSONObject(response);
String success= jsonObject.getString("Success");
JSONArray jsonArray= jsonObject.getJSONArray("Login");
if(success.equals("1")){
for (int i= 0; i < jsonArray.length(); i++){
JSONObject object= jsonArray.getJSONObject(i);
Toast t= Toast.makeText(MainActivity.this,
"Login Successful", Toast.LENGTH_LONG);
t.show();
loading.setVisibility(View.GONE);
}
}
}catch (JSONException e) {
e.printStackTrace();
loading.setVisibility(View.GONE);
login.setVisibility(View.VISIBLE);
Toast t1= Toast.makeText(MainActivity.this,
"Error" + e.toString(),
Toast.LENGTH_LONG);
t1.show();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
loading.setVisibility(View.GONE);
login.setVisibility(View.VISIBLE);
Toast t2= Toast.makeText(MainActivity.this,
"Error" + error.toString(),
Toast.LENGTH_LONG);
t2.show();
}
})
{
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params= new HashMap<>();
params.put("Email", email);
params.put("Password", pass);
return params;
}
};
RequestQueue requestQueue= Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
}
}
According to logcat the problem is:
at com.example.u.locationtracker.MainActivity.onCreate(MainActivity.java:39)
here the php code:
<?php
if ($_SERVER['REQUEST_METHOD']=='POST') {
$email= $_POST['email1'];
$pass= $_POST['pass1'];
require_once 'connect.php';
$select= "SELECT * FROM user_table WHERE Email= '$email' ";
$r= mysqli_query($conn, $select);
$result= array();
$result['login']= array();
if (mysqli_num_rows($r)=== 1) {
$row= mysqli_fetch_assoc($r);
if ( password_verify($pass, $row['Pass']) ) {
$index['Name']= $row['Name'];
$index['Email']= $row['Email'];
array_push($result['login'], $index);
$result['success']= "1";
$result['message']= "Success";
echo json_encode($result);
mysql_close($conn);
}else{
$result['success']= "0";
$result['message']= "Error";
echo json_encode($result);
mysql_close($conn);
}
}
}
?>
Here is the Logcat:
02-03 21:03:21.626 2006-2012/? E/jdwp: Failed writing handshake bytes: Broken pipe (-1 of 14)
02-03 21:03:21.806 2006-2006/? E/dalvikvm: Could not find class 'android.support.v4.view.ViewCompat$OnUnhandledKeyEventListenerWrapper', referenced from method android.support.v4.view.ViewCompat.addOnUnhandledKeyEventListener
02-03 21:03:21.806 2006-2006/? E/dalvikvm: Could not find class 'android.view.WindowInsets', referenced from method android.support.v4.view.ViewCompat.dispatchApplyWindowInsets
02-03 21:03:21.826 2006-2006/? E/dalvikvm: Could not find class 'android.view.WindowInsets', referenced from method android.support.v4.view.ViewCompat.onApplyWindowInsets
02-03 21:03:21.826 2006-2006/? E/dalvikvm: Could not find class 'android.view.View$OnUnhandledKeyEventListener', referenced from method android.support.v4.view.ViewCompat.removeOnUnhandledKeyEventListener
02-03 21:03:21.836 2006-2006/? E/dalvikvm: Could not find class 'android.support.v4.view.ViewCompat$1', referenced from method android.support.v4.view.ViewCompat.setOnApplyWindowInsetsListener
02-03 21:03:22.756 2006-2006/com.example.u.locationtracker E/dalvikvm: Could not find class 'android.graphics.drawable.RippleDrawable', referenced from method android.support.v7.widget.AppCompatImageHelper.hasOverlappingRendering
02-03 21:03:27.786 2006-2006/com.example.u.locationtracker E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.u.locationtracker, PID: 2006
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.u.locationtracker/com.example.u.locationtracker.MainActivity}: android.view.InflateException: Binary XML file line #45: Error inflating class ImageView
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2193)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2243)
at android.app.ActivityThread.access$800(ActivityThread.java:135)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5019)
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:779)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
at dalvik.system.NativeStart.main(Native Method)
Caused by: android.view.InflateException: Binary XML file line #45: Error inflating class ImageView
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:713)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:755)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:758)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:758)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:758)
at android.view.LayoutInflater.inflate(LayoutInflater.java:492)
at android.view.LayoutInflater.inflate(LayoutInflater.java:397)
at android.view.LayoutInflater.inflate(LayoutInflater.java:353)
at android.support.v7.app.AppCompatDelegateImpl.setContentView(AppCompatDelegateImpl.java:469)
at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:140)
at com.example.u.locationtracker.MainActivity.onCreate(MainActivity.java:39)
at android.app.Activity.performCreate(Activity.java:5231)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1104)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2157)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2243)
at android.app.ActivityThread.access$800(ActivityThread.java:135)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5019)
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:779)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
at dalvik.system.NativeStart.main(Native Method)
Caused by: android.content.res.Resources$NotFoundException: Resource is not a Drawable (color or path): TypedValue{t=0x1/d=0x7f07005d a=-1 r=0x7f07005d}
at android.content.res.Resources.loadDrawable(Resources.java:2068)
at android.content.res.TypedArray.getDrawable(TypedArray.java:602)
at android.widget.ImageView.<init>(ImageView.java:129)
at android.support.v7.widget.AppCompatImageView.<init>(AppCompatImageView.java:72)
at android.support.v7.widget.AppCompatImageView.<init>(AppCompatImageView.java:68)
at android.support.v7.app.AppCompatViewInflater.createImageView(AppCompatViewInflater.java:182)
at android.support.v7.app.AppCompatViewInflater.createView(AppCompatViewInflater.java:106)
at android.support.v7.app.AppCompatDelegateImpl.createView(AppCompatDelegateImpl.java:1266)
at android.support.v7.app.AppCompatDelegateImpl.onCreateView(AppCompatDelegateImpl.java:1316)
at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:684)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:755)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:758)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:758)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:758)
at android.view.LayoutInflater.inflate(LayoutInflater.java:492)
at android.view.LayoutInflater.inflate(LayoutInflater.java:397)
at android.view.LayoutInflater.inflate(LayoutInflater.java:353)
at android.support.v7.app.AppCompatDelegateImpl.setContentView(AppCompatDelegateImpl.java:469)
at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:140)
at com.example.u.locationtracker.MainActivity.onCreate(MainActivity.java:39)
at android.app.Activity.performCreate(Activity.java:5231)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1104)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2157)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2243)
at android.app.ActivityThread.access$800(ActivityThread.java:135)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5019)
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:779)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
at dalvik.system.NativeStart.main(Native Method)
The problem seems to lie in this line:
setContentView(R.layout.activity_main);
Are you sure, the layout exists and doesn't have compile errors?
A full stacktrace would be more helpful
I'm creating an Android project where the Registrationadmin activity connects to a PHP file (in a local server, localhost) using HttpURLConnection;
I am having problem while running the project i am getting this D/NetworkSecurityConfig: Using Network Security Config from resource network_security_config debugBuild: true
I have already given the connection and read timeout.
Registrationadmin.java code is:
public void btnregisteradm(View v) {
if (awesomeValidation.validate()) {
admname = name.getText().toString();
admpass = password.getText().toString();
admemail = email.getText().toString();
admmob = mob.getText().toString();
//Toast.makeText(ctx, "we are here", Toast.LENGTH_SHORT).show();
String method = "register";
BackgroundTask backgroundTask = new BackgroundTask(this);
backgroundTask.execute(method,admname,admemail,admpass,admmob);
finish();
}
}
my BackgroundTask.java is
package com.example.hp.healthcareapp;
import android.app.AlertDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.Toast;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import static android.content.ContentValues.TAG;
/**
* Created by HP on 12/18/2017.
*/
public class BackgroundTask extends AsyncTask<String,Void,String> {
AlertDialog alertDialog;
Context ctx;
BackgroundTask(Context ctx)
{
this.ctx =ctx;
}
#Override
protected void onPreExecute() {
alertDialog = new AlertDialog.Builder(ctx).create();
alertDialog.setTitle("Login Information....");
}
#Override
protected String doInBackground(String... params) {
String reg_url = "http://10.14.83.2:8080/register.php";
String login_url = "http://192.168.2.4:8080/login.php";
String method = params[0];
if (method.equals("register")) {
String admname = params[1];
//Log.d(TAG,admname);
String admemail = params[2];
String admpass = params[3];
String admmob = params[4];
try {
URL url = new URL(reg_url);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
httpURLConnection.setReadTimeout(10000);
httpURLConnection.setConnectTimeout(15000);
//httpURLConnection.setDoInput(true);
OutputStream OS = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(OS, "UTF-8"));
String data = URLEncoder.encode("admname", "UTF-8")+"="+URLEncoder.encode(admname, "UTF-8") + "&" +
URLEncoder.encode("admemail", "UTF-8")+"="+URLEncoder.encode(admemail, "UTF-8") + "&" +
URLEncoder.encode("admpass", "UTF-8")+"="+URLEncoder.encode(admpass, "UTF-8")+"&"+
URLEncoder.encode("admmob", "UTF-8")+"="+URLEncoder.encode(admmob, "UTF-8");
Log.d(TAG,data);
httpURLConnection.connect();
bufferedWriter.write(data);
bufferedWriter.flush();
bufferedWriter.close();
OS.close();
InputStream IS = httpURLConnection.getInputStream();
IS.close();
//httpURLConnection.connect();
httpURLConnection.disconnect();
return "Registration Success...";
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
else if(method.equals("login"))
{
}
return null;
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
#Override
protected void onPostExecute(String result) {
if(result.equals("Registration Success..."))
{
Toast.makeText(ctx, result, Toast.LENGTH_LONG).show();
}
else
{
alertDialog.setMessage(result);
alertDialog.show();
}
}
}
register.php is
<?php
echo "this is it";
require "init.php";
$admmane = (isset($_POST['admname']) ) ? $_POST['admname'] : '';
$admpass = (isset($_POST['admpass']) ) ? $_POST['admpass'] : '';
$admemail = (isset($_POST['admemail']) ) ? $_POST['admemail'] : '';
$admmob=(isset($_POST['admmob']) ) ? $_POST['admmob'] : '';
//$admmane = "sdf";
//$admpassword = "sdf";
//$admemail = "sdf#r54";
//$admmob="sdf";
$sql_query= "insert into admin values ('$admmane','$admemail','$admpass','$admmob');";
if(mysqli_query($con, $sql_query)){
echo '{"message":"able to save the data to the database."}';
}
?>
logcat which i am getting on running the project is:
12-19 11:24:48.803 2555-2560/com.example.hp.healthcareapp I/zygote: Increasing code cache capacity to 1024KB
12-19 11:24:55.026 2555-3178/com.example.hp.healthcareapp D/NetworkSecurityConfig: Using Network Security Config from resource network_security_config debugBuild: true
12-19 11:24:55.048 2555-3178/com.example.hp.healthcareapp D/ContentValues: admname=shaista&admemail=shaista8080%40gmail.com&admpass=Pro%401234&admmob=9593626313
12-19 11:24:55.277 2555-2618/com.example.hp.healthcareapp D/EGL_emulation: eglMakeCurrent: 0x9f1840c0: ver 2 0 (tinfo 0x9f183300)
12-19 11:24:55.393 2555-2618/com.example.hp.healthcareapp D/EGL_emulation: eglMakeCurrent: 0x9f1840c0: ver 2 0 (tinfo 0x9f183300)
12-19 11:24:55.481 2555-2618/com.example.hp.healthcareapp D/EGL_emulation: eglMakeCurrent: 0x9f1840c0: ver 2 0 (tinfo 0x9f183300)
12-19 11:24:55.495 2555-2618/com.example.hp.healthcareapp D/OpenGLRenderer: endAllActiveAnimators on 0x8bb11880 (RippleDrawable) with handle 0x9f183b50
12-19 11:25:05.057 2555-3178/com.example.hp.healthcareapp W/System.err: java.net.SocketTimeoutException: timeout
12-19 11:25:05.058 2555-3178/com.example.hp.healthcareapp W/System.err: at com.android.okhttp.okio.Okio$3.newTimeoutException(Okio.java:212)
12-19 11:25:05.059 2555-3178/com.example.hp.healthcareapp W/System.err: at com.android.okhttp.okio.AsyncTimeout.exit(AsyncTimeout.java:261)
12-19 11:25:05.059 2555-3178/com.example.hp.healthcareapp W/System.err: at com.android.okhttp.okio.AsyncTimeout$2.read(AsyncTimeout.java:215)
12-19 11:25:05.060 2555-3178/com.example.hp.healthcareapp W/System.err: at com.android.okhttp.okio.RealBufferedSource.indexOf(RealBufferedSource.java:306)
12-19 11:25:05.061 2555-3178/com.example.hp.healthcareapp W/System.err: at com.android.okhttp.okio.RealBufferedSource.indexOf(RealBufferedSource.java:300)
12-19 11:25:05.063 2555-3178/com.example.hp.healthcareapp W/System.err: at com.android.okhttp.okio.RealBufferedSource.readUtf8LineStrict(RealBufferedSource.java:196)
12-19 11:25:05.065 2555-3178/com.example.hp.healthcareapp W/System.err: at com.android.okhttp.internal.http.Http1xStream.readResponse(Http1xStream.java:186)
12-19 11:25:05.065 2555-3178/com.example.hp.healthcareapp W/System.err: at com.android.okhttp.internal.http.Http1xStream.readResponseHeaders(Http1xStream.java:127)
12-19 11:25:05.067 2555-3178/com.example.hp.healthcareapp W/System.err: at com.android.okhttp.internal.http.HttpEngine.readNetworkResponse(HttpEngine.java:737)
12-19 11:25:05.067 2555-3178/com.example.hp.healthcareapp W/System.err: at com.android.okhttp.internal.http.HttpEngine.readResponse(HttpEngine.java:609)
12-19 11:25:05.068 2555-3178/com.example.hp.healthcareapp W/System.err: at com.android.okhttp.internal.huc.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:471)
12-19 11:25:05.071 2555-3178/com.example.hp.healthcareapp W/System.err: at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:407)
12-19 11:25:05.071 2555-3178/com.example.hp.healthcareapp W/System.err: at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:244)
12-19 11:25:05.072 2555-3178/com.example.hp.healthcareapp W/System.err: at com.example.hp.healthcareapp.BackgroundTask.doInBackground(BackgroundTask.java:70)
12-19 11:25:05.072 2555-3178/com.example.hp.healthcareapp W/System.err: at com.example.hp.healthcareapp.BackgroundTask.doInBackground(BackgroundTask.java:25)
12-19 11:25:05.073 2555-3178/com.example.hp.healthcareapp W/System.err: at android.os.AsyncTask$2.call(AsyncTask.java:333)
12-19 11:25:05.074 2555-3178/com.example.hp.healthcareapp W/System.err: at java.util.concurrent.FutureTask.run(FutureTask.java:266)
12-19 11:25:05.076 2555-3178/com.example.hp.healthcareapp W/System.err: at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:245)
12-19 11:25:05.077 2555-3178/com.example.hp.healthcareapp W/System.err: at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1162)
12-19 11:25:05.077 2555-3178/com.example.hp.healthcareapp W/System.err: at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:636)
12-19 11:25:05.078 2555-3178/com.example.hp.healthcareapp W/System.err: at java.lang.Thread.run(Thread.java:764)
12-19 11:25:05.079 2555-3178/com.example.hp.healthcareapp W/System.err: Caused by: java.net.SocketException: Socket closed
12-19 11:25:05.080 2555-3178/com.example.hp.healthcareapp W/System.err: at java.net.SocketInputStream.read(SocketInputStream.java:203)
12-19 11:25:05.080 2555-3178/com.example.hp.healthcareapp W/System.err: at java.net.SocketInputStream.read(SocketInputStream.java:139)
12-19 11:25:05.082 2555-3178/com.example.hp.healthcareapp W/System.err: at com.android.okhttp.okio.Okio$2.read(Okio.java:136)
12-19 11:25:05.083 2555-3178/com.example.hp.healthcareapp W/System.err: at com.android.okhttp.okio.AsyncTimeout$2.read(AsyncTimeout.java:211)
12-19 11:25:05.083 2555-3178/com.example.hp.healthcareapp W/System.err: ... 18 more
12-19 11:25:05.085 2555-2555/com.example.hp.healthcareapp D/AndroidRuntime: Shutting down VM
12-19 11:25:05.089 2555-2555/com.example.hp.healthcareapp E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.hp.healthcareapp, PID: 2555
java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.lang.String.equals(java.lang.Object)' on a null object reference
at com.example.hp.healthcareapp.BackgroundTask.onPostExecute(BackgroundTask.java:95)
at com.example.hp.healthcareapp.BackgroundTask.onPostExecute(BackgroundTask.java:25)
at android.os.AsyncTask.finish(AsyncTask.java:695)
at android.os.AsyncTask.-wrap1(Unknown Source:0)
at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:712)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:164)
at android.app.ActivityThread.main(ActivityThread.java:6494)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
can you please check whether below 2 API endpoints are working
You can check it using postman
Run app on server (put server ip from below urls)
String reg_url = "http://10.14.83.2:8080/register.php";
String login_url = "http://192.168.2.4:8080/login.php";
Make sure if these are working.that should return 200 response.
You can then check into database if registration data is getting saved.
I currently am trying to pull down an RSS Feed as an XML file and I'm trying to use RXJava instead of an AsyncTask to parse and download the file.
I'm getting a network on the main thread error though while I'm trying to pull the feed down.
Here is the relevant code with observable which is in the main activity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = (RecyclerView) findViewById(R.id.rv_test_items);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
final ArrayList<TestItem> testItems = new ArrayList<>();
//testItems.add(new TestItem("Title here", "Content here"));
RssReader reader = new RssReader("http://www.feedforall.com/sample.xml");
// Subscribe on a new background thread, while returning the result on the UI thread.
// Using the RSS Classes we will pull the rss items from the rss feed and then create our
// own TestItem from them.
try {
Observable
.from(reader.getItems())
.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Action1<RssItem>() {
#Override
public void call(RssItem item) {
TestItem newItem = new TestItem(item.getTitle(), item.getDescription());
testItems.add(newItem);
}
});
} catch (Exception e) {
e.printStackTrace();
Log.e("App", "Failed to download RSS Items");
}
TestItemAdapter testItemAdapter = new TestItemAdapter(testItems);
recyclerView.setLayoutManager(linearLayoutManager);
recyclerView.setAdapter(testItemAdapter);
And here is my RSSReader class
public class RssReader {
private String rssUrl;
public RssReader(String url) {
rssUrl = url;
}
public List<RssItem> getItems() throws Exception {
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser saxParser = factory.newSAXParser();
//Creates a new RssHandler which will do all the parsing.
RssHandler handler = new RssHandler();
//Pass SaxParser the RssHandler that was created.
saxParser.parse(rssUrl, handler);
return handler.getRssItemList();
}
}
And my RSSHandler class
public class RssHandler extends DefaultHandler {
private List<RssItem> rssItemList;
private RssItem currentItem;
private boolean parsingTitle;
private boolean parsingLink;
private boolean parsingDescription;
public RssHandler() {
//Initializes a new ArrayList that will hold all the generated RSS items.
rssItemList = new ArrayList<RssItem>();
}
public List<RssItem> getRssItemList() {
return rssItemList;
}
//Called when an opening tag is reached, such as <item> or <title>
#Override
public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
if (qName.equals("item"))
currentItem = new RssItem();
else if (qName.equals("title"))
parsingTitle = true;
else if (qName.equals("link"))
parsingLink = true;
else if (qName.equals("description"))
parsingDescription = true;
else if (qName.equals("media:thumbnail") || qName.equals("media:content") || qName.equals("image")) {
if (attributes.getValue("url") != null)
currentItem.setImageUrl(attributes.getValue("url"));
}
}
//Called when a closing tag is reached, such as </item> or </title>
#Override
public void endElement(String uri, String localName, String qName) throws SAXException {
if (qName.equals("item")) {
//End of an item so add the currentItem to the list of items.
rssItemList.add(currentItem);
currentItem = null;
} else if (qName.equals("title"))
parsingTitle = false;
else if (qName.equals("link"))
parsingLink = false;
else if (qName.equals("description"))
parsingDescription = false;
}
//Goes through character by character when parsing whats inside of a tag.
#Override
public void characters(char[] ch, int start, int length) throws SAXException {
if (currentItem != null) {
//If parsingTitle is true, then that means we are inside a <title> tag so the text is the title of an item.
if (parsingTitle)
currentItem.setTitle(new String(ch, start, length));
//If parsingLink is true, then that means we are inside a <link> tag so the text is the link of an item.
else if (parsingLink)
currentItem.setLink(new String(ch, start, length));
//If parsingDescription is true, then that means we are inside a <description> tag so the text is the description of an item.
else if (parsingDescription)
currentItem.setDescription(new String(ch, start, length));
}
}
}
Stack trace
10-07 11:39:15.040 1959-1959/? I/art: Late-enabling -Xcheck:jni
10-07 11:39:15.208 1959-1959/? W/System.err: java.io.IOException: Couldn't open http://www.feedforall.com/sample.xml
10-07 11:39:15.208 1959-1959/? W/System.err: at org.apache.harmony.xml.ExpatParser.openUrl(ExpatParser.java:755)
10-07 11:39:15.208 1959-1959/? W/System.err: at org.apache.harmony.xml.ExpatReader.parse(ExpatReader.java:292)
10-07 11:39:15.208 1959-1959/? W/System.err: at javax.xml.parsers.SAXParser.parse(SAXParser.java:390)
10-07 11:39:15.208 1959-1959/? W/System.err: at javax.xml.parsers.SAXParser.parse(SAXParser.java:266)
10-07 11:39:15.208 1959-1959/? W/System.err: at com.polymorphicinc.retrofitsample.rss.RssReader.getItems(RssReader.java:36)
10-07 11:39:15.208 1959-1959/? W/System.err: at com.polymorphicinc.retrofitsample.ui.MainActivity.onCreate(MainActivity.java:47)
10-07 11:39:15.208 1959-1959/? W/System.err: at android.app.Activity.performCreate(Activity.java:5990)
10-07 11:39:15.208 1959-1959/? W/System.err: at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106)
10-07 11:39:15.208 1959-1959/? W/System.err: at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2278)
10-07 11:39:15.208 1959-1959/? W/System.err: at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387)
10-07 11:39:15.208 1959-1959/? W/System.err: at android.app.ActivityThread.access$800(ActivityThread.java:151)
10-07 11:39:15.208 1959-1959/? W/System.err: at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303)
10-07 11:39:15.208 1959-1959/? W/System.err: at android.os.Handler.dispatchMessage(Handler.java:102)
10-07 11:39:15.208 1959-1959/? W/System.err: at android.os.Looper.loop(Looper.java:135)
10-07 11:39:15.208 1959-1959/? W/System.err: at android.app.ActivityThread.main(ActivityThread.java:5254)
10-07 11:39:15.208 1959-1959/? W/System.err: at java.lang.reflect.Method.invoke(Native Method)
10-07 11:39:15.209 1959-1959/? W/System.err: at java.lang.reflect.Method.invoke(Method.java:372)
10-07 11:39:15.209 1959-1959/? W/System.err: at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
10-07 11:39:15.209 1959-1959/? W/System.err: at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)
10-07 11:39:15.209 1959-1959/? W/System.err: Caused by: android.os.NetworkOnMainThreadException
10-07 11:39:15.209 1959-1959/? W/System.err: at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1147)
10-07 11:39:15.209 1959-1959/? W/System.err: at java.net.InetAddress.lookupHostByName(InetAddress.java:418)
10-07 11:39:15.209 1959-1959/? W/System.err: at java.net.InetAddress.getAllByNameImpl(InetAddress.java:252)
10-07 11:39:15.209 1959-1959/? W/System.err: at java.net.InetAddress.getAllByName(InetAddress.java:215)
10-07 11:39:15.209 1959-1959/? W/System.err: at com.android.okhttp.HostResolver$1.getAllByName(HostResolver.java:29)
10-07 11:39:15.209 1959-1959/? W/System.err: at com.android.okhttp.internal.http.RouteSelector.resetNextInetSocketAddress(RouteSelector.java:232)
10-07 11:39:15.209 1959-1959/? W/System.err: at com.android.okhttp.internal.http.RouteSelector.next(RouteSelector.java:124)
10-07 11:39:15.209 1959-1959/? W/System.err: at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:272)
10-07 11:39:15.209 1959-1959/? W/System.err: at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:211)
10-07 11:39:15.209 1959-1959/? W/System.err: at com.android.okhttp.internal.http.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:382)
10-07 11:39:15.209 1959-1959/? W/System.err: at com.android.okhttp.internal.http.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:332)
10-07 11:39:15.209 1959-1959/? W/System.err: at com.android.okhttp.internal.http.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:199)
10-07 11:39:15.209 1959-1959/? W/System.err: at org.apache.harmony.xml.ExpatParser.openUrl(ExpatParser.java:753)
10-07 11:39:15.209 1959-1959/? W/System.err: ... 18 more
10-07 11:39:15.209 1959-1959/? E/App: Failed to download RSS Items
10-07 11:39:15.215 1959-1978/? D/OpenGLRenderer: Use EGL_SWAP_BEHAVIOR_PRESERVED: true
10-07 11:39:15.216 1959-1959/? D/: HostConnection::get() New Host Connection established 0xb42d9a00, tid 1959
10-07 11:39:15.219 1959-1959/? D/Atlas: Validating map...
10-07 11:39:15.281 1959-1978/? D/libEGL: loaded /system/lib/egl/libEGL_emulation.so
10-07 11:39:15.282 1959-1978/? D/libEGL: loaded /system/lib/egl/libGLESv1_CM_emulation.so
10-07 11:39:15.286 1959-1978/? D/libEGL: loaded /system/lib/egl/libGLESv2_emulation.so
10-07 11:39:15.295 1959-1978/? D/: HostConnection::get() New Host Connection established 0xb42d9b90, tid 1978
10-07 11:39:15.311 1959-1978/? I/OpenGLRenderer: Initialized EGL, version 1.4
10-07 11:39:15.360 1959-1978/? D/OpenGLRenderer: Enabling debug mode 0
10-07 11:39:15.381 1959-1978/? W/EGL_emulation: eglSurfaceAttrib not implemented
10-07 11:39:15.381 1959-1978/? W/OpenGLRenderer: Failed to set EGL_SWAP_BEHAVIOR on surface 0xb424bb40, error=EGL_SUCCESS
Take a look at this to get an idea how to do it:
public class RssReader {
private String rssUrl;
public RssReader(String url) {
rssUrl = url;
}
public Observable<List<RssItem>> getItems() {
return Observable.create(new Observable.OnSubscribe<List<RssItem>>() {
#Override
public void call(Subscriber<? super List<RssItem>> subscriber) {
try {
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser saxParser = factory.newSAXParser();
//Creates a new RssHandler which will do all the parsing.
RssHandler handler = new RssHandler();
//Pass SaxParser the RssHandler that was created.
saxParser.parse(rssUrl, handler);
subscriber.onNext(handler.getRssItemList());
subscriber.onCompleted();
} catch (Exception e) {
subscriber.onError(e);
}
}
});
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
recyclerView = (RecyclerView) findViewById(R.id.rv_test_items);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(linearLayoutManager);
RssReader reader = new RssReader("http://www.feedforall.com/sample.xml");
reader.getItems()
.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Action1<List<RssItem>>() {
#Override
public void call(List<RssItem> items) {
final ArrayList<TestItem> testItems = new ArrayList<>(items.size());
for (int size = items.size(), i = 0; i < size; i++) {
RssItem item = items.get(i);
testItems.add(new TestItem(item.getTitle(), item.getDescription()));
}
recyclerView.setAdapter(new TestItemAdapter(testItems));
}
}, new Action1<Throwable>() {
#Override
public void call(Throwable e) {
e.printStackTrace();
Log.e("App", "Failed to download RSS Items");
}
});
}
try this
Observable.defer(() -> Observable.from(reader.getItems())
.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(new Action1<RssItem>() {
#Override
public void call(RssItem item) {
TestItem newItem = new TestItem(item.getTitle(), item.getDescription());
testItems.add(newItem);
}
});
I'm working with a listview which on click opens a dialog box which contains an edittext and a button. On button click, the value entered in the editText is saved in a textView from listview item which had been pressed before. The problem is that the value wasn't saved anymore if I reopened the application. I tried to make it save using sharedPrefences but it's crashing and shows 3 nullpointerexception and can't deal with them.
Here is my:
Carnet.java
package com.cngcnasaud.orar;
import android.app.TabActivity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.TabHost;
import android.widget.TabHost.TabSpec;
#SuppressWarnings("deprecation")
public class Carnet extends TabActivity {
// TabSpec Names
private static final String NOTA_SPEC = "Note";
private static final String ABSENTE_SPEC = "Absente";
private static final String MEDII_SPEC = "Medii";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.carnet);
TabHost tabHost = getTabHost();
TabSpec NotaSpec = tabHost.newTabSpec(NOTA_SPEC);
// Tab Icon
NotaSpec.setIndicator(NOTA_SPEC, getResources().getDrawable(R.drawable.nota_open));
Intent notaIntent = new Intent(this, Note.class);
// Tab Content
NotaSpec.setContent(notaIntent);
TabSpec AbsenteSpec = tabHost.newTabSpec(ABSENTE_SPEC);
AbsenteSpec.setIndicator(ABSENTE_SPEC, getResources().getDrawable(R.drawable.nota_open));
Intent absenteIntent = new Intent(this, Absente.class);
AbsenteSpec.setContent(absenteIntent);
TabSpec MediiSpec = tabHost.newTabSpec(MEDII_SPEC);
AbsenteSpec.setIndicator(MEDII_SPEC, getResources().getDrawable(R.drawable.nota_open));
Intent mediiIntent = new Intent(this, MediiL.class);
AbsenteSpec.setContent(mediiIntent);
// Adding all TabSpec to TabHost
tabHost.addTab(NotaSpec);
tabHost.addTab(AbsenteSpec);
tabHost.addTab(MediiSpec);
}
}
Note.java
package com.cngcnasaud.orar;
import java.util.ArrayList;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.view.Menu;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
public class Note extends Activity {
private static final ListAdapter NoteAdapter = null;
ListView lv;
Context context;
ArrayList<?> prgmName;
TextView text;
public static String[] prgmNameList = { "Romana - ", "Matematica - ",
"Lb. Engleza - ", "Lb. Germana/Franceza - ", "Istorie - ",
"Geografie - ", "Biologie - ", "Fizica - ", "Ed. Fizica - " };
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.note_listview);
text = (TextView) findViewById(R.id.textView2);
context = this;
lv = (ListView) findViewById(R.id.listView);
lv.setAdapter(new NoteAdapter(this, prgmNameList, null));
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
protected void onStop() {
// TODO Auto-generated method stub
NoteAdapter adapter = (NoteAdapter) lv.getAdapter();
// Variable is public for clarity.
String toSave = EncodeDecode.encode(adapter.savedEntries);
SharedPreferences.Editor editor = getSharedPreferences("LV Data",
MODE_PRIVATE).edit();
editor.putString("TVEntries", toSave);
editor.commit();
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
SharedPreferences prefs = getSharedPreferences("LV Data", MODE_PRIVATE);
String encoded = prefs.getString("TVEntries", "");
String[] entries;
if (encoded.equals(""))
entries = null;
else
entries = EncodeDecode.decode(encoded);
NoteAdapter adapter = (NoteAdapter) lv.getAdapter();
adapter.savedEntries = entries;
lv.setAdapter(adapter);
super.onResume();
}
}
And NoteAdapter.java:
package com.cngcnasaud.orar;
import java.util.Arrays;
import android.app.Dialog;
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
public class NoteAdapter extends BaseAdapter {
String[] result;
Context context;
int[] imageId;
private static LayoutInflater inflater = null;
private Dialog dialog;
String[] savedEntries;
String[] saved = null;
public NoteAdapter(Note note, String[] saved, String[] prgmNameList) {
// TODO Auto-generated constructor stub
result = prgmNameList;
context = note;
inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (saved == null) {
savedEntries = new String[result.length];
Arrays.fill(savedEntries, "");
} else
savedEntries = saved;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return result.length;
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return savedEntries[position];
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
public class Holder {
TextView tv;
ImageView img;
public TextView text;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
final Holder holder = new Holder();
View rowView;
rowView = inflater.inflate(R.layout.note_items, null);
holder.tv = (TextView) rowView.findViewById(R.id.textView1);
holder.text = (TextView) rowView.findViewById(R.id.textView2);
holder.text.setText(savedEntries[position]);
holder.img = (ImageView) rowView.findViewById(R.id.imageView1);
rowView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
dialog = new Dialog(context);
dialog.setContentView(R.layout.dialog);
dialog.setTitle("Materie:" + result[position]);
final EditText txtMode = (EditText) dialog
.findViewById(R.id.dialog);
Button btnSave = (Button) dialog.findViewById(R.id.bsave);
btnSave.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String data = txtMode.getText().toString();
holder.text.setText(data);
savedEntries[position] = data;
dialog.dismiss();
Log.d("data", data);
}
});
dialog.show();
}
});
return rowView;
}
}
logcat:
04-18 19:27:28.558: E/AndroidRuntime(1419): FATAL EXCEPTION: main
04-18 19:27:28.558: E/AndroidRuntime(1419): Process: com.cngcnasaud.orar, PID: 1419
04-18 19:27:28.558: E/AndroidRuntime(1419): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.cngcnasaud.orar/com.cngcnasaud.orar.Carnet}: java.lang.RuntimeException: Unable to start activity ComponentInfo{com.cngcnasaud.orar/com.cngcnasaud.orar.Note}: java.lang.NullPointerException
04-18 19:27:28.558: E/AndroidRuntime(1419): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195)
04-18 19:27:28.558: E/AndroidRuntime(1419): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
04-18 19:27:28.558: E/AndroidRuntime(1419): at android.app.ActivityThread.access$800(ActivityThread.java:135)
04-18 19:27:28.558: E/AndroidRuntime(1419): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
04-18 19:27:28.558: E/AndroidRuntime(1419): at android.os.Handler.dispatchMessage(Handler.java:102)
04-18 19:27:28.558: E/AndroidRuntime(1419): at android.os.Looper.loop(Looper.java:136)
04-18 19:27:28.558: E/AndroidRuntime(1419): at android.app.ActivityThread.main(ActivityThread.java:5017)
04-18 19:27:28.558: E/AndroidRuntime(1419): at java.lang.reflect.Method.invokeNative(Native Method)
04-18 19:27:28.558: E/AndroidRuntime(1419): at java.lang.reflect.Method.invoke(Method.java:515)
04-18 19:27:28.558: E/AndroidRuntime(1419): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
04-18 19:27:28.558: E/AndroidRuntime(1419): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
04-18 19:27:28.558: E/AndroidRuntime(1419): at dalvik.system.NativeStart.main(Native Method)
04-18 19:27:28.558: E/AndroidRuntime(1419): Caused by: java.lang.RuntimeException: Unable to start activity ComponentInfo{com.cngcnasaud.orar/com.cngcnasaud.orar.Note}: java.lang.NullPointerException
04-18 19:27:28.558: E/AndroidRuntime(1419): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195)
04-18 19:27:28.558: E/AndroidRuntime(1419): at android.app.ActivityThread.startActivityNow(ActivityThread.java:2035)
04-18 19:27:28.558: E/AndroidRuntime(1419): at android.app.LocalActivityManager.moveToState(LocalActivityManager.java:135)
04-18 19:27:28.558: E/AndroidRuntime(1419): at android.app.LocalActivityManager.startActivity(LocalActivityManager.java:347)
04-18 19:27:28.558: E/AndroidRuntime(1419): at android.widget.TabHost$IntentContentStrategy.getContentView(TabHost.java:749)
04-18 19:27:28.558: E/AndroidRuntime(1419): at android.widget.TabHost.setCurrentTab(TabHost.java:413)
04-18 19:27:28.558: E/AndroidRuntime(1419): at android.widget.TabHost.addTab(TabHost.java:240)
04-18 19:27:28.558: E/AndroidRuntime(1419): at com.cngcnasaud.orar.Carnet.onCreate(Carnet.java:45)
04-18 19:27:28.558: E/AndroidRuntime(1419): at android.app.Activity.performCreate(Activity.java:5231)
04-18 19:27:28.558: E/AndroidRuntime(1419): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
04-18 19:27:28.558: E/AndroidRuntime(1419): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)
04-18 19:27:28.558: E/AndroidRuntime(1419): ... 11 more
04-18 19:27:28.558: E/AndroidRuntime(1419): Caused by: java.lang.NullPointerException
04-18 19:27:28.558: E/AndroidRuntime(1419): at com.cngcnasaud.orar.NoteAdapter.getCount(NoteAdapter.java:46)
04-18 19:27:28.558: E/AndroidRuntime(1419): at android.widget.ListView.setAdapter(ListView.java:480)
04-18 19:27:28.558: E/AndroidRuntime(1419): at com.cngcnasaud.orar.Note.onCreate(Note.java:34)
04-18 19:27:28.558: E/AndroidRuntime(1419): at android.app.Activity.performCreate(Activity.java:5231)
04-18 19:27:28.558: E/AndroidRuntime(1419): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
04-18 19:27:28.558: E/AndroidRuntime(1419): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)
04-18 19:27:28.558: E/AndroidRuntime(1419): ... 21 more
Carnet.java line 45:
tabHost.addTab(NotaSpec);
NoteAdapter.java line 46:
return result.length;
Note.java line 34:
lv.setAdapter(new NoteAdapter(this, prgmNameList, null));
Your String array in null here:
NoteAdapter.java line 46:
return result.length;
because is a class field, you populate in the constructor from a parameter:
public NoteAdapter(Note note, String[] saved, String[] prgmNameList) {
// TODO Auto-generated constructor stub
result = prgmNameList;
that you pass as null here (passed as second parameter, it should be third):
Note.java line 34:
lv.setAdapter(new NoteAdapter(this, prgmNameList, null));
There is no point in passing that as a parameter as it is a public constant (public static final).