Today i am posting my first question here in stackoverflow.
My app's subject is speech to text application all the app is working but the text doen't appear in its zone after saying the speech. So i am here asking you all for help.
Belong my 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=".MainActivity">
<EditText
android:id="#+id/edittext"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:hint="Tap Mic to Speak"
android:padding="20dp"
android:textColor="#000000"
android:textSize="20sp" />
<ImageButton
android:id="#+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/edittext"
android:layout_centerHorizontal="true"
android:padding="40dp"
android:background="#color/white"
android:src="#drawable/ic_baseline_mic_24" />
</RelativeLayout>
And my main code:
package com.example.translationapp;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
checkPermission();
final EditText edittext = findViewById(R.id.edittext);
final SpeechRecognizer mSpeechRecognizer = SpeechRecognizer.createSpeechRecognizer(this);
final Intent mSpeechRecognizerIntent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
mSpeechRecognizerIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
mSpeechRecognizerIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE,
Locale.getDefault());
mSpeechRecognizer.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) {
//getting all the matches
ArrayList<String> matches = bundle
.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);
//displaying the first match
if (matches != null) {
edittext.setText(matches.get(0));
}
}
#Override
public void onPartialResults(Bundle bundle) {
}
#Override
public void onEvent(int i, Bundle bundle) {
}
});
findViewById(R.id.button).setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View view, MotionEvent motionEvent) {
switch (motionEvent.getAction()) {
case MotionEvent.ACTION_UP:
mSpeechRecognizer.stopListening();
edittext.setHint("You will see input here");
break;
case MotionEvent.ACTION_DOWN:
mSpeechRecognizer.startListening(mSpeechRecognizerIntent);
edittext.setText("");
edittext.setHint("Listening...");
break;
}
return false;
}
});
}
private void checkPermission() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (!(ContextCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED)) {
Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS,
Uri.parse("package:" + getPackageName()));
startActivity(intent);
finish();
}
}
}
}
So please again and thank you all for your time.
Related
I am trying to display a word from a second activity to my main activity which is inform of a recycler view with a textview item.
I have created my adapter and I am assuming it works fine the only problem is once I launch my floating button to access my display word activities it does not display on the main activity, what am I doing wrong, I am new to Android.
My Adapter :
public class RoomAdapter extends RecyclerView.Adapter<RoomAdapter.RoomViewHolder> {
private List <RoomPojo> word;
public RoomAdapter(List <RoomPojo> word1){
this.word = word1;
}
#NonNull
#Override
public RoomViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View layoutInflater = LayoutInflater.from(parent.getContext()).inflate(R.layout.word_item,parent,false);
return new RoomViewHolder(layoutInflater);
}
#Override
public void onBindViewHolder(#NonNull RoomViewHolder holder, int position) {
holder.wordTextView.setText(word.get(position).getWord());
}
#Override
public int getItemCount() {
return word.size();
}
public class RoomViewHolder extends RecyclerView.ViewHolder{
private TextView wordTextView;
public RoomViewHolder(View itemView) {
super(itemView);
wordTextView = itemView.findViewById(R.id.display_word);
}
}
}
Here is my Main activity:
public class MainActivity extends AppCompatActivity {
private RoomAdapter roomAdapter;
public static final int NEW_WORD_ACTIVITY_REQUEST_CODE = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
RecyclerView recyclerView = findViewById(R.id.rv_word);
recyclerView.setAdapter(roomAdapter);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(linearLayoutManager);
FloatingActionButton floatingActionButton = findViewById(R.id.fab);
floatingActionButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(), DisplayWord.class);
String word = getIntent().getStringExtra(DisplayWord.EXTRA_KEY);
startActivityForResult(intent,NEW_WORD_ACTIVITY_REQUEST_CODE);
}
});
}
}
Here is my display word which has a button and a edit text which should take just one string.
public class DisplayWord extends AppCompatActivity {
public static final String EXTRA_KEY = "key";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_word);
final EditText editText = findViewById(R.id.word_edit_text);
Button button = findViewById(R.id.word_button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent replyIntent = new Intent();
if(TextUtils.isEmpty(editText.getText())){
setResult(RESULT_CANCELED, replyIntent);
}else {
String word = editText.getText().toString();
replyIntent.putExtra(EXTRA_KEY,word);
}
finish();
}
});
}
}
Main.xml
<?xml version="1.0" encoding="utf-8"?>
<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="match_parent"
tools:context=".MainActivity">
<android.support.v7.widget.RecyclerView
android:id="#+id/rv_word"
android:layout_width="368dp"
android:layout_height="433dp"
android:layout_marginLeft="8dp"
android:layout_marginStart="8dp"
android:layout_marginTop="8dp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<android.support.design.widget.FloatingActionButton
android:id="#+id/fab"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="bottom|end"
android:layout_marginLeft="328dp"
android:layout_marginStart="328dp"
android:layout_marginTop="12dp"
android:src="#drawable/ic_add_black_24dp"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="#+id/rv_word" />
</android.support.constraint.ConstraintLayout>
Your code should be like this :
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent replyIntent = new Intent();
if(TextUtils.isEmpty(editText.getText())){
setResult(RESULT_CANCELED, replyIntent);
}else {
String word = editText.getText().toString();
replyIntent.putExtra(EXTRA_KEY,word);
setResult(RESULT_OK, replyIntent); //missing
}
finish();
}
});
Then After handle it in MainActivity.java
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
try {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_CODE && resultCode == RESULT_OK) {
String requiredValue = data.getStringExtra(DisplayWord.EXTRA_KEY);
}
} catch (Exception ex) {
Toast.makeText(Activity.this, ex.toString(),
Toast.LENGTH_SHORT).show();
}
}
I've been looking for information on Google for 2 days. But all
without results.
I want to use not the full screen mode, but the reduced one, so that
you can scan a certain area.
In Api Google, I also did not find what I needed.
The variant with resizing in SurfaceView is attached with a picture.
As you can see, the result is deplorable ((.
Is there a solution to my problem?
<?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"
android:id="#+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent">
<SurfaceView
android:layout_centerInParent="true"
android:id="#+id/surface_view"
android:layout_width="match_parent"
android:layout_height="100dp"/>
<TextView
android:id="#+id/txtView"
android:text="No Text"
android:layout_alignParentBottom="true"
android:textColor="#android:color/white"
android:textSize="20sp"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</RelativeLayout>
public class MainActivity extends AppCompatActivity {
#BindView(R.id.surface_view) SurfaceView cameraView;
#BindView(R.id.txtView) TextView txtView;
CameraSource cameraSource;
final int RequestCameraPermissionID = 1001;
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
switch (requestCode){
case RequestCameraPermissionID:
if (grantResults[0]==PackageManager.PERMISSION_GRANTED){
if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
return;
}
try {
cameraSource.start(cameraView.getHolder());
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.bind(this);
TextRecognizer textRecognizer = new TextRecognizer.Builder(getApplicationContext()).build();
if (!textRecognizer.isOperational()) {
Log.e("MainActivity", "onCreate= " + "Detecter");
} else {
cameraSource = new CameraSource.Builder(getApplicationContext(), textRecognizer )
.setFacing(CameraSource.CAMERA_FACING_BACK)
.setRequestedFps(2.0f)
.setAutoFocusEnabled(true)
.build();
cameraView.getHolder().addCallback(new SurfaceHolder.Callback() {
#Override
public void surfaceCreated(SurfaceHolder holder) {
try {
if (ActivityCompat.checkSelfPermission(MainActivity.this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{Manifest.permission.CAMERA},
RequestCameraPermissionID);
return;
}
cameraSource.start(cameraView.getHolder());
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
cameraSource.stop();
}
});
textRecognizer.setProcessor(new Detector.Processor<TextBlock>() {
#Override
public void release() {
}
#Override
public void receiveDetections(Detector.Detections<TextBlock> detections) {
final SparseArray<TextBlock> items=detections.getDetectedItems();
if (items.size()!=0){
txtView.post(() -> {
StringBuilder stringBuilder=new StringBuilder();
for (int i = 0; i < items.size(); i++) {
TextBlock item=items.valueAt(i);
stringBuilder.append(item.getValue());
stringBuilder.append("\n");
}
txtView.setText(stringBuilder.toString());
});
}
}
});
}
}
}
I have tried every solution I found on-line and anywhere. But I still can't solve this problem. It keeps giving me this error "E/RecyclerView: No adapter attached; skipping layout". I tried to use breakpoint to test each code. From the result, I get that data is successfully retrieved from firebase and save in ArrayList and the size of mItems is correct. But this is the result I get.Please somebody help me.
The Result I get
My firebase structure
ShowBookedSlotActivity.java
public class ShowBookedSlotActivity extends AppCompatActivity {
private static final String TAG ="Show Booked Activity" ;
private FirebaseAuth.AuthStateListener authListener;
private FirebaseAuth auth;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_show_booked_slot);
setTitle("Booked Gym Slot");
Log.d(TAG, "on create");
//Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
//setSupportActionBar(toolbar);
//getSupportActionBar().setDisplayHomeAsUpEnabled(true);
// getSupportActionBar().setHomeButtonEnabled(true);
auth = FirebaseAuth.getInstance();
FragmentManager fm = getSupportFragmentManager();
Fragment fragment = fm.findFragmentById(R.id.fragmentContainer);
if (fragment == null) {
fragment = new ListBookedSlotFragment();
Bundle bundle = new Bundle();
bundle.putString("UID", auth.getCurrentUser().getUid());
fragment.setArguments(bundle);
fm.beginTransaction()
.add(R.id.fragmentContainer, fragment)
.commit();
}
}
#Override
protected void onResume() {
super.onResume();
}
#Override
public void onStart() {
super.onStart();
}
#Override
public void onStop() {
super.onStop();
}
#Override
public void onBackPressed()
{
super.onBackPressed();
startActivity(new Intent(ShowBookedSlotActivity.this, UserHomeActivity.class));
finish();
}
}
ListBookedSlotFragment.java
public class ListBookedSlotFragment extends Fragment {
private final String TAG = "ListBookedSlotFragment";
private ArrayList<BookedSlot> mItems;
private ArrayList<String> mItemsKey;
private RecyclerView mItemRecyclerView;
private ItemAdapter mAdapter;
private DatabaseReference mItemRef;
private DatabaseReference mDatabase;
private String UID;
private Query mBookedSlotQuery;
private DatabaseReference mBookedSlotRef;
private ValueEventListener mBookedSlotQueryVEL;
#SuppressLint("LongLogTag")
#Override
public void onCreate(Bundle savedInstanceState) {
UID = this.getArguments().getString("UID");
Log.d(TAG, "UID: " + UID);
mDatabase = FirebaseDatabase.getInstance().getReference();
mItems = new ArrayList<>();
if (UID != null) {
mItemsKey = new ArrayList<>();
mBookedSlotQuery = mDatabase.child("booked_slot").orderByChild("UserID").equalTo(UID);
Log.d(TAG, "mItemRef:" + mBookedSlotQuery);
mBookedSlotQueryVEL = mBookedSlotQuery.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
mItems.clear();
mItemsKey.clear();
Log.d(TAG, "onDataChange");
for (DataSnapshot d : dataSnapshot.getChildren()) {
BookedSlot bookedSlot = d.getValue(BookedSlot.class);
Log.d(TAG, "bookedSlot:" + bookedSlot.getUserID());
mItems.add(bookedSlot);
mItemsKey.add(d.getKey());
}
updateUI();
/* TextView infoTextTextview = (TextView) getActivity().findViewById(R.id.info_text); //show_booked_slot.xml
if (mItems.isEmpty()) {
infoTextTextview.setText(R.string.Empty);
} else {
// infoTextTextview.setVisibility(View.GONE);
infoTextTextview.setText("Size: ".concat(Integer.toString(mItems.size())));
}*/
}
#Override
public void onCancelled(DatabaseError databaseError) {
Log.d(TAG, "show booked slot databaseError: " + databaseError);
}
});
}
else{
Log.d(TAG, "UID: "+UID);
}
super.onCreate(savedInstanceState);
}
#Override
public void onDestroy() {
super.onDestroy();
// if (mBookedSlotQuery != null) mBookedSlotRef.removeEventListener(mBookedSlotQueryVEL);
}
#Override
public void onDetach() {
super.onDetach();
// if (mBookedSlotQuery != null) mBookedSlotRef.removeEventListener(mBookedSlotQueryVEL);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_list_booked_slot, container, false);
mItemRecyclerView = (RecyclerView) view.findViewById(R.id.item_recycler_view); //in fragment_list_item_booked_slot.xml
DividerItemDecoration dividerItemDecoration = new DividerItemDecoration(mItemRecyclerView.getContext(), new LinearLayoutManager(getActivity()).getOrientation());
mItemRecyclerView.addItemDecoration(dividerItemDecoration);
mItemRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
return view;
}
private void updateUI() {
Log.d(TAG, "Enter updateUI(); mItems: " + mItems);
mAdapter = new ItemAdapter(mItems);
mItemRecyclerView.setAdapter(mAdapter);
}
private class ItemHolder extends RecyclerView.ViewHolder {
BookedSlot mItems;
TextView mNameTextView;
TextView mDateTextView;
TextView mTimeTextView;
ItemHolder(final View itemView) {
super(itemView);
//refer list_booked_gym_slot.xml
mNameTextView = (TextView) itemView.findViewById(R.id.textview_name);
mDateTextView = (TextView) itemView.findViewById(R.id.textview_date);
mTimeTextView = (TextView) itemView.findViewById(R.id.textview_time);
if (UID != null) {
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.d(TAG, "UID != null");
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder
.setMessage("Delete This Slot?")
.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
deleteSlot(mItems);
}
}).setNegativeButton(R.string.no, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// User cancelled the dialog
}
});
AlertDialog dialog = builder.create();
dialog.show();
}
});
}
}
void bindData(BookedSlot s){
mItems = s;
mNameTextView.setText(s.getUsername());
mDateTextView.setText(s.getBookedDate());
mTimeTextView.setText(s.getBookedTime());
}
}
private class ItemAdapter extends RecyclerView.Adapter<ItemHolder>{
private ArrayList<BookedSlot> mItems;
ItemAdapter(ArrayList<BookedSlot> Items){
this.mItems = Items;
}
#Override
public ItemHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater layoutInflater = LayoutInflater.from(getActivity());
View view = layoutInflater.inflate(R.layout.list_booked_gym_slot,parent,false);
return new ItemHolder(view);
}
#Override
public void onBindViewHolder(ItemHolder holder, int position) {
BookedSlot s = mItems.get(position);
holder.bindData(s);
}
#Override
public int getItemCount() {
return mItems.size();
}
}
private void deleteSlot(final BookedSlot itemClicked) {
mDatabase.child("booked_slot").child(UID).child(mItemsKey.get(mItems.indexOf(itemClicked))).removeValue(new DatabaseReference.CompletionListener() {
#Override
public void onComplete(DatabaseError databaseError, DatabaseReference databaseReference) {
if(databaseError == null){
Toast.makeText(getActivity(), itemClicked.getBookedDate() + " " + itemClicked.getBookedTime() +" Slot Deleted", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(getActivity(), "Something went wrong. Please try again later.", Toast.LENGTH_SHORT).show();
}
}
});
}
}
ShowBookedSlotActivity.xml
<?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:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.example.jaseline.myfyp.ShowBookedSlotActivity">
<android.support.design.widget.AppBarLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
</android.support.design.widget.AppBarLayout>
<TextView
android:id="#+id/info_text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingLeft="5dp"
android:paddingRight="5dp"
android:textSize="18sp" />
<RelativeLayout
android:id="#+id/fragmentContainer"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_behavior="#string/appbar_scrolling_view_behavior"
tools:context="com.example.jaseline.myfyp.ShowBookedSlotActivity"
tools:showIn="#layout/activity_show_booked_slot">
</RelativeLayout>
</LinearLayout>
fragment_list_booked_slot.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.RecyclerView
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/item_recycler_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:scrollbars="vertical">
</android.support.v7.widget.RecyclerView>
list_booked_slot.xml
<?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="wrap_content"
android:padding="5dp">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_marginLeft="10dp"
android:layout_marginStart="10dp"
android:orientation="vertical">
<TextView
android:id="#+id/textview_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="18sp"
android:textStyle="bold" />
<TextView
android:id="#+id/textview_date"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="14sp" />
<TextView
android:id="#+id/textview_time"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="14sp" />
</LinearLayout>
</RelativeLayout>
The Fragment Life Cycle is as follows :
1. constructor
2. onAttach
3. onCreate
4. onCreateView
So you cant call updateUI() method to set data to RecyclerView before setting LayoutManager.
Only after setting LayoutManager should you give data to RecyclerView
This is the code:
public class MainActivity extends Activity
{
private TextView textView2;
private Button button2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView2=(TextView)findViewById(R.id.textView1);
button2=(Button)findViewById(R.id.button1);
button2.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String url="http://stackoverflow.com/";
try{
Document doc=Jsoup.connect(url).get();
Elements elem=doc.select("meta[name=twitter:domain]");
String title1=elem.attr("content");
textView2.setText(title1);
}
catch(Exception e){
}
}
});
}}
This is the 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: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="com.example.jsouptest.MainActivity" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginTop="111dp"
android:text="TextView"
android:textSize="100dp" />
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/textView1"
android:layout_alignParentTop="true"
android:layout_marginLeft="22dp"
android:layout_marginTop="34dp"
android:text="Display" />
It isn't displaying the content in the textview on clicking the
button.
I have added permission for internet in the manifest file.
You can not call Network on main thread. You must call async task to make network calls. When you click on button execute a async task and then do your stuff there.
Below Code will Help:
public class MainActivity extends Activity {
TextView textView1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView1 = (TextView) findViewById(R.id.textView1);
Button b1 = (Button) findViewById(R.id.button1);
b1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
new GetStringTask().execute();
}
});
}
private class GetStringTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
String url = "http://stackoverflow.com/";
Document doc = null;
try {
doc = Jsoup.connect(url).get();
Elements elem = doc.getElementsByTag("title");
String title1 = elem.html();
return title1;
} catch (IOException e) {
e.printStackTrace();
return "Exception";
}
}
#Override
protected void onPostExecute(String title) {
textView1.setText(title);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
the code above sets the TextView label to "Stack Overflow".
AdMob view is not visible, but clickable. If call onResume() view become visible. When I use
AdMob library all work fine, but if use google play services for AdMob I got this issue.
My code is bellow.
protected void initAdMob(){
if (mAdView == null) {
mAdView = new AdView(MainActivity.this);
mAdView.setAdUnitId(getString(R.string.admob_id));
mAdView.setAdSize(AdSize.SMART_BANNER);
mAdView.loadAd(new AdRequest.Builder().build());
mAdView.setAdListener(new AdListener() {
#Override
public void onAdClosed() {
super.onAdClosed();
}
#Override
public void onAdFailedToLoad(int errorCode) {
super.onAdFailedToLoad(errorCode);
}
#Override
public void onAdLeftApplication() {
super.onAdLeftApplication();
}
#Override
public void onAdOpened() {
super.onAdOpened();
}
#Override
public void onAdLoaded() {
super.onAdLoaded();
}
});
}
}
private void showAdMob() {
initAdMob();
FrameLayout.LayoutParams params = new FrameLayout.LayoutParams( FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.WRAP_CONTENT);
params.gravity = Gravity.CENTER_HORIZONTAL;
mAdView.setLayoutParams(params);
FrameLayout fl = (FrameLayout) mainView.findViewById(R.id.adView);
if (fl != null) {
fl.removeAllViews();
fl.addView(mAdView, params);
}
}
#Override
public void onResume() {
if(mAdView != null){
mAdView.resume();
}
super.onResume();
}
view xml:
<FrameLayout
android:id="#+id/gameLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
<FrameLayout
android:id="#+id/adView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_alignParentBottom="true"/>
</RelativeLayout>
Need to use Mediation ID instead Publisher ID in AdMob