Why is my is my App crashing when getting empty data? - java

My app gets data from a PHP file. 3 normal textdata and 5 image urls. The app displays them in a recyclerview with cardviews.
My problem is, that the app crashes when getting empty image urls.
But with empty textdata the app works without problems.
Like:
textdata with content + image urls with content = works
Empty textdata + empty image urls = App crashes
Empty textdata + image urls with content = works
textdata with content + empty image urls = App crashes
This is the getting and sending (to RecyclerviewAdapter) Code:
public void JSON_DATA_WEB_CALL (String url){
jsonArrayRequest = new JsonArrayRequest(url,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
JSON_PARSE_DATA_AFTER_WEBCALL(response);
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
requestQueue = Volley.newRequestQueue(this);
requestQueue.add(jsonArrayRequest);
}
public void JSON_PARSE_DATA_AFTER_WEBCALL(JSONArray array) {
for (int i = 0; i < array.length(); i++) {
GetDataAdapter GetDataAdapter2 = new GetDataAdapter();
JSONObject json = null;
try {
json = array.getJSONObject(i);
GetDataAdapter2.setImageUrl(json.getString(Image_URL_JSON));
GetDataAdapter2.setImageUrl2(json.getString(Image_URL_JSON2));
GetDataAdapter2.setImageUrl3(json.getString(Image_URL_JSON3));
GetDataAdapter2.setImageUrl4(json.getString(Image_URL_JSON4));
GetDataAdapter2.setImageUrl5(json.getString(Image_URL_JSON5));
GetDataAdapter2.setPhone_number(json.getString(SOMETEXT));
GetDataAdapter2.setName(json.getString(SOMETEXT2));
GetDataAdapter2.setSubject2(json.getString(SOMETEXT3));
} catch (JSONException e) {
e.printStackTrace();
}
GetDataAdapter1.add(GetDataAdapter2);
}
recyclerViewadapter = new RecyclerViewAdapter(solutionTemplate.this, GetDataAdapter1, exerciseAdapter);
recyclerView.setAdapter(recyclerViewadapter);
}
The mainproblem is:
json = array.getJSONObject(i);
GetDataAdapter2.setImageUrl(json.getString(Image_URL_JSON));
GetDataAdapter2.setImageUrl2(json.getString(Image_URL_JSON2));
GetDataAdapter2.setImageUrl3(json.getString(Image_URL_JSON3));
GetDataAdapter2.setImageUrl4(json.getString(Image_URL_JSON4));
GetDataAdapter2.setImageUrl5(json.getString(Image_URL_JSON5));
GetDataAdapter2.setPhone_number(json.getString(SOMETEXT));
GetDataAdapter2.setName(json.getString(SOMETEXT2));
GetDataAdapter2.setSubject2(json.getString(SOMETEXT3));
Working:
json = array.getJSONObject(i);
GetDataAdapter2.setImageUrl(json.getString(Image_URL_JSON));
GetDataAdapter2.setImageUrl2(json.getString(Image_URL_JSON2));
GetDataAdapter2.setImageUrl3(json.getString(Image_URL_JSON3));
GetDataAdapter2.setImageUrl4(json.getString(Image_URL_JSON4));
GetDataAdapter2.setImageUrl5(json.getString(Image_URL_JSON5));
Not working:
GetDataAdapter2.setPhone_number(json.getString(SOMETEXT));
GetDataAdapter2.setName(json.getString(SOMETEXT2));
GetDataAdapter2.setSubject2(json.getString(SOMETEXT3));
Getting image urls with content is necassary!
But it should work without it!
This is the GetDataAdapter:
public String getPhone_number() {
return phone_number;
}
public void setPhone_number(String phone_number1) {
this.phone_number = phone_number1;
}
public String getSubject2() {
return subject2;
}
public void setSubject2(String subject2) {
this.subject2 = subject2;
}
public String getImageUrl() {
return ImageURL;
}
public void setImageUrl(String imageServerUrl) {
this.ImageURL = imageServerUrl;
}
public String getImageUrl2() {
return ImageURL2;
}
public void setImageUrl2(String imageServerUrl2) {
this.ImageURL2 = imageServerUrl2;
}
public String getImageUrl3() {
return ImageURL3;
}
public void setImageUrl3(String imageServerUrl3) {
this.ImageURL3 = imageServerUrl3;
}
public String getImageUrl4() {
return ImageURL4;
}
public void setImageUrl4(String imageServerUrl4) {
this.ImageURL4 = imageServerUrl4;
}
public String getImageUrl5() {
return ImageURL5;
}
public void setImageUrl5(String imageServerUrl5) {
this.ImageURL5 = imageServerUrl5;
}
RecyclerViewAdapter:
#Override
public void onBindViewHolder(final RecyclerView.ViewHolder holder, int position) {
if (holder instanceof ViewHolder) {
final GetDataAdapter current = getItem(position - 1);
final ViewHolder holder1 = (ViewHolder) holder;
final ImageLoader imageLoader = ImageAdapter.getInstance(context).getImageLoader();
final ImageLoader imageLoader2 = ImageAdapter.getInstance(context).getImageLoader();
final ImageLoader imageLoader3 = ImageAdapter.getInstance(context).getImageLoader();
final ImageLoader imageLoader4 = ImageAdapter.getInstance(context).getImageLoader();
final ImageLoader imageLoader5 = ImageAdapter.getInstance(context).getImageLoader();
imageLoader.get(current.getImageUrl(),
ImageLoader.getImageListener(
holder1.imageView1,
R.mipmap.ic_launcher_image,
android.R.drawable.ic_dialog_alert
)
);
imageLoader2.get(current.getImageUrl2(),
ImageLoader.getImageListener(
holder1.imageView2,
R.mipmap.ic_launcher_image,
android.R.drawable.ic_dialog_alert
)
);
imageLoader3.get(current.getImageUrl3(),
ImageLoader.getImageListener(
holder1.imageView3,
R.mipmap.ic_launcher_image,
android.R.drawable.ic_dialog_alert
)
);
imageLoader4.get(current.getImageUrl4(),
ImageLoader.getImageListener(
holder1.imageView4,
R.mipmap.ic_launcher_image,
android.R.drawable.ic_dialog_alert
)
);
imageLoader5.get(current.getImageUrl5(),
ImageLoader.getImageListener(
holder1.imageView5,
R.mipmap.ic_launcher_image,
android.R.drawable.ic_dialog_alert
)
);
holder1.imageView1.setImageUrl(current.getImageUrl(), imageLoader);
holder1.imageView2.setImageUrl(current.getImageUrl2(), imageLoader2);
holder1.imageView3.setImageUrl(current.getImageUrl3(), imageLoader3);
holder1.imageView4.setImageUrl(current.getImageUrl4(), imageLoader4);
holder1.imageView5.setImageUrl(current.getImageUrl5(), imageLoader5);
holder1.NameTextView.setText(current.getName());
holder1.PhoneNumberTextView.setText(current.getPhone_number());
holder1.SubjectTextView.setText(current.getSubject2());
ImageAdapter:
public class ImageAdapter {
public static ImageAdapter imageAdapter;
public Network networkOBJ ;
public RequestQueue requestQueue1;
public ImageLoader Imageloader1;
public Cache cache1 ;
public static Context context1;
LruCache<String, Bitmap> LRUCACHE = new LruCache<String, Bitmap>(30);
private ImageAdapter(Context context) {
this.context1 = context;
this.requestQueue1 = RequestQueueFunction();
Imageloader1 = new ImageLoader(requestQueue1, new ImageLoader.ImageCache() {
#Override
public Bitmap getBitmap(String URL) {
return LRUCACHE.get(URL);
}
#Override
public void putBitmap(String url, Bitmap bitmap) {
LRUCACHE.put(url, bitmap);
}
});
}
public ImageLoader getImageLoader() {
return Imageloader1;
}
public static ImageAdapter getInstance(Context SynchronizedContext) {
if (imageAdapter == null) {
imageAdapter = new ImageAdapter(SynchronizedContext);
}
return imageAdapter;
}
public RequestQueue RequestQueueFunction() {
if (requestQueue1 == null) {
cache1 = new DiskBasedCache(context1.getCacheDir());
networkOBJ = new BasicNetwork(new HurlStack());
requestQueue1 = new RequestQueue(cache1, networkOBJ);
requestQueue1.start();
}
return requestQueue1;
}
}
PHP:
<?php
$conn = mysqli_connect('localhost', 'root', '','webapp');
$id = $_GET['id'];
$sql = "SELECT * FROM answers WHERE id='$id' ORDER BY id DESC";
$res = mysqli_query($conn,$sql);
$result = array();
while($row = mysqli_fetch_array($res)){
array_push($result,array(
'url2'=>$row['images'],
'url3'=>$row['images2'],
'url4'=>$row['images3'],
'url5'=>$row['images4'],
'url6'=>$row['images5'],
'subject'=>$row['subject'],
'phone'=>$row['phone'],
'name'=>$row['name']));
}
echo json_encode(array_values($result));
mysqli_close($conn);
?>
If PHP sends url2, url3, url4... without content the app chrashes, but phone, name, subject with empty values works without problems.
I think Android has a Problem with converting empty imageurls and with displaying it.
EDIT:
A lot of users said that I have to add the Logcat:
07-16 13:12:10.713 1578-1990/system_process W/ActivityManager: Force finishing activity com.example.jakob.webapplicationsave/.solutionTemplate
07-16 13:12:10.822 1578-1990/system_process W/ActivityManager: Force finishing activity com.example.jakob.webapplicationsave/.Main2Activity
07-16 13:12:10.946 1578-2630/system_process I/OpenGLRenderer: Initialized EGL, version 1.4
07-16 13:12:10.947 1578-2630/system_process D/EGL_emulation: eglCreateContext: 0x9c2be040: maj 2 min 0 rcv 2
07-16 13:12:10.953 1578-2630/system_process D/EGL_emulation: eglMakeCurrent: 0x9c2be040: ver 2 0 (tinfo 0x9efbd6e0)
07-16 13:12:10.962 1578-2630/system_process D/EGL_emulation: eglMakeCurrent: 0x9c2be040: ver 2 0 (tinfo 0x9efbd6e0)
07-16 13:12:11.323 1578-1592/system_process W/ActivityManager: Activity pause timeout for ActivityRecord{e46f507 u0 com.example.jakob.webapplicationsave/.solutionTemplate t497 f}
07-16 13:12:11.372 1930-2076/com.android.launcher3 I/OpenGLRenderer: Initialized EGL, version 1.4
07-16 13:12:11.374 1930-2076/com.android.launcher3 D/EGL_emulation: eglCreateContext: 0xae414660: maj 2 min 0 rcv 2
07-16 13:12:11.385 1930-2076/com.android.launcher3 D/EGL_emulation: eglMakeCurrent: 0xae414660: ver 2 0 (tinfo 0xae412440)
07-16 13:12:11.423 1930-2076/com.android.launcher3 D/EGL_emulation: eglMakeCurrent: 0xae414660: ver 2 0 (tinfo 0xae412440)
07-16 13:12:13.537 1270-1616/? W/audio_hw_generic: Not supplying enough data to HAL, expected position 38006369 , only wrote 37870012
07-16 13:12:14.795 13519-13519/com.example.jakob.webapplicationsave I/Process: Sending signal. PID: 13519 SIG: 9
07-16 13:12:14.814 1578-2630/system_process D/EGL_emulation: eglMakeCurrent: 0x9c2be040: ver 2 0 (tinfo 0x9efbd6e0)
07-16 13:12:14.815 1578-2630/system_process E/Surface: getSlotFromBufferLocked: unknown buffer: 0x9b6834a0
07-16 13:12:14.830 1578-2182/system_process E/JavaBinder: !!! FAILED BINDER TRANSACTION !!! (parcel size = 104)
07-16 13:12:14.830 1578-2182/system_process W/InputMethodManagerService: Got RemoteException sending setActive(false) notification to pid 13519 uid 10062
07-16 13:12:14.833 1578-2182/system_process E/JavaBinder: !!! FAILED BINDER TRANSACTION !!! (parcel size = 104)
07-16 13:12:14.847 1578-1713/system_process D/GraphicsStats: Buffer count: 5
07-16 13:12:14.847 1578-1625/system_process W/InputDispatcher: channel '7af27b1 com.example.jakob.webapplicationsave/com.example.jakob.webapplicationsave.Main2Activity (server)' ~ Consumer closed input channel or an error occurred. events=0x9
07-16 13:12:14.847 1578-2182/system_process I/WindowState: WIN DEATH: Window{7af27b1 u0 com.example.jakob.webapplicationsave/com.example.jakob.webapplicationsave.Main2Activity}
07-16 13:12:14.847 1578-1625/system_process E/InputDispatcher: channel '7af27b1 com.example.jakob.webapplicationsave/com.example.jakob.webapplicationsave.Main2Activity (server)' ~ Channel is unrecoverably broken and will be disposed!
07-16 13:12:14.847 1578-1625/system_process W/InputDispatcher: channel 'cd3daa3 com.example.jakob.webapplicationsave/com.example.jakob.webapplicationsave.solutionTemplate (server)' ~ Consumer closed input channel or an error occurred. events=0x9
07-16 13:12:14.847 1578-1625/system_process E/InputDispatcher: channel 'cd3daa3 com.example.jakob.webapplicationsave/com.example.jakob.webapplicationsave.solutionTemplate (server)' ~ Channel is unrecoverably broken and will be disposed!
07-16 13:12:14.847 1578-2182/system_process W/InputDispatcher: Attempted to unregister already unregistered input channel '7af27b1 com.example.jakob.webapplicationsave/com.example.jakob.webapplicationsave.Main2Activity (server)'
07-16 13:12:14.848 1578-2179/system_process I/WindowState: WIN DEATH: Window{cd3daa3 u0 com.example.jakob.webapplicationsave/com.example.jakob.webapplicationsave.solutionTemplate}
07-16 13:12:14.848 1578-2179/system_process W/InputDispatcher: Attempted to unregister already unregistered input channel 'cd3daa3 com.example.jakob.webapplicationsave/com.example.jakob.webapplicationsave.solutionTemplate (server)'
07-16 13:12:14.853 1259-1259/? W/SurfaceFlinger: couldn't log to binary event log: overflow.
07-16 13:12:14.853 1578-1963/system_process I/ActivityManager: Process com.example.jakob.webapplicationsave (pid 13519) has died
07-16 13:12:15.026 1578-1597/system_process W/AppOps: Finishing op nesting under-run: uid 1000 pkg android code 24 time=0 duration=0 nesting=0
07-16 13:12:17.958 1270-1616/? W/audio_hw_generic: Not supplying enough data to HAL, expected position 38145850 , only wrote 38008822
07-16 13:13:00.065 1259-1351/? D/hwcomposer: hw_composer sent 312 syncs in 60s
07-16 13:14:00.056 1259-1351/? D/hwcomposer: hw_composer sent 5 syncs in 60s

Related

Android studio Mail issue

I have set up classes in my app to send a mail based on the user's name email and message. It seems in app as if it's working fine but no actual email is being sent. Can Anybody help? Thank you in advance.
Here is the Gmail class i have set:
public class GMail {
final String emailPort = "587"; // this is gMail's smtp port number
final String smtpAuth = "true";
final String starttls = "true";
final String emailHost = "smtp.gmail.com";
String fromEmail;
String fromPassword;
List<String> toEmailList;
String emailSubject;
String emailBody;
Properties emailProperties;
Session mailSession;
MimeMessage emailMessage;
// this will be the constructor of the email
public GMail(String fromEmail, String fromPassword, List<String> toEmailList, String emailSubject, String emailBody)
{
this.fromEmail = fromEmail;
this.fromPassword = fromPassword;
this.toEmailList = toEmailList;
this.emailBody = emailBody;
//setting the server settings for Gmail
emailProperties = System.getProperties();
emailProperties.put("mail.smtp.port", emailPort);
emailProperties.put("mail.smtp.auth", smtpAuth);
emailProperties.put("mail.smtp.starttls.enable", starttls);
Log.i("Gmail", "Mail server properties are now set.");
}
public MimeMessage createEmailMessage() throws AddressException,
MessagingException, UnsupportedEncodingException{
mailSession = Session.getDefaultInstance(emailProperties, null);
emailMessage = new MimeMessage(mailSession);
emailMessage.setFrom(new InternetAddress(fromEmail, fromEmail));//address setup
for(String toEmail : toEmailList){
Log.i("GMail", "toEmail" + toEmail);
emailMessage.addRecipient(Message.RecipientType.TO,
new InternetAddress(toEmail));
}
emailMessage.setSubject(emailSubject); //email Subject
emailMessage.setContent(emailBody, "text/html");
return emailMessage;
}
public void sendEmail() throws AddressException, MessagingException
{
Transport transport = mailSession.getTransport("smtp");
transport.connect(emailHost, fromEmail, fromPassword);
Log.i("Gmail", "allrecipients: " + emailMessage.getAllRecipients());
transport.close();
Log.i("Gmail", "Your Email has successfully been sent.");
}
}
Here's my SendMailTask class
public class SendMailTask extends AsyncTask {
private ProgressDialog statusDialog;
private Activity sendMailActivity;
public SendMailTask(Activity activity) {
sendMailActivity = activity;
}
// make the method for showing dialog progress
protected void onPreExecute() {
statusDialog = new ProgressDialog(sendMailActivity);
statusDialog.setMessage("Setting up..");
statusDialog.setIndeterminate(false);
statusDialog.setCancelable(false);
statusDialog.show();
}
//method for creation and sending of email
#Override
protected Object doInBackground(Object... args) {
try{
Log.i("SendMailTask", "Setting up your email ..");
publishProgress("Processing all your information ..");
GMail androidEmail = new GMail(args[0].toString(),
args[1].toString(), (List) args[2], args[3].toString(),
args[4].toString());
publishProgress("Preparing your information ..");
androidEmail.createEmailMessage();
publishProgress("Sending your information ..");
androidEmail.sendEmail();
publishProgress("Information sent.");
Log.i("SendMailTask", "Information sent.");
}catch(Exception e){
publishProgress(e.getMessage());
Log.e("SendMailTask", e.getMessage(), e);
}
return null;
}
// creating method for dialog messages.
#Override
public void onProgressUpdate(Object... values){
statusDialog.setMessage(values[0].toString());
}
//method to get rid of the dialog message.
#Override
public void onPostExecute(Object result){
statusDialog.dismiss();
}
}
and here is the class that im trying to get the mail sent from:
public class HelpPage extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_help_page2);
final EditText mail1 = findViewById(R.id.email1);
final EditText mail2 = findViewById(R.id.email2);
final EditText nameIn = findViewById(R.id.hName1);
final Button btnSub = findViewById(R.id.helpBtn);
final EditText msgIn = findViewById(R.id.hMsg);
final String password = "xxxxxxxx";
final String sendemail = "come2gopj#gmail.com";
final String recemail = "c2grecieve#gmail.com";
final boolean connt;
ConnectivityManager connectivityManager = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
if(connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState() == NetworkInfo.State.CONNECTED ||
connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState() == NetworkInfo.State.CONNECTED){
// Connection affirmative:)
connt = true;
}
else {
connt = false;
Toast.makeText(getApplicationContext(), "You're not connected to the internet",
Toast.LENGTH_LONG).show();
}
btnSub.setOnClickListener(
arg0 -> {
//method to make sure all fields are checked
if(nameIn.getText().toString().equals("")||mail1.getText().toString().equals("")||mail2.getText().toString().equals("")||msgIn.getText().toString().equals(""))
{
Toast.makeText(getApplicationContext(), "Please check you've filled all fields.",
Toast.LENGTH_LONG).show();
}
else if(connt!=true){
Toast.makeText(getApplicationContext(), "You're internet connection needs to be checked",
Toast.LENGTH_LONG).show();
}
else{
if(mail1.getText().toString().equals(mail2.getText().toString())){
Log.i("SendMailActivity", "Send Button Clicked.");
//declaring the recieving, password and sending of the email
List<String> toEmailList = Arrays.asList(recemail.split("\\s*,\\s*")); //Recipient List
Log.i("SendMailActivity", "To List: " + toEmailList);
String emailSubject = ((EditText) findViewById(R.id.hName1)).getText().toString();
String emailEmail = ((EditText) findViewById(R.id.email1)).getText().toString();
String emailBody = "User's Email : " + ((EditText) findViewById(R.id.email1)).getText().toString() + "\n" +
"User's message: "+((EditText) findViewById(R.id.hMsg)).getText().toString();
new SendMailTask(HelpPage.this).execute(sendemail, password,toEmailList,emailSubject,emailBody,emailEmail);//send the email with all the relevant data included
startActivity(new Intent(getApplicationContext(),AfterMail.class)); //this will start the next activity that i have included after the mail is sent
}
else{//method for checking the email inputs
Toast.makeText(getApplicationContext(), "Your emails don't match please try again.",
Toast.LENGTH_LONG).show();
}
}
});
}
These are the messages i get in the run dialog after I've pressed the send button:
I/SendMailActivity: Send Button Clicked.I/SendMailActivity: To List: [c2grecieve#gmail.com]
I/SendMailTask: Setting up your email ..
I/Gmail: Mail server properties are now set.
D/EGL_emulation: eglMakeCurrent: 0xe1205120: ver 3 1 (tinfo 0xe1203320)
I/.myapplication: Background concurrent copying GC freed 24080(6MB) AllocSpace objects, 5(92KB) LOS objects, 49% free, 2MB/4MB, paused 1.019ms total 105.897ms
D/EGL_emulation: eglMakeCurrent: 0xe1205120: ver 3 1 (tinfo 0xe1203320)
W/ActivityThread: handleWindowVisibility: no activity for token android.os.BinderProxy#af22bc6
D/EGL_emulation: eglMakeCurrent: 0xe1205120: ver 3 1 (tinfo 0xe1203320)
I/chatty: uid=10085(com.example.myapplication2) RenderThread identical 5 lines
D/EGL_emulation: eglMakeCurrent: 0xe1205120: ver 3 1 (tinfo 0xe1203320)
I/GMail: toEmailc2grecieve#gmail.comD/EGL_emulation: eglMakeCurrent: 0xe1205120: ver 3 1 (tinfo 0xe1203320)
D/EGL_emulation: eglMakeCurrent: 0xe1205120: ver 3 1 (tinfo 0xe1203320)
I/Choreographer: Skipped 34 frames! The application may be doing too much work on its main thread.
D/EGL_emulation: eglMakeCurrent: 0xe1205120: ver 3 1 (tinfo 0xe1203320)
D/NetworkSecurityConfig: No Network Security Config specified, using platform default
D/EGL_emulation: eglMakeCurrent: 0xe1205120: ver 3 1 (tinfo 0xe1203320)
D/EGL_emulation: eglMakeCurrent: 0xe1205120: ver 3 1 (tinfo 0xe1203320)
D/EGL_emulation: eglMakeCurrent: 0xe1205120: ver 3 1 (tinfo 0xe1203320)
D/EGL_emulation: eglMakeCurrent: 0xe1205120: ver 3 1 (tinfo 0xe1203320)
D/EGL_emulation: eglMakeCurrent: 0xe1205120: ver 3 1 (tinfo 0xe1203320)
D/EGL_emulation: eglMakeCurrent: 0xe1205120: ver 3 1 (tinfo 0xe1203320)
I/Gmail: allrecipients: [Ljavax.mail.internet.InternetAddress;#80121b1
I/Gmail: Your Email has successfully been sent.I/SendMailTask: Information sent.
I finally figured out what I was missing. in the GMail.java file i was missing 1 line of code to get the email to actually send. `transport.sendMessage(emailMessage, emailMessage.getAllRecipients());
That was the line i was missing. `

TextToSpeech android API 22 not playing audio

I am using text to speech engine in my App. It works fine on emulator Nexus 6 with API 23 and higher. But on emulator Nexus 6 with API 22 it does not speak.
Both emulators use Pico TTS as preferred engine.
My activity layout contains only one button "Speak".
This is my activity code:
public class MainActivity extends AppCompatActivity {
private TextToSpeech mTTS;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button speakBtn = findViewById(R.id.button);
speakBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
speak();
}
});
mTTS = new TextToSpeech(this, new TextToSpeech.OnInitListener() {
#Override
public void onInit(int status) {
if (status == TextToSpeech.SUCCESS) {
int result = mTTS.setLanguage(Locale.US);
if (result == TextToSpeech.LANG_MISSING_DATA
|| result == TextToSpeech.LANG_NOT_SUPPORTED) {
Log.e("TTS", "Language not supported");
}
mTTS.setOnUtteranceProgressListener(new UtteranceProgressListener() {
#Override
public void onStart(String utteranceId) {
Log.d("TTS", "onStart called, utteranceId = " + utteranceId);
}
#Override
public void onDone(String utteranceId) {
Log.d("TTS", "onDone called, utteranceId = " + utteranceId);
}
#Override
public void onError(String utteranceId) {
Log.d("TTS", "onError called, utteranceId = " + utteranceId);
}
});
} else {
Log.e("TTS", "Initialization failed");
}
}
});
}
private void speak() {
Log.d("TTS", "speak() method called");
HashMap<String, String> map = new HashMap<>();
map.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, "greeting");
mTTS.speak("hello", TextToSpeech.QUEUE_FLUSH, map);
}
}
This is all logs from emulator Nexus 6 API 22:
02-18 13:54:09.942 9739-9739/? E/libprocessgroup: failed to make and chown /acct/uid_10059: Read-only file system
02-18 13:54:09.943 9739-9739/? W/Zygote: createProcessGroup failed, kernel missing CONFIG_CGROUP_CPUACCT?
02-18 13:54:09.943 9739-9739/? I/art: Not late-enabling -Xcheck:jni (already on)
02-18 13:54:09.961 9739-9748/? E/art: Failed sending reply to debugger: Broken pipe
02-18 13:54:09.961 9739-9748/? I/art: Debugger is no longer active
02-18 13:54:09.992 9739-9739/? W/art: Before Android 4.1, method android.graphics.PorterDuffColorFilter android.support.graphics.drawable.VectorDrawableCompat.updateTintFilter(android.graphics.PorterDuffColorFilter, android.content.res.ColorStateList, android.graphics.PorterDuff$Mode) would have incorrectly overridden the package-private method in android.graphics.drawable.Drawable
02-18 13:54:10.001 9739-9739/? I/art: Rejecting re-init on previously-failed class java.lang.Class
02-18 13:54:10.001 9739-9739/? I/art: Rejecting re-init on previously-failed class java.lang.Class
02-18 13:54:10.064 9739-9739/? I/TextToSpeech: Sucessfully bound to com.svox.pico
02-18 13:54:10.072 9739-9757/? D/OpenGLRenderer: Use EGL_SWAP_BEHAVIOR_PRESERVED: true
02-18 13:54:10.074 9739-9739/? D/Atlas: Validating map...
02-18 13:54:10.093 9739-9739/? I/TextToSpeech: Connected to ComponentInfo{com.svox.pico/com.svox.pico.PicoService}
02-18 13:54:10.096 9739-9758/? I/TextToSpeech: Set up connection to ComponentInfo{com.svox.pico/com.svox.pico.PicoService}
02-18 13:54:10.111 9739-9757/? I/OpenGLRenderer: Initialized EGL, version 1.4
02-18 13:54:10.111 9739-9757/? W/OpenGLRenderer: Failed to choose config with EGL_SWAP_BEHAVIOR_PRESERVED, retrying without...
02-18 13:54:10.128 9739-9757/? D/EGL_emulation: eglCreateContext: 0xae434e20: maj 2 min 0 rcv 2
02-18 13:54:10.131 9739-9757/? D/EGL_emulation: eglMakeCurrent: 0xae434e20: ver 2 0
02-18 13:54:10.134 9739-9757/? D/OpenGLRenderer: Enabling debug mode 0
02-18 13:54:10.174 9739-9757/? D/EGL_emulation: eglMakeCurrent: 0xae434e20: ver 2 0
02-19 09:32:25.570 9739-9739/com.example.ttsapp D/TTS: speak() method called
Figured out how to solve the problem. Everything works if launch the emulator not via Debugging or Execution but from AVD Manager after starting Android Studio.

