How to add Text to speech for Hindi language? - android

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()

Related

How to show CustomDialog from FragmentActivity

I am getting Error that i wrote below when showing custom Dialog from FragmentActivity.
Error i am getting :
android.view.WindowManager$BadTokenException: Unable to add window -- token null is not for an application
Here is my DriverMapActivity that i show custom Dialog from :
Note: I removed some codes that they are not related to my question
DriverMap FragmentActivity
public class DriverMapActivity extends FragmentActivity{
private GoogleMap mMap;
GoogleApiClient googleApiClient;
SupportMapFragment mapFragment;
LocationRequest mLocationRequest;
private Location lastLocation;
private FirebaseAuth mAuth;
private Switch workingswitch;
private String customerId, userId;
private Toolbar toolbar;
private NavigationView navigationView;
private DrawerLayout drawerLayout;
private DatabaseReference driverInfoDB;
private String name, surname, profileimageURL;
private String distancetopick,distancetodes;
private int distancefinal;
private Button yesBtn, noBtn;
private UserInfoShower cdd;
private int cameraupdatedandzoomed;
private Map<String,String> infoMap;
private LatLng pickupLoc;
private LatLng destiantionLoc;
private Marker pickupMarker, destinationMarker;
private float rideDistance;
private Button btnzoom;
private String customerprofileUrl;
private Button logoutbtn, settingsbtn, historybtn, opendrawer;
private boolean pickupgeted;
private String rideStatus = "";
private LatLng target;
#SuppressLint("NewApi")
#RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_driver_map);
customerId = "";
cameraupdatedandzoomed=0;
mAuth = FirebaseAuth.getInstance();
toolbar = findViewById(R.id.toolbar);
polylines = new ArrayList<>();
userId = FirebaseAuth.getInstance().getCurrentUser().getUid();
btnzoom=findViewById(R.id.btnzoom);
pickupgeted = false;
startService(new Intent(DriverMapActivity.this,onAppKilled.class));
navigationView = (NavigationView) findViewById(R.id.navigation_view);
navigationView.setNavigationItemSelectedListener(this);
// This method will trigger on item Click of navigation menu
// Initializing Drawer Layout and ActionBarToggle
drawerLayout = (DrawerLayout) findViewById(R.id.drawer);
setDriverStuffToNavView();
btnzoom.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(lastLocation!=null)
{
}
else
{
Toast.makeText(DriverMapActivity.this, "Turn on Working
}
}
});
private void listenForCustomerRequest() {
String userId = FirebaseAuth.getInstance().getCurrentUser().getUid();
DatabaseReferencelistenerRef=FirebaseDatabase.getInstance().getReference()
.child("Users").child("Drivers").child(userId).child("CustomerRequest");
listenerRef.addChildEventListener(new ChildEventListener() {
public void onChildAdded(#NonNull DataSnapshot dataSnapshot, String s) {
if (dataSnapshot.exists()) {
customerId = dataSnapshot.getKey();
showUserInfo();
}
}
});
}
Here is method that i show CustomDialog:
UserInfoShower Method
Note: I removed some codes that they are not related to my question
private void showUserInfo() {
DatabaseReferenceuserinfoRef=FirebaseDatabase.getInstance().getReference()
.child("Users").child("Customers").child(customerId);
Log.i("TEST", "CustomerId Comes Driver " + customerId);
infoMap=new HashMap<>();
cdd = new UserInfoShower(DriverMapActivity.this,infoMap);
DatabaseReferenceuserInfoDB=FirebaseDatabase.getInstance().getReference()
.child("Users").child("Customers").child(customerId);
userInfoDB.addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot.exists() && dataSnapshot.getChildrenCount() > 0) {
Map<String, Object> map = (Map<String, Object>)
dataSnapshot.getValue();
infoMap.put("DriverOrCus", "1");
infoMap.put("Name", map.get("name").toString());
infoMap.put("Surname", map.get("surname").toString());
if(map.get("profileimageURL") !=null)
{
infoMap.put("profileimageURL",
map.get("profileimageURL").toString());
customerprofileUrl=map.get("profileimageURL").toString();
}
infoMap.put("customerId", customerId);
cdd = new UserInfoShower(DriverMapActivity.this,infoMap);
cdd.show();
cdd.setCanceledOnTouchOutside(false);
yesBtn = cdd.findViewById(R.id.yesBtn);
noBtn = cdd.findViewById(R.id.noBtn);
yesBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String userId=FirebaseAuth.getInstance().
getCurrentUser().getUid();
DatabaseReference decisionRef=FirebaseDatabase.
getInstance().getReference().
child("Users").child("Drivers").child(userId).child("CustomerRequest")
.child(customerId)
.child("driverDecision");
decisionRef.setValue("YES").addOnCompleteListener(newOnCompleteListener
<Void>() {
#Override
public void onComplete(#NonNull
Task<Void>task) {
cdd.cancel();
cdd.dismiss();
cdd=null;
getCustomerRideInfo();
}
});
}
});
}
Error happens when i call cdd.show();
Here is UserInfoShower Dialog:
public class UserInfoShower extends Dialog {
public Context c;
private Button noBtn, yesBtn;
private String name, surname, profileimageURL;
private TextView customerName, customerSurname;
private ImageView customerprofile;
private int position;
private String driverId;
private LatLng CustomerPickupLoc, CustomerDestinationLoc;
private String customerId, desName;
private SharedPreferences sharedpref;
Map<String,String> infoMap;
public UserInfoShower(Context a,Map<String,String> infoMap) {
super(a);
this.c = a;
this.infoMap=infoMap;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_customer_info_shower);
noBtn = findViewById(R.id.noBtn);
yesBtn = findViewById(R.id.yesBtn);
customerName = findViewById(R.id.customerName);
customerSurname = findViewById(R.id.customerSurname);
customerprofile = findViewById(R.id.customerprofile);
position = Integer.valueOf(infoMap.get("DriverOrCus"));
if (position == 1) {
showCusInfo();
} else {
showDriverInfo();
}
yesBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (position == 1) // If user is Driver
{
dismiss();
} else //if user is Cusomer And Liked Driver
{
dismiss();
}
}
});
noBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (position == 1) //if User is Driver
{
dismiss();
} else// if User is Customer And not liked Driver
{
dismiss();
}
}
});
}
private void showCusInfo() {
name = infoMap.get("Name");
surname = infoMap.get("Surname");
customerId = infoMap.get("customerId");
customerName.setText("Name " + name);
customerSurname.setText("Surname " + surname);
}
#Override
public void onAttachedToWindow() {
super.onAttachedToWindow();
}
public static boolean isValidContextForGlide(final Context context) {
if (context == null) {
return false;
}
if (context instanceof Activity) {
final Activity activity = (Activity) context;
if (activity.isDestroyed() || activity.isFinishing()) {
return false;
}
}
return true;
}
}
Here is My Dialog xml file:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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"
tools:context=".UserInfoShower">
<ImageView
android:id="#+id/customerprofile"
android:layout_width="90dp"
android:layout_height="102dp"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_marginStart="30dp"
android:layout_marginTop="35dp"
android:src="#drawable/customer"
tools:ignore="RtlCompat" />
<TextView
android:layout_width="240dp"
android:layout_height="wrap_content"
android:id="#+id/customerName"
android:layout_alignParentTop="true"
android:layout_marginTop="36dp"
android:layout_toEndOf="#+id/customerprofile"
android:text="Name : Vuqar"
android:textColor="#color/colorPrimaryDark"
android:textSize="20sp"
tools:ignore="RtlCompat" />
<TextView
android:id="#+id/customerSurname"
android:layout_width="240dp"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_marginTop="92dp"
android:layout_toEndOf="#+id/customerprofile"
android:text="Surname : Samed"
android:textColor="#color/colorPrimaryDark"
android:textSize="20sp"
tools:ignore="RtlCompat" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_marginTop="219dp"
android:orientation="horizontal">
<Button
android:id="#+id/yesBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="OK.Looks Good" />
<Button
android:id="#+id/noBtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Nope" />
</LinearLayout>
</RelativeLayout>
And finally here is whole error log :
Hope you can help me.Cheers !
Problem solved by : #dr3k
Here is solution. Solution

