In my app, I am getting text content from JSON and that content I am showing into text view. But, problem is text is not appearing complete and it is not formatted as well. I had checked my JSON using http://jsonformatter.curiousconcept.com/ and it showed the JSON is valid. I had printed the content that I received on the log and it is complete. Even, after setting it to textview and again getting back from it, I am getting complete data. But, it is not displaying complete text.
I am not getting where the problem is. The textview is inside scrollview.
Below is my code:
Base Activity
public class TIEBaseActivity extends MapActivity
{
//private ProgressDialog dialog;
public AlertDialog _alertDialog;
protected HeaderBar _headerBar;
protected FooterBar _footerBar;
protected LinearLayout _manager;
protected LinearLayout form;
protected TIEBaseActivity _self;
public void createDefaultView(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.basescreen);
this._self=this;
initView();
}
public void loadFormFromResource(int resourceID)
{
LayoutInflater inflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(resourceID, null);
_manager.addView(view);
}
public void loadDefaultForm()
{
form=new LinearLayout(this);
form.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT));
form.setOrientation(LinearLayout.VERTICAL);
form.setGravity(Gravity.CENTER);
_manager.addView(form);
}
public void initView()
{
_headerBar = (HeaderBar) findViewById(R.id.baseHeaderBar);
_manager = (LinearLayout) findViewById(R.id.baseScrollContent);
//_footerBar = (FooterBar) findViewById(R.id.baseFooterBar);
_headerBar.view.setVisibility(View.GONE);
//_footerBar.view.setVisibility(View.GONE);
}
protected void showScreen(Intent intent) {
startActivity(intent);
}
public void setHeaderTitle(String title) {
if (_headerBar!=null) {
_headerBar.setTitle(title);
}
}
public Handler progressCloseHandler = new Handler() {
public void handleMessage(Message msg) {
super.handleMessage(msg);
if (_alertDialog != null)
_alertDialog.cancel();
}
};
private Handler alertViewHandler = new Handler() {
public void handleMessage(Message msg) {
String message=(String)msg.obj;
AlertDialog.Builder _alert = new AlertDialog.Builder(TIEBaseActivity.this);
_alert.setMessage(message)
.setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
}
});
_alert.create().show();
}
};
public void DisplayAlert(String message) {
Message msg=Message.obtain(alertViewHandler);
msg.obj=message;
alertViewHandler.sendMessage(msg);
}
public void DisplayAlert(String message, int id) {
Message msg=Message.obtain(alertViewHandler);
msg.obj=message;
msg.what=id;
alertViewHandler.sendMessage(msg);
}
private Handler closeViewHandler=new Handler() {
public void handleMessage(Message msg) {
super.handleMessage(msg);
_self.finish();
}
};
public void closeScreen() {
closeViewHandler.sendMessage(Message.obtain(closeViewHandler));
}
public void openRating()
{
Intent marketIntent = new Intent(Intent.ACTION_VIEW,Uri.parse("market://details?id=com.dzo.tie"));
startActivity(marketIntent);
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
}
public void openShare()
{
String mMailSubject = "OIE App. - Get the All Indian Events happening in Overseas";
String mMailMessage = null;
mMailMessage = "Hi,\n I found this great Application. This application customize for Overseas Indian Events.";
mMailMessage += "\n";
mMailMessage += "Go to: https://market.android.com/details?id=com.dzo.oie";
mMailMessage += ",\n Please visit: http://www.dotzoo.net to see more about Dotzoo Inc.";
Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);
emailIntent.setType("text/*");
emailIntent.putExtra(Intent.EXTRA_SUBJECT, ""+mMailSubject);
emailIntent.putExtra(Intent.EXTRA_TEXT, mMailMessage);
startActivity(Intent.createChooser(emailIntent, "Share via..."));
}
#Override
protected boolean isRouteDisplayed() {
// TODO Auto-generated method stub
return false;
}
}
Layout for BaseActivity:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:background="#color/white"
android:layout_height="fill_parent"
android:orientation="vertical"
android:id="#+id/baseLayout">
<com.dzo.tie.ui.HeaderBar
android:id="#+id/baseHeaderBar"
android:layout_width="fill_parent"
android:layout_height="50dp"/>
<ScrollView
android:scrollbars="vertical"
android:fillViewport="true"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<LinearLayout
android:id="#+id/baseScrollContent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:gravity="center"
android:layout_gravity="center"
android:layout_width="fill_parent">
</LinearLayout>
</ScrollView>
I am extending this base activity in my activity class:
My Activity
public class TIEInfo extends TIEBaseActivity
{
TextView txtTieInfo;
String contents;
private String infoUrl = "http://www.tradeineu.com/tie_app/aboutTie.php";
protected void onCreate(Bundle savedInstanceState)
{
super.createDefaultView(savedInstanceState);
_headerBar.view.setVisibility(View.VISIBLE);
super.setHeaderTitle("Info");
init();
new TIEInfoAsyncTask(getParent(), infoUrl, txtTieInfo).execute();
}//onCreate
public void init()
{
loadFormFromResource(R.layout.tieinfo);
txtTieInfo = (TextView)findViewById(R.id.txtTieInfo);
}//init
}//TIEInfo
Layout for my activity
<?xml version="1.0" encoding="utf-8"?>
<TextView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="#+id/txtTieInfo"
android:textSize="12sp"
android:textColor="#color/copper_gold"
android:lineSpacingExtra="5dp"/>
You need to scroll to see the rest of your text.
Place your textview inside a scrollView and it will be ok.
Related
Instead of getting checkbox like this(i am getting it only few times randomly when moving from on fragment to another).
I am getting like this(checkbox is still true but only tik mark is missing randomly)
I am using onSaveInstanceState and onViewStateRestored. The problem is the checkbox tik mark only disappears and comes back few times but the state of checkbox is still selected i see blue color around all the selected check boxes that selected color doesn't go away only the tik mark goes away and comes back randomly.
Layout:
<?xml version="1.0" encoding="utf-8"?>
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<CheckBox
android:id="#+id/checkBox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="16dp"
android:layout_marginTop="8dp"
android:drawableLeft="#drawable/ic_tv"
android:text="TV"
android:theme="#style/CheckBoxTheme"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"
tools:text="Tv" />
</android.support.constraint.ConstraintLayout>
</ScrollView>
My Fragment:
public class StepFragmentTwo extends Fragment implements BlockingStep {
private static final String CLICKS_KEY = "clicks";
private static final String TAG = "ADERVERTISMENT";
private int i = 0;
FragmentManager fm = getFragmentManager();
CheckBox c;
Boolean tv = false ;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(getLayoutResId(), container, false);
c = (CheckBox)v.findViewById(R.id.checkBox);
//initialize your UI
return v;
}
protected int getLayoutResId() {
return getArguments().getInt(String.valueOf(R.layout.step2));
}
#Override
public void onSaveInstanceState(Bundle outState) {
outState.putInt(CLICKS_KEY, i);
super.onSaveInstanceState(outState);
if(outState!=null) {
outState.putBoolean("c", c.isChecked());
}
}
#Override
public void onViewStateRestored(#Nullable Bundle savedInstanceState) {
super.onViewStateRestored(savedInstanceState);
if(savedInstanceState!=null) {
tv = savedInstanceState.getBoolean("c");
}
}
#Override
public void onResume() {
super.onResume();
c.setChecked(tv);
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
}
public void onNextClicked(final StepperLayout.OnNextClickedCallback callback) {
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
if (c.isChecked()) {
tv = true;
}
SharedPreferences shared = getActivity().getSharedPreferences("Mypref", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = shared.edit();
editor.putBoolean("tv", tv);
editor.apply(); // This line is IMPORTANT !!!
callback.goToNextStep();
}
}, 200L);
}
#Override
#UiThread
public void onCompleteClicked(final StepperLayout.OnCompleteClickedCallback callback) {
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
callback.complete();
}
}, 2000L);
}
public static StepFragmentTwo newInstance(#LayoutRes int layoutResId) {
Bundle args = new Bundle();
args.putInt(String.valueOf(R.layout.step2), layoutResId);
StepFragmentTwo fragment = new StepFragmentTwo();
fragment.setArguments(args);
return fragment;
}
#Override
public VerificationError verifyStep() {
//return null if the user can go to the next step, create a new VerificationError instance otherwise
return null;
}
#Override
public void onSelected() {
//update UI when selected
}
#Override
public void onError(#NonNull VerificationError error) {
//handle error inside of the fragment, e.g. show error on EditText
}
public void onBackClicked(StepperLayout.OnBackClickedCallback callback) {
//Toast.makeText(this.getContext(), "Your custom back action. Here you should cancel currently running operations", Toast.LENGTH_SHORT).show();
callback.goToPrevStep();
}
}
In short you can do,
#Override
public void onResume() {
super.onResume();
SharedPreferences shared = getActivity().getSharedPreferences("Mypref", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = shared.edit();
tv = editor.getBoolean("tv", tv);
c.setChecked(tv);
}
I am building my first android app using WiFi Direct to transfer
text, image, and media files to peers.I am using a RecyclerView
and a Fragment. I hope to show peers's list on a framelayout
(a simple textview) and then click the views to form a group
to send files. I am stuck at the first stage of making the list shown
on the parent's view. I would appreciate your help on what I did wrong.
I am just a beginner. Any advice or resources would be welcome even besides the pending problem. The followings are three classes and two xmls I've made fumbling around many sources and Android Developer's guide.
public class MainActivity extends FragmentActivity {
public static String TAG="test";
IntentFilter mIntentFilter;
WifiP2pManager.Channel mChannel;
WifiP2pManager mManager;
BroadcastReceiver mReceiver;
public static boolean setIsWifiP2pEnable;
Button open, connect, file, image, media;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
open = (Button) findViewById(R.id.wifi_open);
connect = (Button) findViewById(R.id.connect);
file = (Button) findViewById(R.id.file);
image = (Button) findViewById(R.id.gallery);
media = (Button) findViewById(R.id.media);
open.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Settings.ACTION_WIRELESS_SETTINGS);
startActivity(intent);
}
});
mIntentFilter = new IntentFilter();
mIntentFilter.addAction(WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION);
mIntentFilter.addAction(WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION);
mIntentFilter.addAction(WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION);
mIntentFilter.addAction(WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION);
mManager = (WifiP2pManager) getSystemService(Context.WIFI_P2P_SERVICE);
mChannel = mManager.initialize(this, getMainLooper(), null);
mReceiver = new WiFiDirectBroadcastReceiver(mManager, mChannel, this);
checkWiFi();
connect.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mManager.discoverPeers(mChannel, new WifiP2pManager.ActionListener() {
#Override
public void onSuccess() {
Log.d (TAG, "search start");
}
#Override
public void onFailure(int reasonCode) {
Log.d (TAG, "search failed");
}
});
}
});
FragmentManager fm = getSupportFragmentManager();
Fragment fragment = fm.findFragmentById(R.id.fragment_container);
if (fragment == null) {
fragment = new DeviceFragment();
fm.beginTransaction()
.add(R.id.fragment_container, fragment)
.commit();
Log.d (TAG, "fragment_activated");
}
}
#Override
protected void onResume () {
super.onResume();
mReceiver = new WiFiDirectBroadcastReceiver(mManager, mChannel, this);
registerReceiver(mReceiver, mIntentFilter);
}
#Override
protected void onPause () {
super.onPause();
unregisterReceiver(mReceiver);
}
public void checkWiFi(){
if(setIsWifiP2pEnable==true){
Toast.makeText(MainActivity.this, "WiFi Direct connected", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(MainActivity.this, "Open WiFi Direct in settings", Toast.LENGTH_LONG).show();
}
}
}
public class WiFiDirectBroadcastReceiver extends BroadcastReceiver {
public static WifiP2pManager mManager;
public static WifiP2pManager.Channel mChannel;
private MainActivity mActivity;
public static List<WifiP2pDevice> peers = new ArrayList<>();
public WiFiDirectBroadcastReceiver(WifiP2pManager manager, WifiP2pManager.Channel channel,
MainActivity activity) {
super();
this.mManager = manager;
this.mChannel = channel;
this.mActivity = activity;
}
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION.equals(action)) {
int state = intent.getIntExtra(mManager.EXTRA_WIFI_STATE, -1);
if (state==mManager.WIFI_P2P_STATE_ENABLED){
Log.d (MainActivity.TAG, "WiFi_enabled");
mActivity.setIsWifiP2pEnable=true;
mActivity.checkWiFi();
} else {
Log.d (MainActivity.TAG, "WiFi_failed");
mActivity.setIsWifiP2pEnable=false;
mActivity.checkWiFi();
}
} else if (WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION.equals(action)) {
if (mManager != null) mManager.requestPeers(mChannel, new WifiP2pManager.PeerListListener() {
#Override
public void onPeersAvailable(WifiP2pDeviceList peerList) {
Log.d (MainActivity.TAG, "peers_found");
peers.clear();
peers.addAll(peerList.getDeviceList());
if(peers.size() ==0){
Log.d (MainActivity.TAG, "No_Peers_found");
return;
}
}
});
} else if (WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION.equals(action)) {
// Respond to new connection or disconnections
if (mManager==null) {
return;
}
NetworkInfo networkInfo = (NetworkInfo) intent
.getParcelableExtra(WifiP2pManager.EXTRA_NETWORK_INFO);
if (networkInfo.isConnected()){
mManager.requestConnectionInfo(mChannel, new WifiP2pManager.ConnectionInfoListener() {
#Override
public void onConnectionInfoAvailable(WifiP2pInfo info) {
InetAddress groupOwnerAddress = info.groupOwnerAddress;
String s=groupOwnerAddress.getHostAddress();
if (info.groupFormed && info.isGroupOwner) {
} else if (info.groupFormed) {
}
}
});
}
} else if (WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION.equals(action)) {
}
}
}
public class DeviceFragment extends Fragment {
private RecyclerView mDeviceRecyclerView;
private DeviceAdapter mAdapter;
private List<WifiP2pDevice> mDevices;
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_device_list, container,false);
mDeviceRecyclerView = (RecyclerView) view
.findViewById(R.id.device_recycler_view);
mDeviceRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
updateUI();
return view;
}
private void updateUI(){
mDevices = WiFiDirectBroadcastReceiver.peers;
mAdapter = new DeviceAdapter(mDevices);
mDeviceRecyclerView.setAdapter(mAdapter);
Log.d (MainActivity.TAG, "adapter_connected");
}
private class DeviceHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
public TextView mTitleTextView;
public DeviceHolder(View itemView) {
super(itemView);
itemView.setOnClickListener(this);
mTitleTextView = (TextView) itemView;
Log.d(MainActivity.TAG, "Item_Click_try");
}
#Override
public void onClick(View v) {
Toast.makeText(getActivity(),"Click Succeeded", Toast.LENGTH_LONG).show();
int i = (int) v.getTag();
WifiP2pDevice device = mDevices.get(i);
WifiP2pConfig config = new WifiP2pConfig();
config.deviceAddress = device.deviceAddress;
config.wps.setup = WpsInfo.PBC;
WiFiDirectBroadcastReceiver.mManager.connect(WiFiDirectBroadcastReceiver.mChannel, config, new WifiP2pManager.ActionListener() {
#Override
public void onSuccess() {
Log.d (MainActivity.TAG, "Click_Success!!");
}
#Override
public void onFailure(int reason) {
Log.d (MainActivity.TAG, "Click_Failed!!");
}
});
}
}
private class DeviceAdapter extends RecyclerView.Adapter<DeviceHolder>{
private List<WifiP2pDevice> Devices;
public DeviceAdapter(List<WifiP2pDevice> devices){
Devices=devices;
Log.d (MainActivity.TAG, "device_list");
}
#Override
public DeviceHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater layoutInflater = LayoutInflater.from(getActivity());
View view=layoutInflater
.inflate(android.R.layout.simple_list_item_1, parent, false);
Log.d (MainActivity.TAG, "simple_list");
return new DeviceHolder(view);
}
#Override
public void onBindViewHolder(DeviceHolder holder, int position) {
WifiP2pDevice device = Devices.get(position);
holder.mTitleTextView.setTag(position);
holder.mTitleTextView.setText(device.deviceName);
Log.d (MainActivity.TAG, "Device_bound");
}
#Override
public int getItemCount() {
return mDevices.size();
}
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:orientation="vertical"
android:layout_height="wrap_content"
tools:context="com.moon.android.wifidirectproject_moon.MainActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button
android:id="#+id/wifi_open"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="WiFi_Direct" />
<Button
android:id="#+id/connect"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Connect" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<Button
android:id="#+id/file"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="file" />
<Button
android:id="#+id/gallery"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="gallery" />
<Button
android:id="#+id/media"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="media" />
</LinearLayout>
The Other Layout:
<android.support.v7.widget.RecyclerView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/device_recycler_view"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
I think I have made some (not complete) progress on my question. I suspected that the ArrayList information is not properly delivered to my fragment class. So I wrote the following code in OnCreate method in MainActivity:
DeviceFragment df = new DeviceFragment();
Bundle bundle = new Bundle();
bundle.putParcelableArrayList("bundle",WiFiDirectBroadcastReceiver.peers);
df.setArguments(bundle);
FragmentManager fm = getSupportFragmentManager();
Fragment fragment = fm.findFragmentById(R.id.fragment_container);
if (fragment == null) {
fragment = df;
fm.beginTransaction()
.add(R.id.fragment_container, fragment)
.commit();
Log.d (TAG, "fragment_activated");
}
I put the following code in my fragment class:
mDevices = getArguments().getParcelableArrayList("bundle");
and revised Adapter class as follows:
public DeviceAdapter(List<WifiP2pDevice> devices){
Devices=devices;
notifyDataSetChanged();
Log.d (MainActivity.TAG, "device_list");
}
It worked. But I met with one more problem. The textviews on screen are refreshed only when I turned off and on again (not powered on/off). So, I want to make a "refresh button" in MainActivity so that I can refresh the list like when turning on/off. But I have no idea how I can refresh the RecyclerView's fragment in MainActivity. I think I should work on fragmentManager and transaction. Could anybody help me deal with this issue?
My app consists of two strings and two buttons, one English string and Hindi string, when i click on English speak button, the English string is pronouncing, when i come to Hindi string it is not responding to given word as it was mentioned.
Here is my MainActivity look likes,
public class MainActivity extends AppCompatActivity {
private TextView englishString, hindiString;
private Button englishButton, hindiButton;
private TextToSpeech textToSpeech;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
englishString = (TextView) findViewById(R.id.englishString);
hindiString = (TextView) findViewById(R.id.hindiString);
englishButton = (Button) findViewById(R.id.englishButton);
hindiButton = (Button) findViewById(R.id.hindiButton);
englishButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
loadSpeakingLanguages(englishString.getText().toString());
}
});
hindiButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
loadSpeakingLanguages(hindiString.getText().toString());
}
});
}
private void loadSpeakingLanguages(String textToTranslate) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
ttsGreater21(textToTranslate);
} else {
ttsUnder20(textToTranslate);
}
}
#SuppressWarnings("deprecation")
private void ttsUnder20(String text) {
HashMap<String, String> map = new HashMap<>();
map.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, "MessageId");
textToSpeech.speak(text, TextToSpeech.QUEUE_FLUSH, map);
}
#TargetApi(Build.VERSION_CODES.LOLLIPOP)
private void ttsGreater21(String text) {
String utteranceId = this.hashCode() + "";
textToSpeech.speak(text, TextToSpeech.QUEUE_FLUSH, null, utteranceId);
}
#Override
protected void onResume() {
textToSpeech = new TextToSpeech(getApplicationContext(), new TextToSpeech.OnInitListener() {
#Override
public void onInit(int status) {
if (status != TextToSpeech.ERROR) {
textToSpeech.setLanguage(Locale.ENGLISH);
}
}
});
super.onResume();
}
public void onPause() {
if (textToSpeech != null) {
textToSpeech.stop();
textToSpeech.shutdown();
textToSpeech = null;
}
super.onPause();
}}
Here is my activity_main looks like,
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="ravi.texttospeech.MainActivity">
<TextView
android:id="#+id/englishString"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello World!"
android:textSize="25dp" />
<TextView
android:id="#+id/hindiString"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/englishString"
android:text="नमस्ते दुनिया"
android:textSize="25dp" />
<Button
android:id="#+id/englishButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/hindiString"
android:text="Speak English Text" />
<Button
android:id="#+id/hindiButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/englishButton"
android:text="Speak Hindi Text" />
And here is how my app look like
I have done some modifications in your code.
hindiButton.setOnClickListener(new View.OnClickListener() {
#TargetApi(Build.VERSION_CODES.LOLLIPOP)
#Override
public void onClick(View view) {
loadSpeakingLanguages(hindiString.getText().toString());
textToSpeech.setLanguage(Locale.forLanguageTag("hin"));
}
});
its working fine for me.
You need to use ISO 639 3-letter word or ISO 639 2-letter word
check out the ISO country names and there corresponding codes in this link
Note: This method works only above lollipop and next versions .
setLanguage(new Locale("hi","IN"))
Try this:-
Locale locale = new Locale("hi", "IN");
int avail = textToSpeech.isLanguageAvailable(locale);
switch (avail) {
case TextToSpeech.LANG_AVAILABLE:
textToSpeech.setLanguage(Locale.forLanguageTag("hi"));
isLanguageAvailable = true;
break;
case TextToSpeech.LANG_COUNTRY_AVAILABLE:
case TextToSpeech.LANG_COUNTRY_VAR_AVAILABLE:
textToSpeech.setLanguage(locale);
isLanguageAvailable = true;
break;
}
Changing the default engine to com.google.android.tts, worked for me.
Example:
new TextToSpeech(
context.getApplicationContext(),
new TextToSpeech.OnInitListener() {
#Override
public void onInit(int status) {
if (status != TextToSpeech.ERROR) {
if (textToSpeech != null) {
textToSpeech.setLanguage(new Locale("en", "IN"));
textToSpeech.setSpeechRate(1);
}
}
}
},
"com.google.android.tts");
Add this import:
import android.speech.tts.TextToSpeech
Implement this listener
class DetailDay : AppCompatActivity(), TextToSpeech.OnInitListener {
Then override (paste) this method:
override fun onInit(intVar: Int) {
if(intVar==TextToSpeech.SUCCESS){
var local= Locale("hi","IN")
val resultado=tts!!.setLanguage(local)
if(resultado==TextToSpeech.LANG_MISSING_DATA){
Log.i(TAG,"lang not found")
}
}
}
Then create this variable:
private var tts:TextToSpeech?=null
Initialize in onCreate (recommended)
tts= TextToSpeech(this,this)
To start playing, call this method:
tts!!.speak(stringData, TextToSpeech.QUEUE_FLUSH, null);
To Stop playing,
tts!!.stop()
I am trying to implement "Swipe to load more" method in my application but I got that error when I swipe down in the first time. This is what it showed in the console:
E/SwipeRefreshLayout: Got ACTION_MOVE event but don't have an active
pointer id. E/SwipeRefreshLayout: Got ACTION_MOVE event but don't have
an active pointer id. E/SwipeRefreshLayout: Got ACTION_MOVE event but
don't have an active pointer id. E/SwipeRefreshLayout: Got ACTION_MOVE
event but don't have an active pointer id.
This is my layout code:
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context="training.com.chatgcmapplication.ChatActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:theme="#style/AppTheme.AppBarOverlay">
<android.support.v7.widget.Toolbar
android:id="#+id/toolbar"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
app:popupTheme="#style/AppTheme.PopupOverlay" />
</android.support.design.widget.AppBarLayout>
<android.support.v4.widget.SwipeRefreshLayout
android:id="#+id/swipeLayout"
android:layout_width="match_parent"
android:layout_height="380dp">
<ListView
android:id="#+id/listMessage"
android:layout_width="match_parent"
android:layout_height="380dp"
android:layout_alignParentLeft="false"
android:layout_alignParentTop="false"
android:divider="#null"
android:listSelector="#android:color/transparent"
android:stackFromBottom="true"
android:transcriptMode="alwaysScroll" />
</android.support.v4.widget.SwipeRefreshLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:weightSum="1">
<EditText
android:id="#+id/txt_chat"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="0.92"
android:inputType="text" />
<Button
android:id="#+id/btn_send"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_marginLeft="30dp"
android:text="#string/btn_send" />
</LinearLayout>
</LinearLayout>
</android.support.design.widget.CoordinatorLayout>
And when I swipe in the second time: it load double data.
This is ChatActivity, what implement that method:
public class ChatActivity extends AppCompatActivity implements View.OnClickListener, SwipeRefreshLayout.OnRefreshListener {
private static EditText txt_chat;
private String registId;
private String chatTitle;
private MessageSender mgsSender;
private int userId;
private DatabaseHelper databaseHelper;
private TimeUtil timeUtil;
private MessageAdapter messageAdapter;
private int offsetNumber = 5;
private SwipeRefreshLayout swipeRefreshLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
if (getSupportActionBar() != null) {
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}
Button btn_send = (Button) findViewById(R.id.btn_send);
txt_chat = (EditText) findViewById(R.id.txt_chat);
swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipeLayout);
swipeRefreshLayout.setOnRefreshListener(this);
ListView lv_message = (ListView) findViewById(R.id.listMessage);
timeUtil = new TimeUtil();
databaseHelper = DatabaseHelper.getInstance(getApplicationContext());
btn_send.setOnClickListener(this);
Bundle bundle = getIntent().getExtras();
chatTitle = bundle.getString("titleName");
if (getIntent().getBundleExtra("INFO") != null) {
chatTitle = getIntent().getBundleExtra("INFO").getString("name");
this.setTitle(chatTitle);
} else {
this.setTitle(chatTitle);
}
registId = bundle.getString("regId");
userId = databaseHelper.getUser(chatTitle).getUserId();
List<Message> messages = databaseHelper.getLastTenMessages(AppConfig.USER_ID, databaseHelper.getUser(chatTitle).getUserId(), 0);
messageAdapter = new MessageAdapter(getApplicationContext(), R.layout.chat_item, (ArrayList<Message>) messages);
LocalBroadcastManager.getInstance(this).registerReceiver(onNotice, new IntentFilter("Msg"));
if (messages.size() > 0) lv_message.setAdapter(messageAdapter);
}
private BroadcastReceiver onNotice = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String message = intent.getStringExtra("message");
try {
Message messageObj = new Message();
messageObj.setMessage(message);
messageObj.setUserId(userId);
messageObj.setSender_id(AppConfig.USER_ID);
messageObj.setExpiresTime(timeUtil.formatDateTime(timeUtil.getCurrentTime()));
messageAdapter.add(messageObj);
} catch (ParseException e) {
e.printStackTrace();
}
messageAdapter.notifyDataSetChanged();
}
};
#Override
public void onBackPressed() {
super.onBackPressed();
finish();
}
#Override
protected void onDestroy() {
LocalBroadcastManager.getInstance(this).unregisterReceiver(onNotice);
super.onDestroy();
}
private static MessageSenderContent createMegContent(String regId, String title) {
String message = txt_chat.getText().toString();
MessageSenderContent mgsContent = new MessageSenderContent();
mgsContent.addRegId(regId);
mgsContent.createData(title, message);
return mgsContent;
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_send:
String message = txt_chat.getText().toString();
databaseHelper = DatabaseHelper.getInstance(getApplicationContext());
mgsSender = new MessageSender();
new AsyncTask<Void, Void, Void>() {
#Override
protected Void doInBackground(Void... params) {
MessageSenderContent mgsContent = createMegContent(registId, AppConfig.USER_NAME);
mgsSender.sendPost(mgsContent);
return null;
}
}.execute();
databaseHelper.addMessage(message, timeUtil.getCurrentTime(), userId, AppConfig.USER_ID);
txt_chat.setText("");
try {
Message messageObj = new Message();
messageObj.setMessage(message);
messageObj.setUserId(AppConfig.USER_ID);
messageObj.setSender_id(userId);
messageObj.setExpiresTime(timeUtil.formatDateTime(timeUtil.getCurrentTime()));
messageAdapter.add(messageObj);
} catch (ParseException e) {
e.printStackTrace();
}
messageAdapter.notifyDataSetChanged();
break;
}
}
#Override
public void onRefresh() {
swipeRefreshLayout.setRefreshing(true);
List<Message> messages = databaseHelper.getLastTenMessages(AppConfig.USER_ID, databaseHelper.getUser(chatTitle).getUserId(), offsetNumber);
messageAdapter.insertToTheFirst(messages);
messageAdapter.notifyDataSetChanged();
offsetNumber += 5;
Log.i("Offset number", offsetNumber + "");
swipeRefreshLayout.setRefreshing(false);
}
}
UPDATE ISSUE's REASON
I found the reason of that issue. It due to I force the listview scroll to the bottom when it init with this code :
android:stackFromBottom="true"
I replace that code with this but still have same issue:
lv_message.post(new Runnable() {
#Override
public void run() {
lv_message.setSelection(lv_message.getCount() -1);
}
});
I think the problem is , You are trying to show , dismiss and refresh swipeRefreshLayout inside the same method i.e onRefresh().
Make seperate methods for showing and dismissing dialog and invoke them from the place where they are required as I have done below:
#Override
public void onRefresh() {
// refresh code here.
}
#Override
public void showDialog() {
swipeRef.post(new Runnable() {
#Override
public void run() {
if(swipeRef != null)
swipeRef.setRefreshing(true);
}
});
}
#Override
public void dismissDialog() {
if(swipeRef!=null && swipeRef.isShown() )
swipeRef.setRefreshing(false);
}
I created this just to understand what intents do and how they do it:
first activity:
public class FirstActivity extends AppCompatActivity {
private Button launch;
private EditText label;
private String msg;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
launch=(Button)findViewById(R.id.launch);
label=(EditText)findViewById(R.id.et);
msg= label.getText().toString();
launch.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent=SecondActivity.newIntent(FirstActivity.this, msg);
startActivity(intent);
}
});
}
}
second activity:
public class SecondActivity extends AppCompatActivity {
private EditText et1;
private static String EXTRA ="extra";
private static String message="msg";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
et1=(EditText)findViewById(R.id.et1);
message=getIntent().getStringExtra(message);
et1.setText(message);
}
public static Intent newIntent(Context packageContext, String msg) {
Intent i = new Intent(packageContext, SecondActivity.class);
i.putExtra(EXTRA, msg);
return i;
}
}
and these are the xml files of the two activities(although I dont think these will be needed but if necessary):
first activity:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<EditText
android:text="First Activity"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/et"
android:inputType="text"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Launch the second activity"
android:id="#+id/launch"/>
</LinearLayout>
second activity:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Second Activity"
android:id="#+id/et1"/>
</LinearLayout>
You should do it the regular way, don't create any method.
In your first activity :
#Override
public void onClick(View v) {
Intent intent = new Intent(this, SecondActivity.class);
startActivity(intent);
}
And it should work.
You can add content to your intent (like you tried with your msg) this way :
intent.putExtra("Value1", "This value one for ActivityTwo ");
intent.putExtra("Value2", "This value two ActivityTwo");
Then in activity 2 you retrieve the datas like this :
Bundle extras = getIntent().getExtras();
if (extras == null) {
return;
}
// get data via the key
String value1 = extras.getString(Intent.EXTRA_TEXT);
if (value1 != null) {
// do something with the data
}
#Override
public void onClick(View v) {
Intent intent=SecondActivity.newIntent(FirstActivity.this, targetActivity.class);
startActivity(intent);
}
public class FirstActivity extends AppCompatActivity {
private Button launch;
private EditText label;
private String msg;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_first);
launch=(Button)findViewById(R.id.launch);
label=(EditText)findViewById(R.id.et);
launch.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
msg= label.getText().toString();
Intent intent=SecondActivity.newIntent(FirstActivity.this, SecondActivity.class);
intent.putExtra("msg",msg);
startActivity(intent);
}
});
}
}