Android Volley cannot return String

I have creted a class through which i want to get a list url's from the database. But I get this error:
03-30 15:05:35.599 3591-3591/? E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.imran.myapp, PID: 3591
java.lang.NullPointerException: Attempt to read from null array
at com.example.imran.myapp.gridgallery.onCreateView(gridgallery.java:55)
at android.support.v4.app.Fragment.performCreateView(Fragment.java:1962)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1026)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1207)
at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:738)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1572)
at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:493)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:6145)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1399)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1194)
03-30 15:05:35.599 1032-1045/? V/ApplicationPolicy: isApplicationStateBlocked userId 0 pkgname com.example.imran.myapp
03-30 15:05:35.599 1032-1045/? W/ActivityManager: Force finishing activity com.example.imran.myapp/.Home
03-30 15:05:35.609 1032-1045/? V/ApplicationPolicy: isApplicationStateBlocked userId 0 pkgname com.example.imran.myapp
03-30 15:05:35.909 1032-1032/? D/CrashAnrDetector: processName: com.example.imran.myapp
03-30 15:05:35.919 1032-1032/? D/CrashAnrDetector: broadcastEvent : com.example.imran.myapp data_app_crash
03-30 15:05:36.159 1032-1059/? W/ActivityManager: Activity pause timeout for ActivityRecord{3f2af340 u0 com.example.imran.myapp/.Home t3125 f}
03-30 15:05:37.019 1032-1521/? I/WindowState: WIN DEATH: Window{224e112b u0 com.example.imran.myapp/com.example.imran.myapp.Home}
03-30 15:05:37.079 1032-1528/? I/ActivityManager: Process com.example.imran.myapp (pid 3591)(adj 9) has died(67,606)
03-30 15:05:37.359 10199-10199/? D/AASAservice-UpdateReceiver: AASAUpdateReceiver: android.intent.action.PACKAGE_REPLACED, package = com.example.imran.myapp, uid = -1
03-30 15:05:37.379 2433-3619/? D/PkgBroadcastIntentOp: Received broadcast action=android.intent.action.PACKAGE_REPLACED and uri=com.example.imran.myapp
03-30 15:05:37.559 2433-3974/? D/k: Processing package: com.example.imran.myapp
03-30 15:05:37.559 2227-3976/? D/Compatibility: intentservice saw: Intent { act=android.intent.action.PACKAGE_REPLACED dat=package:com.example.imran.myapp flg=0x4000010 cmp=com.sec.android.app.soundalive/.compatibility.Compatibility$Receiver (has extras) } Bundle[{android.intent.extra.UID=10252, android.intent.extra.REPLACING=true, android.intent.extra.user_handle=0}]
03-30 15:05:37.589 2433-3974/? D/GassUtils: Found app info for package com.example.imran.myapp:1. Hash: 6b9333e031907d7a6a6c12cd9fdfa0d23bd13ee0f40c9617ddd005dc358321b0
03-30 15:05:37.589 2433-3974/? D/k: Found info for package com.example.imran.myapp in db.
This is the activity in which i am using the class:
gridgallery.java
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_gridgallery, null);
Myserver myserver = new Myserver();
//postStringRequest(myserver.url + "/api/albums/getalbums.php", view);
AlbumsList albumsList = new AlbumsList(myserver.url+"/api/albums/getalbums.php",getContext(),view);
albumsList.connection(); // Do connection
Toast.makeText(getContext(),albumsList.imgsurls[1],Toast.LENGTH_LONG).show();
/*
GridView gv = (GridView)view.findViewById(R.id.fragment_gridgallery);
ImageAdapter myadapter = new ImageAdapter(getContext(),albumsList.imgurls());
gv.setAdapter(myadapter);
*/
return view;
}
AlbumsList.java
public class AlbumsList {
private String server;
Context mycontext;
public String[] imgsurls;
private View view;
AlbumsList(String serverurl, Context c,View uview){
mycontext = c;
server = serverurl;
view = uview;
}
public View connection(){
// Instantiate the RequestQueue.
RequestQueue queue = Volley.newRequestQueue(mycontext);
// Request a string response from the provided URL.
StringRequest stringRequest = new StringRequest(Request.Method.POST, server,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
//GridView gv = (GridView)view.findViewById(R.id.fragment_gridgallery);
final ArrayList<String> urls2 = new ArrayList<String>();
try {
JSONArray jsonObj = new JSONArray(response);
Myserver myserver = new Myserver();
for (int i=0;i<jsonObj.length();i++){
JSONObject c = jsonObj.getJSONObject(i);
String imgurl = myserver.url+"/images/thumbs/tn_"+c.getString("album_thumbnail");
urls2.add(imgurl);
}
final String myabc[] = urls2.toArray(new String[urls2.size()]); //Do not remove this
imgsurls = myabc;
Toast.makeText(mycontext, imgsurls[0], Toast.LENGTH_LONG).show(); //Interestingly this toast works and imgsurls[] is ok
} catch (JSONException e) {
e.printStackTrace();
Toast.makeText(mycontext,e.getLocalizedMessage(),Toast.LENGTH_LONG).show();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(mycontext, "Unable to reach server", Toast.LENGTH_LONG).show();
}
}) {
#Override
protected Map<String, String> getParams() {
Map<String, String> params = new HashMap<String, String>();
params.put("getalbum", "getalbum");
return params;
}
};
queue.add(stringRequest);
return view;
}
public String[] imgurls(){
return imgsurls;
}
}
In AlbumsList.java, I want to return the list of URLS by either a function or variables, but both approachs don't work. Interestingly the url's are fetched proper from database. And that Toast inside AlbumsList.java: Toast.makeText(mycontext, imgsurls[0], Toast.LENGTH_LONG).show(); also works. Then I don't know why the imgsurls is not returned to main function. Thanks in advance.
Because Volley request is asynchronous.
Thus when are you calling albumsList.connection();, the request is running in background and before it is completed, control comes to the following line:
Toast.makeText(getContext(),albumsList.imgsurls[1],Toast.LENGTH_LONG).show();
And by that time, your request is not completed.
Volley works in an asynchronous fashion. This means that it doesn't return the result of the operation immediately. You are trying to access the results before they are fetched from the server.
You should move your view initialisation logic to the onResponse(), when the result is actually being delivered.