I've failed to show lists of a RecyclerView

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?

Updating listview with beacons in android, putting beacons into arraylist

Please help, I can find the distance of one beacon but I can't populate a listview with other beacons in the region. I've tested the listview by just using a string array, populates fine. Everything else works but I'm at a total loss for this last part, close to the edge here...
Here's my code for the main activity`import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.RemoteException;
import android.util.Log;
import android.widget.*;
import org.altbeacon.beacon.*;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.logging.Handler;
import java.util.logging.LogRecord;
public class MainActivity extends Activity implements BeaconConsumer{
private BeaconManager beaconManager;
int distance;
Identifier minorID;
double distanceLong;
private Handler mHandler;
private int i;
public TextView distanceText;
public TextView distanceName1;
public ImageView distanceImage;
public String name1;
public boolean exitRegion = false;
public String minorString;
List<String> beaconList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent intent = getIntent();
name1 = intent.getStringExtra("beacon1");
beaconManager = BeaconManager.getInstanceForApplication(this);
beaconManager.getBeaconParsers().add(new BeaconParser()
.setBeaconLayout("m:2-3=0215,i:4-19,i:20-21,i:22-23,p:24-24,d:25-25"));
beaconManager.bind(this);
distanceText = (TextView) findViewById(R.id.distanceText);
distanceText.setText("No beacons found yet, please wait");
distanceName1 = (TextView) findViewById(R.id.name1);
distanceName1.getText();
distanceName1.setText("How far away is "+name1+"?");
distanceText = (TextView) findViewById(R.id.distanceText);
distanceText.getText();
distanceText.setText("Distance: " + distance+ " metres");
distanceImage = (ImageView) findViewById(R.id.distanceImage);
//alertDialogue();
i = 0;
mHandler = new Handler() {
#Override
public void close() {
}
#Override
public void flush() {
}
#Override
public void publish(LogRecord record) {
}
};
beaconList = new ArrayList<String>();
ListAdapter beaconAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, beaconList);
ListView beaconListView = (ListView) findViewById(R.id.beaconListView);
beaconListView.setAdapter(beaconAdapter);
distanceText.post(mUpdate);
distanceImage.post(mUpdate);
}
private Runnable mUpdate = new Runnable() {
public void run() {
distanceText.setText("Distance: " + distance+ " ms");
imageDistance(distance);
alertDialogue(distance);
i++;
distanceText.postDelayed(this, 10000);
}
};
#Override
protected void onDestroy() {
super.onDestroy();
beaconManager.unbind(this);
}
#Override
public void onBeaconServiceConnect() {
final Region region = new Region("myBeacons", Identifier.parse("B9407F30-F5F8-466E-AFF9-25556B57FE6D"), null, null);
beaconManager.setMonitorNotifier(new MonitorNotifier() {
#Override
public void didEnterRegion(Region region) {
try {
Log.d(TAG, "didEnterRegion");
exitRegion=false;
beaconManager.startRangingBeaconsInRegion(region);
} catch (RemoteException e) {
e.printStackTrace();
}
}
#Override
public void didExitRegion(Region region) {
try {
Log.d(TAG, "didExitRegion");
exitRegion = true;
beaconManager.stopRangingBeaconsInRegion(region);
} catch (RemoteException e) {
e.printStackTrace();
}
}
#Override
public void didDetermineStateForRegion(int i, Region region) {
}
});
beaconManager.setRangeNotifier(new RangeNotifier() {
#Override
public void didRangeBeaconsInRegion(Collection<Beacon> beacons, Region region) {
for(Beacon oneBeacon : beacons) {
distanceLong = oneBeacon.getDistance();
distance = (int) distanceLong;
minorID = oneBeacon.getId3();
minorString = minorID.toString();
String distanceString = String.valueOf("Distance of " + minorID +" beacon: "+ (int) distanceLong+ " metres");
beaconList.add(distanceString);
Beacon.setHardwareEqualityEnforced(true);
}
}
});
try {
beaconManager.startMonitoringBeaconsInRegion(region);
} catch (RemoteException e) {
e.printStackTrace();
}
}
`
My layout code is here, as I said the UI mostly works already but maybe I've missed something with the listview...
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout 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:orientation="vertical"
tools:context="${relativePackage}.${activityClass}">
<TextView
android:layout_width="wrap_content"
android:layout_height="60dp"
android:textColor="#color/material_blue_grey_800"
android:textSize="25sp"
android:id="#+id/name1"
android:layout_gravity="center_horizontal"
android:layout_margin="10dp"
/>
<TextView android:layout_width="wrap_content"
android:layout_height="60dp"
android:id="#+id/distanceText"
android:textColor="#color/material_blue_grey_800"
android:textSize="25sp"
android:layout_margin="10dp"
android:layout_gravity="center_horizontal"
android:layout_below="#+id/name1"
/>
<ImageView android:layout_width="150dp"
android:layout_height="150dp"
android:id="#+id/distanceImage"
android:layout_margin="10dp"
android:layout_below="#+id/distanceText"
android:layout_gravity="center_horizontal"
/>
<ListView android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/beaconListView"
android:textColor="#color/material_blue_grey_800"
android:textSize="25sp"
></ListView>
</LinearLayout></ScrollView>
A few tips:
You don't need the separate beaconList, only the beaconAdapter. But you do need to move the declaration of the beaconAdapter to be a class level variable like this:
...
public String minorString;
private ListAdapter beaconAdapter;
...
Then you can initialize it the same place you do now, just remove the declaration part. You can also remove the reference to beaconList, which is unneeded:
beaconAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1);
In the didRangeBeaconsInRegion callback, you then update the entries in the beaconAdapter. Like this:
public void didRangeBeaconsInRegion(Collection<Beacon> beacons, Region region) {
beaconAdapter.clear();
for(Beacon oneBeacon : beacons) {
distanceLong = oneBeacon.getDistance();
distance = (int) distanceLong;
minorID = oneBeacon.getId3();
minorString = minorID.toString();
String distanceString = String.valueOf("Distance of " + minorID +" beacon: "+ (int) distanceLong+ " metres");
beaconAdapter.add(distanceString);
Beacon.setHardwareEqualityEnforced(true);
}
beaconAdapter.notifyDataSetChanged()
}
Note that in the code above, notifyDataSetChanged() is called as #niels-masdorp correctly says to do in his answer.

in app purchase saving buttons states

I am trying to develop an app with in app purchases in it, simply what I want to do is to have two buttons one to make the purchase(enabled) the second button to open the activity after purchase (at first is disabled then after purchase is enabled).
Two problems the first was to save the buttons state after the purchase as they were getting reset every time I restart the app. So I did some researches and found about shared preference and I did implemented it but the second problem came out that buttons statuses doesn’t seem to work right (between disabled to enabled) after implementing shared preference.
Note that in the app I have two buttons that do the same thing one enables the other buttons but with no purchase made and they work fine with shared preference, but the buttons associated with the in app purchase stopped changing their status from disabled to enabled after the purchase is made (they stay disabled after the purchase)
Here is my xml code:
<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:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin" tools:context=".MainScreen">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Activity 1"
android:id="#+id/act1"
android:onClick="Activity1"
android:layout_marginTop="84dp"
android:layout_alignParentTop="true"
android:layout_toLeftOf="#+id/buyall"
android:layout_toStartOf="#+id/buyall"
android:enabled="false" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Buy Act 1"
android:id="#+id/buyButton"
android:onClick="buyClick"
android:layout_alignTop="#+id/act1"
android:layout_toRightOf="#+id/act1"
android:layout_toEndOf="#+id/act1"
android:layout_marginLeft="45dp"
android:layout_marginStart="45dp"
android:enabled="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Activity 2"
android:id="#+id/act2"
android:layout_below="#+id/act1"
android:layout_alignLeft="#+id/act1"
android:layout_alignStart="#+id/act1"
android:onClick="Activity2"
android:enabled="false" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Buy act 2"
android:id="#+id/buyact2"
android:layout_alignBottom="#+id/act2"
android:layout_alignLeft="#+id/buyButton"
android:layout_alignStart="#+id/buyButton"
android:onClick="buyAct2"
android:enabled="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Activity 3"
android:id="#+id/act3"
android:layout_below="#+id/act2"
android:layout_alignLeft="#+id/act2"
android:layout_alignStart="#+id/act2"
android:onClick="Activity3"
android:enabled="false" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Buy act 3"
android:id="#+id/buyact3"
android:layout_alignBottom="#+id/act3"
android:layout_alignLeft="#+id/buyact2"
android:layout_alignStart="#+id/buyact2"
android:onClick="buyAct3"
android:enabled="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Buy all"
android:id="#+id/buyall"
android:onClick="buyAll"
android:enabled="true"
android:layout_below="#+id/eact4"
android:layout_centerHorizontal="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="ACT 4"
android:id="#+id/act4"
android:onClick="ACT4"
android:layout_below="#+id/act3"
android:layout_alignLeft="#+id/act3"
android:layout_alignStart="#+id/act3"
android:enabled="false" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Enable ACT 4"
android:id="#+id/eact4"
android:onClick="EACT4"
android:layout_below="#+id/buyact3"
android:layout_alignLeft="#+id/buyact3"
android:layout_alignStart="#+id/buyact3"
android:enabled="true" />
And that’s my java code:
package com.aseng90_test.smiap2;
import android.content.Intent;
import android.content.SharedPreferences;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import com.aseng90_test.smiap2.util.IabHelper;
import com.aseng90_test.smiap2.util.IabResult;
import com.aseng90_test.smiap2.util.Purchase;
public class MainScreen extends ActionBarActivity {
private static final String TAG = "com.aseng90_test.smiap2";
IabHelper mHelper;
private static final String ITEM_SKU = "com.aseng90_test.smiap2_button555";
private static final String ITEM_SKU2 = "com.aseng90_test.smiap2_buyact222";
private static final String ITEM_SKU3 = "com.aseng90_test.smiap2_buyact333";
private static final String ITEM_SKU4 = "com.aseng90_test.smiap2_buyall_11";
private Button Activity1;
private Button Activity2;
private Button Activity3;
private Button buyButton;
private Button buyAct2;
private Button buyAct3;
private Button buyAll;
private Button EAct4;
private Button Act4;
private SharedPreferences prefs;
private String prefName = "MyPref";
boolean Activity1_isEnabled;
boolean Activity2_isEnabled;
boolean Activity3_isEnabled;
boolean Act4_isEnabled;
boolean buyButton_isEnabled;
boolean buyAct2_isEnabled;
boolean buyAct3_isEnabled;
boolean buyAll_isEnabled;
boolean EAct4_isEnabled;
private static final String Activity1_state = "Activity1_state";
private static final String Activity2_State = "Activity2_state";
private static final String Activity3_State = "Activity3_state";
private static final String buyButton_State = "buyButton_state";
private static final String buyAct2_State = "buyAct2_state";
private static final String buyAct3_State = "buyAct3_state";
private static final String buyAll_State = "buyAll_state";
private static final String Act4_State = "Act4_state";
private static final String EAct4_State = "EAct4_state";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_screen);
buyButton = (Button) findViewById(R.id.buyButton);
buyAct2 = (Button) findViewById(R.id.buyact2);
buyAct3 = (Button) findViewById(R.id.buyact3);
buyAll = (Button) findViewById(R.id.buyall);
Activity1 = (Button) findViewById(R.id.act1);
Activity2 = (Button) findViewById(R.id.act2);
Activity3 = (Button) findViewById(R.id.act3);
EAct4 = (Button) findViewById(R.id.eact4);
Act4 = (Button) findViewById(R.id.act4);
String base64EncodedPublicKey =
"";
mHelper = new IabHelper(this, base64EncodedPublicKey);
mHelper.startSetup(new
IabHelper.OnIabSetupFinishedListener() {
public void onIabSetupFinished(IabResult result) {
if (!result.isSuccess()) {
Log.d(TAG, "In-app Billing setup failed: " + result);
} else {
Log.d(TAG, "In-app Billing is set up OK");
}
}
});
}
public void EACT4(View view) {
EAct4.setEnabled(false);
Act4.setEnabled(true);
}
public void ACT4(View view) {
Toast.makeText(MainScreen.this,
"ACt4 Clicked", Toast.LENGTH_LONG).show();
}
public void buyClick(View view) {
mHelper.launchPurchaseFlow(this, ITEM_SKU, 10001,
mPurchaseFinishedListener, "mypurchasetoken");
}
public void buyAct2(View view) {
mHelper.launchPurchaseFlow(this, ITEM_SKU2, 10002, mPurchaseFinishedListener, "buyact2");
}
public void buyAct3(View view) {
mHelper.launchPurchaseFlow(this, ITEM_SKU3, 10003, mPurchaseFinishedListener, "buyact3");
}
public void buyAll(View view) {
mHelper.launchPurchaseFlow(this, ITEM_SKU4, 10004, mPurchaseFinishedListener, "buyall");
}
#Override
protected void onActivityResult(int requestCode, int resultCode,
Intent data) {
if (!mHelper.handleActivityResult(requestCode,
resultCode, data)) {
super.onActivityResult(requestCode, resultCode, data);
}
}
IabHelper.OnIabPurchaseFinishedListener mPurchaseFinishedListener
= new IabHelper.OnIabPurchaseFinishedListener() {
public void onIabPurchaseFinished(IabResult result,
Purchase purchase) {
if (result.isFailure()) {
// Handle error
return;
}
if (purchase.getSku().equals(ITEM_SKU)) {
Activity1.setEnabled(true);
buyButton.setEnabled(false);
}
if (purchase.getSku().equals(ITEM_SKU2)) {
Activity2.setEnabled(true);
buyAct2.setEnabled(false);
}
if (purchase.getSku().equals(ITEM_SKU3)) {
Activity3.setEnabled(true);
buyAct3.setEnabled(false);
}
if (purchase.getSku().equals(ITEM_SKU4)) {
Activity1.setEnabled(true);
Activity2.setEnabled(true);
Activity3.setEnabled(true);
buyAll.setEnabled(false);
buyButton.setEnabled(false);
buyAct2.setEnabled(false);
buyAct3.setEnabled(false);
}
}
};
public void Activity1(View view) {
startActivity(new Intent(MainScreen.this, Click1.class));
}
public void Activity2(View view) {
startActivity(new Intent(MainScreen.this, Activity2.class));
}
public void Activity3(View view) {
startActivity(new Intent(MainScreen.this, Activity3.class));
}
#Override
public void onDestroy() {
super.onDestroy();
if (mHelper != null) mHelper.dispose();
mHelper = null;
}
#Override
protected void onPause(){
super.onPause();
if (Act4.isEnabled()){
Act4_isEnabled = true;
}
else {
Act4_isEnabled = false;
}
if (Activity1.isEnabled()){
Activity1_isEnabled = true;
}
else {
Activity1_isEnabled = false;
}
if (Activity2.isEnabled()){
Activity2_isEnabled = true;
}
else {
Activity2_isEnabled = false;
}
if (Activity3.isEnabled()){
Activity3_isEnabled = true;
}
else {
Activity3_isEnabled = false;
}
if (buyButton.isEnabled()){
buyButton_isEnabled = true;
}
else {
buyButton_isEnabled = false;
}
if (buyAct2.isEnabled()){
buyAct2_isEnabled = true;
}
else {
buyAct2_isEnabled = false;
}
if (buyAct3.isEnabled()){
buyAct3_isEnabled = true;
}
else {
buyAct3_isEnabled = false;
}
if (buyAll.isEnabled()){
buyAll_isEnabled = true;
}
else {
buyAll_isEnabled = false;
}
prefs = getSharedPreferences(prefName,MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putString(Activity1_state,this.getLocalClassName());
editor.putBoolean(Act4_State,Act4_isEnabled);
editor.putBoolean(EAct4_State,EAct4_isEnabled);
editor.putBoolean(Activity1_state,Activity1_isEnabled);
editor.putBoolean(Activity2_State,Activity2_isEnabled);
editor.putBoolean(Activity3_State,Activity3_isEnabled);
editor.putBoolean(buyButton_State,buyButton_isEnabled);
editor.putBoolean(buyAct2_State,buyAct2_isEnabled);
editor.putBoolean(buyAct3_State,buyAct3_isEnabled);
editor.putBoolean(buyAll_State,buyAll_isEnabled);
editor.apply();
}
#Override
protected void onResume(){
super.onResume();
prefs = getSharedPreferences(prefName,MODE_PRIVATE);
Act4.setEnabled(prefs.getBoolean(Act4_State,false));
Activity1.setEnabled(prefs.getBoolean(Activity1_state,false));
Activity2.setEnabled(prefs.getBoolean(Activity2_State,false));
Activity3.setEnabled(prefs.getBoolean(Activity3_State,false));
EAct4.setEnabled(prefs.getBoolean(EAct4_State,true));
buyButton.setEnabled(prefs.getBoolean(buyButton_State,true));
buyAct2.setEnabled(prefs.getBoolean(buyAct2_State,true));
buyAct3.setEnabled(prefs.getBoolean(buyAct3_State,true));
buyAll.setEnabled(prefs.getBoolean(buyAll_State,true));
}
So Any suggestions if I have something wrong in my code?
Thanks a lot.
Try to call methods from Java part , don't call from xml using android:onClick
Use default value of the button(buy) state to false in shared preference .
and in this screen implement this if check inside oncreate() method as:
if(button(buy) state ==false)
{
//make button(buy) state enable
//make activity button state disable
}
else
{
//make button(buy) state disable
//make activity button state enable
}
And make button(buy) and activity calling button state to true/false according to result after in app purchase and also update shared prefrence state according to result

Android: Data obtained from JSON not appearing complete in textview

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.

Categories

Resources