I am new to Android programming, and have one question.
I am trying to access findViewById in my AsyncTask, but obviously, by default this will not be available, because I am not performing any actions against a View object.
I have found, a few articles, explaining how to solve this, but they are old, 5 years and up, and would like to know if this is still the correct approach? I am using android's data binding methodology, and this is supposed to replace findViewById calls, but I don't see how, in this scenario?
Is this way of solving still valid?
Here, is my code, in case there is a better solution. I am trying to access the progressbar in this view from within the AsyncTask
My Profile view:
<?xml version="1.0" encoding="utf-8"?>
<layout>
<data>
<variable name="user" type="Models.User" />
<variable name="viewActions" type="ViewModel.ProfileViewModel" />
</data>
<LinearLayout xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:gravity="center_horizontal|top">
<ProgressBar
android:id="#+id/progressPostUser"
android:layout_width="120dp"
android:layout_height="120dp"
android:visibility="gone"/>
<include layout="#layout/main_toolbar"/>
<ImageView
android:id="#+id/imagePlaceHolder"
android:layout_width="250dp"
android:layout_height="150dp"
android:layout_marginTop="20dp"
android:layout_marginBottom="5dp"
android:src="#mipmap/ic_account"/>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="10dp">
<ImageButton
android:id="#+id/btnOpenCamera"
android:layout_width="50dp"
android:layout_height="50dp"
android:layout_marginRight="10dp"
android:src="#mipmap/ic_account"
android:onClick="btnOpenCamper_OnClick"/>
<ImageButton
android:id="#+id/btnChooseImage"
android:layout_width="50dp"
android:layout_height="50dp"
android:src="#mipmap/ic_view_list"/>
</LinearLayout>
<EditText
android:layout_width="250dp"
android:layout_height="50dp"
android:hint="Name"
android:text="#={user._name}"/>
<EditText
android:layout_width="250dp"
android:layout_height="50dp"
android:hint="Surname"
android:text="#={user._surname}"/>
<EditText
android:layout_width="250dp"
android:layout_height="50dp"
android:hint="Email"
android:text="#={user._email}"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Save"
android:onClick="#{() -> viewActions.onSaveClicked(user)}"/>
</LinearLayout>
My Activity class:
public class ProfileActivity extends MenuActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ActivityProfileBinding binding = DataBindingUtil.setContentView(this, R.layout.activity_profile);
binding.setUser(new User());
binding.setViewActions(new ProfileViewModel(this));
//get the toolbar
Toolbar tb = (Toolbar)findViewById(R.id.toolbarMain);
setSupportActionBar(tb);
}
}
And the 'ViewModel' which handles events from the View.
public class ProfileViewModel {
private User mUser;
private Context mContext;
public ProfileViewModel(Context context){
mContext = context;
}
public void onSaveClicked(User user) {
String nameTest = user.get_name();
String surnameTest = user.get_surname();
Toast.makeText(mContext, user.get_name(), Toast.LENGTH_SHORT).show();
}
}
Here is my User class.
public class User extends BaseObservable {
public User() {
}
private String _name;
#Bindable
public String get_name() {
return _name;
}
public void set_name(String _name) {
this._name = _name;
notifyPropertyChanged(BR._name);
}
private String _surname;
#Bindable
public String get_surname() {
return _surname;
}
public void set_surname(String _surname) {
this._surname = _surname;
notifyPropertyChanged(BR._surname);
}
private String _email;
#Bindable
public String get_email() {
return _email;
}
public void set_email(String _email) {
this._email = _email;
notifyPropertyChanged(BR._email);
}
private Bitmap _profileImage;
public Bitmap get_profileImage() {
return _profileImage;
}
public void set_profileImage(Bitmap _profileImage) {
this._profileImage = _profileImage;
}
public String toJsonString(){
try{
JSONObject jObject = new JSONObject();
jObject.put("Name", get_name());
jObject.put("Surname", get_surname());
jObject.put("Email", get_email());
jObject.put("ProfileImage", Base64.encodeToString(convertBitmapToBytes(), Base64.DEFAULT));
} catch (Exception ex){
Log.d("Error", "User.toJson");
}
return "";
}
#Override
public String toString() {
return super.toString();
}
private byte[] convertBitmapToBytes(){
ByteArrayOutputStream stream = new ByteArrayOutputStream();
get_profileImage().compress(Bitmap.CompressFormat.PNG, 100, stream);
return stream.toByteArray();
}
}
You can do something like this. You can change information in the onPre, doInBackground, onPost --> This wouldnt matter much.
public class MainActivity extends AppCompatActivity {
TestView textView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = findViewById(R.id.textView);
}
private class ASyncCall extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
//What happens BEFORE everything in the background.
}
#Override
protected Void doInBackground(Void... arg0) {
textView.setText("set the text");
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
//After you get everything you need from the JSON.
}
}
}
I really did not like the idea of passing context, and the View around to different objects, and like to keep the view specific functionality within the activity class itself, so I implemented an interface, that I passed around, as follow:
Here is my interface:
public interface IProfiler {
void ShowProgressbar();
void HideProgressbar();
void MakeToast();
}
My activity class implements this interface, as follow:
public class ProfileActivity extends MenuActivity implements IProfiler {
private ProgressBar mProgressar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ActivityProfileBinding binding = DataBindingUtil.setContentView(this, R.layout.activity_profile);
binding.setUser(new User());
binding.setViewActions(new ProfileViewModel(this));
//get the toolbar
Toolbar tb = (Toolbar)findViewById(R.id.toolbarMain);
setSupportActionBar(tb);
//set the Progressbar
mProgressar = (ProgressBar)findViewById(R.id.progressPostUser);
}
#Override
public void ShowProgressbar() {
mProgressar.setVisibility(View.VISIBLE);
}
#Override
public void HideProgressbar() {
mProgressar.setVisibility(View.GONE);
}
#Override
public void MakeToast() {
Toast.makeText(this, "Some toast", Toast.LENGTH_SHORT);
}
}
My ProfileViewModel, which excepts the interface as parameter:
public class ProfileViewModel {
private User mUser;
private IProfiler mProfiler;
public ProfileViewModel(IProfiler profiler){
mProfiler = profiler;
}
public void onSaveClicked(User user) {
try {
String nameTest = user.get_name();
String surnameTest = user.get_surname();
new AsyncTaskPost(mProfiler).execute(new URL("http://www.Trackme.com"));
}
catch (Exception ex) {
}
}
}
And then finally, my AsyncTaskPost.
public class AsyncTaskPost extends AsyncTask<URL, Void, Void> {
private IProfiler mProfilerActions;
public AsyncTaskPost(IProfiler profilerActions){
mProfilerActions = profilerActions;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
mProfilerActions.ShowProgressbar();
}
#Override
protected Void doInBackground(URL... urls) {
try{
Thread.sleep(5000);
return null;
}
catch (Exception ex) {
return null;
}
}
#Override
protected void onPostExecute(Void aVoid) {
mProfilerActions.HideProgressbar();
mProfilerActions.MakeToast();
}
#Override
protected void onCancelled() {
super.onCancelled();
mProfilerActions.HideProgressbar();
}
}
Related
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.
This question already has answers here:
Create clickable link in text view in android
(2 answers)
Closed 2 years ago.
I'm trying to develop an Android application with Java. I need to separate all words in a text (bookText in code) and make them clickable. How can I do this? I will be grateful if you could help me. Thanks in advance.
public class BookActivity extends AppCompatActivity {
public static final String BOOK_TEXT = "com.example.altaybook.BOOK_TEXT";
BookViewModel bookViewModel;
private TextView bookTextView;
private String bookName;
private String bookText;
ProgressBar bookTextProgressBar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_book);
bookTextView = findViewById(R.id.book_text_id);
bookTextProgressBar = findViewById(R.id.bookTextProgressBar);
Intent intent = getIntent();
final int bookPosition = intent.getIntExtra(BOOK_TEXT, -1);
bookViewModel = new ViewModelProvider(this, ViewModelProvider.AndroidViewModelFactory.getInstance(this.getApplication())).get(BookViewModel.class);
bookViewModel.getAllBooks().observe(this, new Observer<List<Book>>() {
#Override
public void onChanged(List<Book> books) {
bookName = books.get(bookPosition).getName();
setTitle(bookName);
bookText = books.get(bookPosition).getText();
SetTextAsyncTask setTextAsyncTask = new SetTextAsyncTask();
setTextAsyncTask.execute();
bookTextView.setMovementMethod(LinkMovementMethod.getInstance());
}
});
}
public class SetTextAsyncTask extends AsyncTask<String, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
bookTextProgressBar.setVisibility(View.VISIBLE);
}
#Override
protected Void doInBackground(String... strings) {
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
bookTextView.setText(bookText);
bookTextProgressBar.setVisibility(View.GONE);
}
}
}
You can use LinearLayout. Here is an example:
activity_book.xml
<?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="vertical"
android:gravity="center">
<LinearLayout
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:orientation="horizontal"
android:gravity="center"
android:id="#+id/container"/>
</LinearLayout>
BookActivity.java
public class BookActivity extends Activity
{
public static final String BOOK_TEXT = "com.example.altaybook.BOOK_TEXT";
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_book);
LinearLayout ll = findViewById(R.id.container);
String[] splitText = BOOK_TEXT.split("\\.");
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
for(int i=0; i < splitText.length; i++) {
TextView content = new TextView(this);
if(i == 0) { content.setText(splitText[i]);
} else { content.setText("." + splitText[i]); }
content.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(BookActivity.this, "You clicked: " + ((TextView)view).getText(), Toast.LENGTH_SHORT).show();
}
});
ll.addView(content, params);
}
}
}
I have an interface implemented in MainActivity, and inside that callback method i want to update my TextView but i am getting nullpointer exception.
This is my MainActivity class
public class MainActivity extends AppCompatActivity implements GenericCallback
{
Context mcontext;
TextView tv;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mcontext = this;
Button btn = findViewById(R.id.btn);
tv = findViewById(R.id.tv);
btn.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
startActivity(new Intent(MainActivity.this,SecondActivity.class));
}
});
}
#Override
public void doSomething(Context context, String... a)
{
Toast.makeText(context,"Calback"+a[0]+a[1],Toast.LENGTH_SHORT).show();
tv = findViewById(R.id.tv);//Line 43
tv.setText(a[0]+a[1]);
}
My interface looks like this
public interface GenericCallback
{
void doSomething(Context context, String... a);
}
My SecomdActivity
public class SecondActivity extends AppCompatActivity
{
Context context;
GenericCallback genericCallback = new MainActivity();
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
context = this;
String a="Secomd",b = "Activity";
genericCallback.doSomething(context,a,b);
finish();
}
}
StackTrace
Caused by: java.lang.NullPointerException: Attempt to invoke virtual
method 'android.view.Window$Callback
android.view.Window.getCallback()' on a null object reference
at android.support.v7.app.AppCompatDelegateImplBase.(AppCompatDelegateImplBase.java:117)
at android.support.v7.app.AppCompatDelegateImplV9.(AppCompatDelegateImplV9.java:149)
at android.support.v7.app.AppCompatDelegateImplV14.(AppCompatDelegateImplV14.java:56)
at android.support.v7.app.AppCompatDelegateImplV23.(AppCompatDelegateImplV23.java:31)
at android.support.v7.app.AppCompatDelegate.create(AppCompatDelegate.java:200)
at android.support.v7.app.AppCompatDelegate.create(AppCompatDelegate.java:183)
at android.support.v7.app.AppCompatActivity.getDelegate(AppCompatActivity.java:519)
at android.support.v7.app.AppCompatActivity.findViewById(AppCompatActivity.java:190)
at android.com.callback.MainActivity.doSomething(MainActivity.java:43)
at android.com.callback.SecondActivity.onCreate(SecondActivity.java:21)
I already know what is nullpointer, I already referred this and this
You can use EventBus Library
For installation
compile 'org.greenrobot:eventbus:3.1.1'
First, create a Java class
public class MsgEvent {
String oo;
public String getOo() {
return oo;
}
public void setOo(String oo) {
this.oo = oo;
}
}
Then in SecondActivity
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
context = this;
String a="Secomd",b = "Activity";
MsgEvent msgEvent = new MsgEvnet();
msgEvent.setOo(a);
EventBus.getDefault().post(msgEvent);
finish();
}
Then in MainActivity
#Override
public void onStart() {
super.onStart();
EventBus.getDefault().register(this);
}
#Override
public void onStop() {
super.onStop();
EventBus.getDefault().unregister(this);
}
#Subscribe(threadMode = ThreadMode.MAIN)
public void onMessageEvent(MsgEvent event) {
String value = event.getOo();
}
You can use BroadcastReceiver
check the below example
MainActivity
public class MainActivity extends AppCompatActivity {
TextView mTitle;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTitle = findViewById(R.id.toolbar_title);
startActivity(new Intent(this, SecondActivity.class));
}
private BroadcastReceiver myBroadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
mTitle.setText(intent.getStringExtra("DATA"));
Toast.makeText(context, "recieved text : " + intent.getStringExtra("DATA"), Toast.LENGTH_SHORT).show();
}
};
#Override
protected void onResume() {
IntentFilter filter = new IntentFilter();
filter.addAction("MY_ACTION");
registerReceiver(myBroadcastReceiver, filter);
super.onResume();
}
#Override
protected void onPause() {
super.onPause();
}
}
XML form MainActivity
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/toolbarIcon"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:orientation="vertical">
<TextView
android:id="#+id/toolbar_title"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="50dp"
android:text="Nilesh"
android:textStyle="bold" />
</LinearLayout>
Second_activity
public class SecondActivity extends AppCompatActivity {
TextView tvText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
getSupportActionBar().setTitle("SECOND Activity");
tvText = findViewById(R.id.tvText);
tvText.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
sendBroadcast();
}
});
}
public void sendBroadcast() {
Intent broadcast = new Intent();
broadcast.putExtra("DATA", "MY NAME IS NILESH");
broadcast.setAction("MY_ACTION");
sendBroadcast(broadcast);
}
}
LAYOUT for second activity
<?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"
tools:context=".SecondActivity">
<TextView
android:layout_width="match_parent"
android:id="#+id/tvText"
android:text="Click to Send Broadcas"
android:layout_height="wrap_content" />
</LinearLayout>
The reason you are getting that null exception is that your MainActivity view is not inflated because it is not instantiated by the framework.
You can create an instance getter method from your first activity.
private static GenericCallback instance;
public static GenericCallback getHandler() {
return instance;
}
#Override
protected void onCreate(Bundle savedInstanceState)
{
...
instance = this;
...
}
And then on your 2nd activity, get that instance instead of instantiating an activity.
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
context = this;
String a="Secomd",b = "Activity";
GenericCallback genericCallback = MainActivity.getHandler();
genericCallback.doSomething(context,a,b);
finish();
}
I am trying to display a camera on in my android app, but all I am getting is a black box where the SurfaceView is located.
I am using this simple XML layout:
<?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="com.lazylayer.photoshoot.MainActivity">
<SurfaceView
android:id="#+id/surface_view"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
With this Activity:
public class MainActivity extends AppCompatActivity implements SurfaceHolder.Callback {
SurfaceView surfaceView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
surfaceView = (SurfaceView)findViewById(R.id.surface_view);
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
try{
CameraManager cameraManager = (CameraManager)getSystemService(Context.CAMERA_SERVICE);
String[] cameras = cameraManager.getCameraIdList();
cameraManager.openCamera(cameras[0], deviceCallback, null);
} catch (CameraAccessException e) {
e.printStackTrace();
}
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {}
CameraDevice.StateCallback deviceCallback = new CameraDevice.StateCallback() {
#Override
public void onOpened(CameraDevice camera) {
try {
List<Surface> surfaceList = Collections.singletonList(surfaceView.getHolder().getSurface());
camera.createCaptureSession(surfaceList, sessionCallback, null);
} catch (CameraAccessException e) {
e.printStackTrace();
}
}
#Override
public void onDisconnected(CameraDevice camera) {}
#Override
public void onError(CameraDevice camera, int error) {}
};
CameraCaptureSession.StateCallback sessionCallback = new CameraCaptureSession.StateCallback() {
#Override
public void onConfigured(CameraCaptureSession session) {
}
#Override
public void onConfigureFailed(CameraCaptureSession session) {}
};
}
Here is what gets displayed when the app is ran on my phone:
I was able to fix the issue by using a FrameLayout instead of a SurfaceView
<FrameLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/camera_view">
</FrameLayout>
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".