Error in OnClick Script

myOnClickListener = new MyOnClickListener(this);
nRecyclerView = (RecyclerView) findViewById(R.id.my_recycler2_view);
nRecyclerView.setHasFixedSize(true);
static class MyOnClickListener implements View.OnClickListener{
private final Context context;
private MyOnClickListener(Context context) {
this.context = context;
}
public void onClick(View v) {
checkWhich(v);
}
private static void checkWhich (View v){
int selectedItemPosition = nRecyclerView.getChildPosition(v);
RecyclerView.ViewHolder nViewHolder = nRecyclerView.findViewHolderForPosition (selectedItemPosition);
TextView textViewName = (TextView) nViewHolder.itemView.findViewById(R.id.textViewCountry);
String selectedName = (String) textViewName.getText();
for (int i = 0; i < MyData.countryArray.length; i++){
if (selectedName==MyData.countryArray[i]) {
System.out.println(selectedName);
}
}
}
}
This has worked before, but isnt working now. Did I do anything wrong? I have 2 RecyclerViews but they are not visible together. This click listener is for one RecyclerView only.
LogCat
01-31 18:41:17.514 3441-3441/com.wc.gap.worldcupfixture I/art﹕ Late-enabling -Xcheck:jni
01-31 18:41:17.761 3441-3471/com.wc.gap.worldcupfixture D/OpenGLRenderer﹕ Render dirty regions requested: true
01-31 18:41:17.767 3441-3441/com.wc.gap.worldcupfixture D/Atlas﹕ Validating map...
01-31 18:41:17.792 3441-3471/com.wc.gap.worldcupfixture I/Adreno-EGL﹕ <qeglDrvAPI_eglInitialize:410>: QUALCOMM Build: 10/24/14, 167c270, I68fa98814b
01-31 18:41:17.793 3441-3471/com.wc.gap.worldcupfixture I/OpenGLRenderer﹕ Initialized EGL, version 1.4
01-31 18:41:17.805 3441-3471/com.wc.gap.worldcupfixture D/OpenGLRenderer﹕ Enabling debug mode 0
01-31 18:41:57.529 3441-3470/com.wc.gap.worldcupfixture I/System.out﹕ 544, 543, 646, 797, 64, 66, 987
01-31 18:43:25.218 4242-4271/com.wc.gap.worldcupfixture D/OpenGLRenderer﹕ Render dirty regions requested: true
01-31 18:43:25.224 4242-4242/com.wc.gap.worldcupfixture D/Atlas﹕ Validating map...
01-31 18:43:25.257 4242-4271/com.wc.gap.worldcupfixture I/Adreno-EGL﹕ <qeglDrvAPI_eglInitialize:410>: QUALCOMM Build: 10/24/14, 167c270, I68fa98814b
01-31 18:43:25.258 4242-4271/com.wc.gap.worldcupfixture I/OpenGLRenderer﹕ Initialized EGL, version 1.4
01-31 18:43:25.270 4242-4271/com.wc.gap.worldcupfixture D/OpenGLRenderer﹕ Enabling debug mode 0
When implementing View.OnClickListener, do it like below.
public class YourClass extends Activity implements View.OnClickListener
#Override
protected void onCreate(Bundle savedInstanceState) {
//Component setup here.
nRecyclerView = (RecyclerView) findViewById(R.id.my_recycler2_view);
nRecyclerView.setHasFixedSize(true);
nRecyclerView.setOnClickListener(this);
}
#Override
public void onClick(View v) {
checkWhich(v);
}
private static void checkWhich (View v){
int selectedItemPosition = nRecyclerView.getChildPosition(v);
RecyclerView.ViewHolder nViewHolder = nRecyclerView.findViewHolderForPosition (selectedItemPosition);
TextView textViewName = (TextView) nViewHolder.itemView.findViewById(R.id.textViewCountry);
String selectedName = textViewName.getText().toString();
for (int i = 0; i < MyData.countryArray.length; i++){
if (selectedName==MyData.countryArray[i]) {
System.out.println(selectedName);
}
}
}
}

