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".
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.
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();
}
}
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
Is there anyway of showing only my webview once loading has complete? at the moment i have a little webview Fragment on my homescreen but it takes a while to load.I want to show only once loading completes because at the moment its a white screen until loading completes.This does not look the greatest. I tried to add a progress bar but for some reason that does not work in my fragment either.
Ive tried to add the code posted as an answer but it makes no difference. i think its because it a fragment that im having the issues as the progress par works in my main activity webviews.
public class WebViewFragment extends Fragment {
WebView wv;
private String NEWS = "mywebsite goes here";
#Override
public void onSaveInstanceState(Bundle outState) {
wv.saveState(outState);
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Checks the orientation of the screen
if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
Toast.makeText(getContext(), "landscape", Toast.LENGTH_SHORT).show();
} else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) {
Toast.makeText(getContext(), "portrait", Toast.LENGTH_SHORT).show();
}
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final ProgressBar Pbar;
View view = inflater.inflate(R.layout.webviewfrag, null, false);
if (savedInstanceState == null) {
((WebView )view.findViewById(R.id.NewsFeedWbview)).restoreState(savedInstanceState);
wv = (WebView) view.findViewById(R.id.NewsFeedWbview);
wv.setScrollbarFadingEnabled(false);
Pbar = (ProgressBar) view.findViewById(R.id.pBwvf);
final TextView tv = (TextView) view.findViewById(R.id.tV69);
wv.setWebChromeClient(new WebChromeClient() {
public void onProgressChanged(WebView view, int progress) {
if (progress < 100 && Pbar.getVisibility() == ProgressBar.GONE) {
Pbar.setVisibility(ProgressBar.VISIBLE);
tv.setVisibility(View.VISIBLE);
}
Pbar.setProgress(progress);
if (progress == 100) {
Pbar.setVisibility(ProgressBar.GONE);
tv.setVisibility(View.GONE);
}
}
});
wv.getSettings().setJavaScriptEnabled(true);
wv.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
wv.getSettings().setRenderPriority(WebSettings.RenderPriority.HIGH);
wv.getSettings().setLoadsImagesAutomatically(true);
wv.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT);
if (Build.VERSION.SDK_INT >= 19) {
// chromium, enable hardware acceleration
wv.setLayerType(View.LAYER_TYPE_HARDWARE, null);
} else {
// older android version, disable hardware acceleration
wv.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
}
wv.canGoBackOrForward(5);
wv.getSettings().setLoadWithOverviewMode(true);
wv.getSettings().setUseWideViewPort(true);
wv.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
wv.setPadding(0, 0, 0, 0);
wv.loadUrl(NEWS);
}
return view;
}
}
Here my code:
Activity:
public class WebViewActivity extends Activity {
private WebView webView;
private EditText urlEditText;
private ProgressBar progress;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_web_view);
urlEditText = (EditText) findViewById(R.id.urlField);
webView = (WebView) findViewById(R.id.webView);
webView.setWebChromeClient(new MyWebViewClient());
progress = (ProgressBar) findViewById(R.id.progressBar);
progress.setMax(100);
Button openUrl = (Button) findViewById(R.id.goButton);
openUrl.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
String url = urlEditText.getText().toString();
if (validateUrl(url)) {
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl(url);
WebViewActivity.this.progress.setProgress(0);
}
}
private boolean validateUrl(String url) {
return true;
}
});
}
private class MyWebViewClient extends WebChromeClient {
#Override
public void onProgressChanged(WebView view, int newProgress) {
WebViewActivity.this.setValue(newProgress);
super.onProgressChanged(view, newProgress);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.web_view, menu);
return true;
}
public void setValue(int progress) {
this.progress.setProgress(progress);
}
}
Layout:
<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"
tools:context=".WebViewActivity" >
<LinearLayout
android:id="#+id/urlContainer"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<EditText
android:id="#+id/urlField"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="3"
android:hint="Enter URL to open" />
<Button
android:id="#+id/goButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Open" />
</LinearLayout>
<ProgressBar
android:id="#+id/progressBar"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="#id/urlContainer" />
<WebView
android:id="#+id/webView"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_below="#id/progressBar" />
</RelativeLayout>
Use below code
wv.setWebViewClient(new WebViewClient() {
public void onPageFinished(WebView view, String url) {
// do your stuff here
}
});
I'm trying to add a progress spinner at the top of my app while data is being received from the volley. There may be an easier way to do this but this is what i've tried so far only I have a few errors. The first error being newsListView getting the error 'varied is accessed from within inner class, needs to be declared final'. and the string values cannot be resolved. Here is the class I made within the oncreate method:
public class MainActivity extends AppCompatActivity {
private List<NewsRecord> newsListData = new ArrayList<NewsRecord>();
private GridView newsListView;
private NewsListAdapter adapter;
LinearLayout layout;
private ProgressDialog pDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
GridView newsListView = (GridView) findViewById(R.id.newsFeedList);
adapter = new NewsListAdapter(this, R.layout.adapter_news_list, newsListData, this);
layout = (LinearLayout) findViewById(R.id.progressbar_view);
newsListView.setAdapter(adapter);
pDialog = new ProgressDialog(this);
// Showing progress dialog before making http request
pDialog.setMessage("Loading Articles...");
pDialog.show();
newsListView.setOnItemClickListener(itemClicked);
nextStart = 0;
updateListData(nextStart, 20);
}
public int nextStart = 0;
public void updateListData(int StartPoint, int count){
String url = "http://www.efstratiou.info/projects/newsfeed/getList.php?start=" + StartPoint + "&count=" + count;
EDANewsApp app = EDANewsApp.getInstance();
JsonArrayRequest jsonRequest = new JsonArrayRequest(url, listener, errorListener);
app.requestQueue.add(jsonRequest);
nextStart +=count;
}
#Override
public boolean onCreateOptionsMenu (Menu menu){
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main_menu, menu);
return true;
}
#Override
public void onDestroy() {
super.onDestroy();
hidePDialog();
}
private void hidePDialog() {
if (pDialog != null) {
pDialog.dismiss();
pDialog = null;
}
}
public boolean onOptionsItemSelected(MenuItem item){
switch (item.getItemId()) {
case R.id.action_about:
Intent intent = new Intent(this, AboutActivity.class);
startActivity(intent);
return true;
case R.id.action_search:
return true;
case R.id.action_settings:
return true;
default:
return super.onOptionsItemSelected(item);
}
}
AdapterView.OnItemClickListener itemClicked = new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(MainActivity.this, NewsItemActivity.class);
intent.putExtra("newsItemId", newsListData.get(position).recordId);
startActivity(intent);
}
};
private SearchView.OnQueryTextListener searchQueryListener = new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
Intent searchIntent = new Intent(MainActivity.this, SearchResultsActivity.class);
searchIntent.putExtra("query", query);
return true;
}
#Override
public boolean onQueryTextChange(String newText) {
return false;
}
};
//Listeners
Response.Listener<JSONArray> listener = new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
//we successfully received the JSONArray
//Here we will extract the data and use it in our app
hidePDialog();
//Clear the dataset before loading new data
// newsListData.clear();
//Go through all the JSON objects
for (int i = 0; i < response.length(); i++) {
try {
//Get one JSON object
JSONObject jsonObj = response.getJSONObject(i);
//Put JSON data in a Java object
NewsRecord record = new NewsRecord();
record.recordId = jsonObj.getInt("record_id");
record.title = jsonObj.getString("title");
record.date = jsonObj.getString("date");
record.shortInfo = jsonObj.getString("short_info");
record.imageUrl = jsonObj.getString("image_url");
newsListData.add(record);
} catch (JSONException e) {
e.printStackTrace();
}
}
adapter.notifyDataSetChanged();
}
};
Response.ErrorListener errorListener = new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//There was an error in the communication
//We can notify the user about it
hidePDialog();
}
};
}
and the progress bar appears in the activity_main.xml like so:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/newsListItem"
android:layout_width="match_parent"
android:layout_height="wrap_content"
tools:context=".MainActivity">
<LinearLayout
android:id="#+id/progressbar_view"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:orientation="vertical" >
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:orientation="horizontal" >
<ProgressBar
style="?android:attr/progressBarStyle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical|center_horizontal" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical|center_horizontal"
android:text="Loading data..." />
</LinearLayout>
<View
android:layout_width="fill_parent"
android:layout_height="1dp"
android:background="#C0C0C0" />
</LinearLayout>
<GridView
android:id="#+id/newsFeedList"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:verticalSpacing="0dp"
android:horizontalSpacing="0dp"
android:stretchMode="columnWidth"
android:numColumns="2"/>
</FrameLayout>
Here is the way I often do in my projects, IMO you can take a look and apply to your project, hope it helps!
#Override
protected void onCreate(Bundle savedInstanceState) {
...
mRequestQueue = Volley.newRequestQueue(this);
mProgressBar = (ProgressBar) findViewById(R.id.progressBar);
mProgressBar.setVisibility(View.VISIBLE);
JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.GET, url, null, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
mProgressBar.setVisibility(View.INVISIBLE);
// do something...
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
mProgressBar.setVisibility(View.INVISIBLE);
// do something...
}
});
mRequestQueue.add(jsonArrayRequest);
...
}
you declare your progressbar
private ProgressDialog pDialog;
pDialog = new ProgressDialog(this);
// Showing progress dialog before making http request
pDialog.setMessage("Loading...");
pDialog.show();
you call you Volley request than when you get the response (either success or error event) you call the hidePDialog method
hidePDialog();
//method to hide progressbar
private void hidePDialog() {
if (pDialog != null) {
pDialog.dismiss();
pDialog = null;
}
}
don't forget to call the method in onDestroy() also
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
GridView newsListView = (GridView) findViewById(R.id.newsFeedList);
adapter = new NewsListAdapter(this, R.layout.adapter_news_list, newsListData, this);
layout = (LinearLayout) findViewById(R.id.progressbar_view);
newsListView.setAdapter(adapter);
newsListView.setOnItemClickListener(itemClicked);
EDANewsApp app = EDANewsApp.getInstance();
nextStart = 0;
updateListData(nextStart, 20);
}
private class Task extends AsyncTask<String, Integer, Boolean> {
private ProgressDialog dialog;
#Override
protected void onPreExecute() {
dialog.setMessage("Doing something, please wait.");
dialog.show();
layout.setVisibility(View.VISIBLE);
newsListView.setVisibility(View.GONE);
super.onPreExecute();
}
#Override
protected void onPostExecute(Boolean result) {
dialog.dismiss();
layout.setVisibility(View.GONE);
newsListView.setVisibility(View.VISIBLE);
adapter.notifyDataSetChanged();
super.onPostExecute(result);
}
#Override
protected Boolean doInBackground(String... params) {
stringValues.add("String 1");
stringValues.add("String 2");
stringValues.add("String 3");
stringValues.add("String 4");
stringValues.add("String 5");
try {
Thread.sleep(3000);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
Hope this will help you.