import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.VolleyLog;
import com.android.volley.toolbox.JsonObjectRequest;
import net.simonvt.menudrawer.MenuDrawer;
import net.simonvt.menudrawer.Position;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.reflect.Method;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import adapter.MyRecyclerAdapter;
import app.AppController;
import data.FeedItem;
public class CategoryMain extends Activity {
private static final String URL_FEED = "http://lorempixel.com/800/400/nightlife/";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.category_main);
RecyclerView recyclerView = (RecyclerView) findViewById(R.id.list);
recyclerView.setHasFixedSize(true);
final CatRecyclerAdapter adapter;
recyclerView.setAdapter(adapter = new CatRecyclerAdapter(createMockList(), R.layout.item));
recyclerView.setLayoutManager(new LinearLayoutManager(this));
recyclerView.setItemAnimator(new DefaultItemAnimator());
adapter.setOnItemClickListener(new OnRecyclerViewItemClickListener<ViewModel>() {
#Override
public void onItemClick(View view, ViewModel viewModel) {
adapter.remove(viewModel);
}
});
}
//
private List<ViewModel> createMockList() {
List<ViewModel> items = new ArrayList<ViewModel>();
for (int i = 0; i < 20; i++) {
items.add(new ViewModel(i, "Item " + (i + 1), URL_FEED + (i % 10 + 1), i + ""));
}
return items;
}
}
I don't know how to import JSON Data to Arraylist. How can I import JSON Array in createMockList() ? Someone help me! I'm beginner. Sorry for my poor english. Thanks You!
I want to know how to replace with JSON Array?
Related
I want to create application which will write text while listening. I have tried this code but this is not working. and i have followed this link. but it couldn't work for me.
If i speak, it is not displaying spoken words and speech recognition is also not working. if you know the solution Please guide me to solve this problem. Thank you...
package com.kp.notesapp;
import static android.Manifest.permission.READ_EXTERNAL_STORAGE;
import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;
import android.Manifest;
import android.annotation.SuppressLint;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Typeface;
import android.graphics.fonts.Font;
import android.graphics.pdf.PdfDocument;
import android.graphics.pdf.PdfRenderer;
import android.os.Bundle;
import android.os.Environment;
import android.print.PageRange;
import android.provider.DocumentsContract;
import android.speech.RecognitionListener;
import android.speech.RecognizerIntent;
import android.speech.SpeechRecognizer;
import android.text.Html;
import android.text.style.ParagraphStyle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.compose.ui.text.Paragraph;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import com.google.android.material.internal.ViewUtils;
import com.kp.notesapp.Models.Notes;
import org.w3c.dom.Document;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Locale;
public class NoteView extends AppCompatActivity {
EditText contentEditText;
ImageView micImg;
SpeechRecognizer speechRecognizer;
int count = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_note_view);
getSupportActionBar().hide();
contentEditText = findViewById(R.id.contentNotes);
micImg = findViewById(R.id.micImg);
speechRecognizer = SpeechRecognizer.createSpeechRecognizer(this);
Intent speechIntent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
speechIntent.putExtra(RecognizerIntent.EXTRA_PARTIAL_RESULTS, true);
speechIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
speechIntent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE,"voice.recognition.test");
speechIntent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS,5);
micImg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(count==0){
micImg.setImageResource(R.drawable.micvoice);
speechRecognizer.startListening(speechIntent);
count=1;
}
else{
micImg.setImageResource(R.drawable.mic);
speechRecognizer.stopListening();
count=0;
}
}
});
speechRecognizer.setRecognitionListener(new RecognitionListener() {
#Override
public void onReadyForSpeech(Bundle bundle) {
}
#Override
public void onBeginningOfSpeech() {
}
#Override
public void onRmsChanged(float v) {
}
#Override
public void onBufferReceived(byte[] bytes) {
}
#Override
public void onEndOfSpeech() {
}
#Override
public void onError(int i) {
}
#Override
public void onResults(Bundle bundle) {
/*ArrayList<String> data = bundle.getStringArrayList(speechRecognizer.RESULTS_RECOGNITION);
contentEditText.setText(data.get(0));
Log.e("csData", String.valueOf(data));*/
String str = new String();
Log.e( "csonResults " , String.valueOf(bundle));
ArrayList data = bundle.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);
for (int i = 0; i < data.size(); i++)
{
Log.e("csresult", String.valueOf(data.get(i)));
str += data.get(i);
}
}
#Override
public void onPartialResults(Bundle bundle) {
ArrayList data = bundle.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);
String word = (String) data.get(data.size() - 1);
contentEditText.setText(word);
Log.e("csWord", word);
}
#Override
public void onEvent(int i, Bundle bundle) {
}
});
}
#Override
public void onBackPressed() {
super.onBackPressed();
saveData();
finish();
}
}
How Can I return Top completed value in ok http to use appear it in recycle view
note when I use log.d to check its value in ok http method it is not null but when I try to appear it in out the method the value of it is null so how can I solve this problem and how can I return Array in avoid
note I work in fragment
package com.example.animekingdom.ui.gallery;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.example.animekingdom.MyAdapter;
import com.example.animekingdom.R;
import com.example.animekingdom.ui.Anime;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;
import org.jetbrains.annotations.NotNull;
import org.json.JSONArray;
import java.io.IOException;
import java.util.ArrayList;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
public class GalleryFragment extends Fragment {
private RecyclerView recyclerView;
private RecyclerView.Adapter TopCompleted;
private GalleryViewModel galleryViewModel;
private RecyclerView.LayoutManager layoutManager;
private ArrayList<Anime> Topcompleted = new ArrayList<>();
private ArrayList<Anime>ss=new ArrayList<>();
public View onCreateView(#NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState) {
View root = inflater.inflate(R.layout.fragment_gallery, container, false);
int i=1;
final String url = "https://api.jikan.moe/v3/top/anime/"+i+"/airing";
OkHttpClient okHttpClient=new OkHttpClient();
final Request request = new Request.Builder()
.url(url)
.build();
okHttpClient.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(#NotNull Call call, #NotNull IOException e) {
}
#Override
public void onResponse(#NotNull Call call, #NotNull Response response) throws IOException {
JsonArray features=((JsonObject) JsonParser.parseString(response.body().string())).getAsJsonArray("top");
Log.d("TRYYY", String.valueOf(features.size()));
for (int i=0;features.size()>i;i++){
JsonObject New=(JsonObject) features.get(i);
String a=new Gson().toJson(New);
Topcompleted.add(new Gson().fromJson(New,Anime.class));
}
}
});
Log.d("Tag" ,new Gson().toJson(Topcompleted.size()));
recyclerView = root.findViewById(R.id.TopCompletedAnime);
recyclerView.setHasFixedSize(true);
layoutManager = new LinearLayoutManager(getActivity());
recyclerView.setLayoutManager(new GridLayoutManager(getActivity(),3));
TopCompleted = new MyAdapter(Topcompleted, GalleryFragment.this);
recyclerView.setAdapter(TopCompleted);
return root;
}
}
How do I get the json result from onPostExecute to another activity? I was able to get the user details from the database based on the username logged in. So in my HomePageActivity there is a button to go to profile and when I clicked on btnprofile it displays the user details on textviews in the current activity(HomePageActivity) but what I wanted to do is to get the user details and then display it to a new activity, which is in the Profile Activity. I tried using Intent but when I go to Profile Activity it displays nothing. Can you please help me? :(
Here is my HomePageActivity:
package com.example.androidmp;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
import android.content.*;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONObject;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.view.Menu;
import android.view.View;
import android.widget.*;
import com.example.androidmp.User;
import java.util.ArrayList;
import java.util.List;
import com.example.androidmp.User;
import com.example.androidmp.Poem;
import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.widget.ListView;
public class HomePageActivity extends Activity {
Button btnfeed, btnprofile;
User u = new User();
String Username,Password,Fullname,Email,Location,Bio,uname;
String getusername,getpw,getfn,getem,getloc,getb;
JSONObject jsonobject;
JSONArray jsonarray;
ListView listview;
ListViewAdapter adapter;
ProgressDialog mProgressDialog;
ArrayList<HashMap<String, String>> arraylist;
HashMap<String, String> hashMap = new HashMap<String, String>();
Intent i;
Bundle bundle;
private static final String USERNAME = "Username";
private static final String PASSWORD = "Password";
private static final String FULLNAME = "Fullname";
private static final String EMAIL = "Email";
private static final String BIO = "Bio";
private static final String LOCATION = "Location";
String s="";
TextView fn,em,loc,b;
private static final String TAG_PROFILE = "user";
private static final String PROFILE_URL = "http://192.168.1.5/webservices/mycontroller/getUser.php";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_homepage);
Intent intent = getIntent();
u.SetUsername(intent.getStringExtra(u.username()));
fn = (TextView) findViewById(R.id.textView1);
em = (TextView) findViewById(R.id.textView2);
loc = (TextView) findViewById(R.id.textView3);
b = (TextView) findViewById(R.id.textView4);
TextView textView = (TextView) findViewById(R.id.getusername);
textView.setText(u.getUsername());
uname = u.getUsername().toString();
//uname = textView.toString();
//u.SetUsername(uname.toString());
btnprofile = (Button) findViewById(R.id.btnprofile);
btnfeed = (Button) findViewById(R.id.btnfeed);
//getem = em.getText().toString();
//getloc = loc.getText().toString();
//getb = b.getText().toString();
btnprofile.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
new ProfileAsync().execute();
Intent i = new Intent(HomePageActivity.this,ProfileActivity.class);
i.putExtra("fullname",Fullname);
i.putExtra("email", Email);
i.putExtra("bio", Bio);
i.putExtra("location", Location);
startActivity(i);
finish();
}
});
btnfeed.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent a = new Intent(HomePageActivity.this,FeedActivity.class);
startActivity(a);
}
});
}
class ProfileAsync extends AsyncTask<String, String, String>{
private Dialog loadingDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
loadingDialog = ProgressDialog.show(HomePageActivity.this, "Please wait", "Loading...");
}
#Override
protected String doInBackground(String... params) {
String json=null;
byte[] data;
StringBuffer buffer = null;
InputStream is = null;
try{
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("Username", uname));
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(PROFILE_URL);
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpClient.execute(httpPost);
HttpEntity entity = response.getEntity();
json = EntityUtils.toString(entity);
Log.e("Profile JSON: ", json.toString());
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return json;
}
#Override
protected void onPostExecute(String json){
super.onPostExecute(json);
loadingDialog.dismiss();
try
{
jsonobject = new JSONObject(json);
jsonarray = jsonobject.getJSONArray("user");
JSONObject jb= jsonarray.getJSONObject(0);
//Username = jb.getString("Username");
//Password = jb.getString("Password");
Fullname = jb.getString("Fullname");
Email = jb.getString("Email");
Bio = jb.getString("Bio");
Location = jb.getString("Location");
fn.setText(Fullname);
em.setText(Email);
loc.setText(Location);
b.setText(Bio);
}catch(Exception e)
{
e.printStackTrace();
}
}
}//end of asynctask
}
Here is my ProfileActivity:
package com.example.androidmp;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
import android.content.*;
import com.example.androidmp.User;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.view.Menu;
import android.view.View;
import android.widget.*;
public class ProfileActivity extends Activity {
Button btncreate;
private TextView _username,_password,_fullname,_Email,_bio,_location;
User u = new User();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.profileview);
//_username = (TextView) findViewById(R.id._username);
//_password = (TextView) findViewById(R.id._password);
_fullname = (TextView) findViewById(R.id._fullname);
_Email = (TextView) findViewById(R.id._Email);
_bio = (TextView) findViewById(R.id._bio);
_location = (TextView) findViewById(R.id._location);
Intent i = getIntent();
u.SetUsername(i.getStringExtra(u.username()));
_username.setText(u.getUsername());
String displayfullname = i.getExtras().getString("fullname");
String displayemail = i.getExtras().getString("email");
String displaybio = i.getExtras().getString("bio");
String displaylocation = i.getExtras().getString("location");
_fullname.setText(displayfullname);
_Email.setText(displayemail);
_bio.setText(displaybio);
_location.setText(displaylocation);
}
}
It is because new activity starts before async task is completed. Just call function for start new activity in onPostExecute() function.
Pass values after fetching the details. Is the settext working properly? then you can give the intent at that scope, in the onPostexecute method. Look before doing this.Look this
First I will describe the process/problem briefly in words. Afterwards, I'll attach all of the code.
I start the android application in debug mode.
Main activity gets called.
It calls Activity2 via "intent".
Then (in onCreate) I start an Async activity in order to get information from a webserver. I do that with this command "new Kontakt(info1, info2, information).execute();"
I've put a break point at the onPostExecute method in "Kontakt" to see what happens. But!! It doesn't stop there. So then I figured, "okey, the doInBackground method didn't get called for some reason"
When I continue to run the code, as a surprise, onPostExecute gets called (somewhere at the end of onClick) and stops at the break point just the way I want it but than it's too late, because I'd like to have the output already in the onCreate method where I called "new Kontakt(info1, info2, information).execute();".
So why does it call onPostExecute too late and what can I do to make the process call it properly already in onCreate at the line "new Kontakt(info1, info2, information).execute();" in Activity2?
The code is below
MainActivity.java
package com.example.myapplication;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.graphics.PorterDuff;
import android.graphics.drawable.Drawable;
import android.preference.PreferenceManager;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends ActionBarActivity implements View.OnClickListener {
Button button1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button1 = (Button) findViewById(R.id.button1);
button1.setOnClickListener(this);
}
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.button1:
Intent intent = new Intent(this, Activity2.class);
startActivity(intent);
break;
}
}
}
Activity2.java
package com.example.myapplication;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.preference.PreferenceManager;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.text.InputType;
import android.text.TextUtils;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import java.io.IOException;
import java.net.MalformedURLException;
import java.util.ArrayList;
public class Activty2 extends ActionBarActivity implements View.OnClickListener {
Button button;
Context information;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity2);
information=this;
String info1="Yeah";
String info2="Yeah";
new Kontakt(info1, info2, information).execute();
button = (Button) findViewById(R.id.button);
button.setOnClickListener(this);
}
#Override
public void onClick(View view) {
if (view.getId() == R.id.button) {
}
}
Kontakt.java
package com.example.myapplication;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.util.Log;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.json.JSONObject;
import java.util.ArrayList;
public class Kontakt extends AsyncTask<Void, Void, Integer> {
public static final int CONNECTION_TIMEOUT = 1000 * 15;
public static final String SERVER_ADDRESS = "http://test.site.net/";
String info1;
String info2;
private final Context information;
public Kontakt(String info1, String info2, Context context) {
this.info1=info1;
this.Info2=info2;
this.information=context;
}
#Override
protected Integer doInBackground(Void... params) {
ArrayList<NameValuePair> dataToSend = new ArrayList<>();
dataToSend.add(new BasicNameValuePair("user", info1));
dataToSend.add(new BasicNameValuePair("password", info2));
HttpParams httpRequestParams = getHttpRequestParams();
HttpClient client = new DefaultHttpClient(httpRequestParams);
HttpPost post = new HttpPost(SERVER_ADDRESS
+ "Register.php");
try {
post.setEntity(new UrlEncodedFormEntity(dataToSend));
client.execute(post);
int result=1;
return result;
} catch (Exception e) {
e.printStackTrace();
int result=0;
return result;
}
//return null;
}
private HttpParams getHttpRequestParams() {
HttpParams httpRequestParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpRequestParams,
CONNECTION_TIMEOUT);
HttpConnectionParams.setSoTimeout(httpRequestParams,
CONNECTION_TIMEOUT);
return httpRequestParams;
}
#Override
protected void onPostExecute(Integer result)
{
super.onPostExecute(result);
SharedPreferences.Editor editor = information.getSharedPreferences("INTERNET_KOLL", Context.MODE_PRIVATE).edit();
editor.putString("internet_status", String.valueOf(result));
editor.commit();
}
}
In Activity2, when onCreate() calls new Kontakt(info1, info2, information).execute();:
an asynchronous task (Kontakt) is started in the background
the execution of onCreate() continues
so it's normal that you don't have the response immediately.
The Android does not talk despite my code being error free and accurate. I have used a toast function to see where the issue occurs. However, both toasts are called.
I have removed all irrelevant code.
The code below is mostly relevant.
package com.example.android.BluetoothChat;
import android.R.string;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.speech.tts.TextToSpeech;
import android.speech.tts.TextToSpeech.OnInitListener;
import android.telephony.SmsManager;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.Locale;
import java.util.Set;
import android.bluetooth.BluetoothDevice;
import java.io.InputStream;
import java.io.OutputStream;
import android.bluetooth.BluetoothSocket;
import android.widget.EditText;
import java.io.IOException;
import java.util.UUID;
public class MainActivity extends Activity implements LocationListener{
Button start, stop;
TextView tv;
TextView tv2;
TextView sum;
LocationManager lm;
static TextToSpeech Talker;
TextView myLabel;
Handler mhandler = new Handler();
int i;
int sum1 = 0;
static BluetoothDevice mmDevice;
static BluetoothAdapter mBluetoothAdapter;
static BluetoothSocket mmSocket;
String lat;
String lon;
EditText myTextbox;
static OutputStream mmOutputStream;
static InputStream mmInputStream;
static Thread workerThread;
static byte[] readBuffer;
static int readBufferPosition;
static int counter;
static volatile boolean stopWorker;
TextToSpeech talker;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main2);
setTitle("Seizure Detection Helmet Application");
myTextbox = (EditText)this.findViewById(R.id.name);
talker = new TextToSpeech(getApplicationContext(),new TextToSpeech.OnInitListener() {
#Override
public void onInit(int status) {
if(status != TextToSpeech.ERROR)
{
talker.setLanguage(Locale.US);
}
}
});
Button talk = (Button)this.findViewById(R.id.talk);
talk.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
speakOut();
}
});
public void speakOut()
{
String toSpeak = myTextbox.getText().toString();
Toast.makeText(getApplicationContext(), toSpeak, Toast.LENGTH_SHORT).show();
String full = ("My name is"+toSpeak+ "and I am having a Seizure at 38.901 Latitude and -77.031 Longitude ");
Toast.makeText(getApplicationContext(), toSpeak, Toast.LENGTH_SHORT).show();
talker.speak(full, TextToSpeech.QUEUE_FLUSH, null);
Toast.makeText(getApplicationContext(), full, Toast.LENGTH_SHORT).show();
talker.speak("HELLO",TextToSpeech.QUEUE_FLUSH, null);
}
}
There are several problems with your code. You should check for error returned by setLanguage. You cannot call speakOut until onInit has been called. One way you can insure this is to disable the talk button in the xml layout file and enable it in onInit.