Android: App crashes at getting text form editText in dialog

everytime i press the positive button of the dialog my app crashes with an nullpointerexception but i have no idea what i have to change. i think the problem is caused by the part with getText() because it works when i delete it here:
class newLessonDialog extends DialogFragment {
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
// Get the layout inflater
LayoutInflater inflater = getActivity().getLayoutInflater();
// Inflate and set the layout for the dialog
// Pass null as the parent view because its going in the dialog layout
builder.setView(inflater.inflate(R.layout.new_lesson_dialog, null))
// Add action buttons,
.setPositiveButton("Speichern", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id)
{
EditText eF = (EditText)getView().findViewById(R.id.editFach);
fach = eF.getText().toString();
EditText eR = (EditText)getView().findViewById(R.id.editRaum);
raum = eR.getText().toString();
EditText eL = (EditText)getView().findViewById(R.id.editLehrer);
lehrer = eL.getText().toString();
save(fach, raum, lehrer, index);
}
})
.setNegativeButton("Abbrechen", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
newLessonDialog.this.getDialog().cancel();
}
});
return builder.create();
}
}
and
public static void save(String fach, String raum, String lehrer, int index)
{
BufferedWriter out = null;
try
{
out = new BufferedWriter(new FileWriter("/sdcard/" + index + "fach.txt"));
out.write(fach);
out = new BufferedWriter(new FileWriter("/sdcard/" + index + "raum.txt"));
out.write(raum);
out = new BufferedWriter(new FileWriter("/sdcard/" + index + "lehrer.txt"));
out.write(lehrer);
out.close();
}
catch (Exception e)
{
Toast.makeText(getAppContext(), "Fehler beim Speichern!", Toast.LENGTH_SHORT);
}
}
logcat:
08-13 19:14:07.609 23114-23114/de.nathan.android.droidschool W/dalvikvm: threadid=1: thread exiting with uncaught exception (group=0x41760700)
08-13 19:14:07.619 23114-23114/de.nathan.android.droidschool E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.NullPointerException
at de.nathan.android.droidschool.MainActivity$fragmentTab1$1$1newLessonDialog$2.onClick(MainActivity.java:267)
at com.android.internal.app.AlertController$ButtonHandler.handleMessage(AlertController.java:166)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5103)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
08-13 19:14:07.639 438-6851/? W/ActivityManager: Process de.nathan.android.droidschool has crashed too many times: killing!
08-13 19:14:07.639 438-6851/? W/ActivityManager: Force finishing activity de.nathan.android.droidschool/.MainActivity
08-13 19:14:07.659 438-6851/? I/ActivityManager: Killing proc 23114:de.nathan.android.droidschool/u0a10018: crash
08-13 19:14:07.679 438-551/? W/InputDispatcher: channel '428f0a50 de.nathan.android.droidschool/de.nathan.android.droidschool.MainActivity (server)' ~ Consumer closed input channel or an error occurred. events=0x9
08-13 19:14:07.679 438-551/? E/InputDispatcher: channel '428f0a50 de.nathan.android.droidschool/de.nathan.android.droidschool.MainActivity (server)' ~ Channel is unrecoverably broken and will be disposed!
08-13 19:14:07.679 438-551/? W/InputDispatcher: channel '41f4abe8 de.nathan.android.droidschool/de.nathan.android.droidschool.MainActivity (server)' ~ Consumer closed input channel or an error occurred. events=0x9
08-13 19:14:07.679 438-551/? E/InputDispatcher: channel '41f4abe8 de.nathan.android.droidschool/de.nathan.android.droidschool.MainActivity (server)' ~ Channel is unrecoverably broken and will be disposed!
08-13 19:14:07.679 438-448/? W/InputDispatcher: Attempted to unregister already unregistered input channel '41f4abe8 de.nathan.android.droidschool/de.nathan.android.droidschool.MainActivity (server)'
08-13 19:14:07.679 438-449/? W/InputDispatcher: Attempted to unregister already unregistered input channel '428f0a50 de.nathan.android.droidschool/de.nathan.android.droidschool.MainActivity (server)'
08-13 19:14:07.679 438-448/? I/WindowState: WIN DEATH: Window{41f4abe8 u0 de.nathan.android.droidschool/de.nathan.android.droidschool.MainActivity}
08-13 19:14:07.679 438-449/? I/WindowState: WIN DEATH: Window{428f0a50 u0 de.nathan.android.droidschool/de.nathan.android.droidschool.MainActivity}
Try replacing your getView()s with getDialog().
EditText eF = (EditText)getDialog().findViewById(R.id.editFach);
fach = eF.getText().toString();
EditText eR = (EditText)getDialog().findViewById(R.id.editRaum);
raum = eR.getText().toString();
EditText eL = (EditText)getDialog().findViewById(R.id.editLehrer);
lehrer = eL.getText().toString();
You may as well keep a reference to the original view; it'll make things a lot easier. Try:
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
LayoutInflater inflater = getActivity().getLayoutInflater();
final View view = inflater.inflate(R.layout.new_lesson_dialog, null);
builder.setView(view)
.setPositiveButton("Speichern", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
EditText eF = (EditText)view.findViewById(R.id.editFach);
...etc.

Categories