I am having trouble using the back button to go back in webview. I have 5 different fragments in a tab + swipe layout. Each having a different webview. I have my MainActivity.Java as well as a java file for each fragment. Using the examples shown in stackoverflow regarding this (can't link. Sorry) I get a force close whenever I press back on the app. So I received some helped and did a non-conventional stab at it but I get a couple of errors so I'm hoping one of you guys can help me out. I am super new to app development and java in general so please bear with me.
Here is my MainActivity.java where the errors are:
Code:
package com.-------;
import java.util.Locale;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.KeyEvent;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.webkit.WebSettings;
import android.webkit.WebViewFragment;
public class MainActivity extends FragmentActivity {
SectionsPagerAdapter mSectionsPagerAdapter;
ViewPager mViewPager;
[user=439709]@override[/user]
public void onBackPressed(){
mSectionsPagerAdapter.getLastFragment().tryGoBack(); [B]<-Error #1[/B]
}
[user=439709]@override[/user]
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
}
public class SectionsPagerAdapter extends FragmentPagerAdapter {
private WebViewFragment lastFragment;
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
public WebViewFragment getLastFragment() {
return lastFragment;
}
[user=439709]@override[/user]
public Fragment getItem(int position) {
WebViewFragment Fragment;
switch (position) {
case 0:
Fragment = new fragment1();
break;
case 1:
Fragment = new fragment2();
break;
case 2:
Fragment = new fragment3();
break;
case 3:
Fragment = new fragment4();
break;
case 4:
Fragment = new fragment5();
break;
default:
Fragment = null;
break;
}
lastFragment = Fragment;
return Fragment; [B]<-Error #2[/B]
}
[user=439709]@override[/user]
public int getCount() {
return 5;
}
[user=439709]@override[/user]
public CharSequence getPageTitle(int position) {
Locale l = Locale.getDefault();
switch (position) {
case 0:
return getString(R.string.tab1).toUpperCase(l);
case 1:
return getString(R.string.tab2).toUpperCase(l);
case 2:
return getString(R.string.tab3).toUpperCase(l);
case 3:
return getString(R.string.tab4).toUpperCase(l);
case 4:
return getString(R.string.tab5).toUpperCase(l);
}
return null;
}
}
}
Error #1 is in line 26 and says:
Code:
The method tryGoBack() is undefined for the type WebViewFragment
Error #2 is in line 80 and says
Code:
Type mismatch: cannot convert from WebViewFragment to Fragment
Here is one of my fragment java files as well:
fragment1.java
Code:
package com.-----;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.app.NavUtils;
import android.support.v4.view.ViewPager;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.view.Window;
import android.view.WindowManager;
import android.webkit.WebSettings;
import android.webkit.WebViewFragment;
public class fragment1 extends WebViewFragment {
public abstract class WebViewFragment extends Fragment{
public abstract void tryGoBack();
}
WebView myWebView;
[user=439709]@override[/user]
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View root = inflater.inflate(R.layout.fragment1, container, false);
myWebView = (WebView) root.findViewById(R.id.webview1);
myWebView.setWebViewClient(new WebViewClient());
myWebView.loadUrl("url");
return root;
}
}
Any help is greatly appreciated!
When dealing with two or different classes which all extend one of them, so in this case the WebViewFragment extending Fragment and your fragment1 inheriting from WebViewFragment, you can convert the object simply putting
Code:
(NewType)
in front of it. So for error 1, insert (Fragment1) and for error 2 insert (Fragment).
One advice I'd like to give you, Capitalize class names and don't capitalize object and variable names, so it should be Fragment1 (maybe a more clear name) and WebViewFragment fragment.
Related
Good evening everyone! I am working on learning some java and I have made it to the notepad tutorial and when I go to run it on the emulator, I am getting a few errors, and I'm hoping someone here may be able to help.
Code:
package com.a8a.todolist;
import java.util.ArrayList;
import android.app.Activity;
import android.os.Bundle;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.ArrayAdapter;
import android.view.View.OnClickListener;
public class ToDoList extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle icicle) {
//Inflat your view
setContentView(R.layout.main);
//Get references to UI widgets
ListView myListView = (ListView)findViewById(R.id.myListView);
final EditText myEditText = (EditText)findViewById(R.id.myEditText);
//Create the array list of to do items
final ArrayList<String> todoItems = new ArrayList<String>();
//Create the array adapter to bind the array to the listview
final ArrayAdapter<String> aa;
[B]aa = new ArayAdapter<String>(this, android.R.layout.simple_list_item_1,todoItems);[/B] [I]Multiple markers at this line - ArayAdapter cannot be resolved to a type - Line breakpoint:ToDoList [line: 27] - onCreate[/I]
(Bundle)
//Bind the arary adapter to the listview.
myListView.setAdapter(aa);
[B]myEditText.setOnKeyListener(new OnKeyListener() {[/B] [I]OnKeyListener cannot be resolved to a type[/I]
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_DOWN)
if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER)
{
todoItems.add(0, myEditText.getText().toString());
aa.notifyDataSetChanged();
myEditText.setText("");
return true;
}
return false;
}
});
}
}
The bolded text is whats getting the error and the italics are the error itself. Any help would be appreciated, if you are able to explain why the change needs to be made as well that would be much appreciated, so I can learn from my mistakes.
Thanks in advance!
ArayAdapter was miss-spelled ArrayAdapter
I was also missing an import for OnKeyListener (import android.view.View.OnKeyListener). If you don't import a class and try to use it, Java doesn't know what it is, so it tells you it doesn't recognize the type.
How would I go about saving the state of the rating of the stars when I click the button? I need it to save how many stars it has up when I reopen the app. Here is what I have so far...
package com.example.helloandroid;
import android.app.Activity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RatingBar;
import android.widget.RatingBar.OnRatingBarChangeListener;
import android.widget.TextView;
import android.widget.Toast;
public class HelloAndroid extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new OnClickListener()
{ public void onClick(View v)
{
Toast.makeText(HelloAndroid.this, "State saved", Toast.LENGTH_SHORT).show();
}});
final RatingBar ratingbar = (RatingBar) findViewById(R.id.ratingbar);
ratingbar.setOnRatingBarChangeListener(new OnRatingBarChangeListener() {
public void onRatingChanged(RatingBar ratingBar, float rating, boolean fromUser) {
Toast.makeText(HelloAndroid.this, "New Rating: " + rating, Toast.LENGTH_SHORT).show();
}
});
}
}
I would suggest http://developer.android.com/guide/topics/data/data-storage.html. I haven't used it yet but it should work for what you are doing.
I'm trying to update the text in my card view. I cannot figure out how to do it. I posted the code of my recyclerAdapter class below.
When a user clicks a card view it should update the text on the card view with a specified time.
Code:
package com.teamtreehouse.oslist;
import java.util.ArrayList;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.net.Uri;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.view.LayoutInflater;
import java.util.Calendar;
import android.content.Intent;
import java.text.SimpleDateFormat;
import java.util.Locale;
public class RecyclerAdapter extends RecyclerView.Adapter<FaucetHolder>
{
private ArrayList<Faucet> faucets;
private Context context;
private SharedPreferences sharedPref;
private String dateFormat = "h:mm a";
public RecyclerAdapter (ArrayList<Faucet> faucetsI,Context context) {
this.faucets = faucetsI;
this.context=context;
}
@Override
public FaucetHolder onCreateViewHolder(ViewGroup viewGroup, int i)
{
View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.card_view,viewGroup,false);
FaucetHolder f = new FaucetHolder(v);
return f;
}
@Override
public void onBindViewHolder(FaucetHolder f, int k)
{
final Faucet faucet = faucets.get(k);
f.titleText.setText(faucet.getName());
f.titleText.setOnClickListener(new View.OnClickListener() {
public void onClick(View btn) {
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(faucet.getLink()));
setRenewal(faucet);
context.startActivity(intent);
}
});
}
@Override
public int getItemCount()
{
return faucets.size();
}
private void setRenewal(Faucet g) {
sharedPref = context.getSharedPreferences("myPref",0);
SharedPreferences.Editor edit = sharedPref.edit();
Calendar c = Calendar.getInstance();
long current = c.getTimeInMillis();
long future = current + g.getLength();
c.setTimeInMillis(future);
SimpleDateFormat df = new SimpleDateFormat(dateFormat,Locale.US);
String date = df.format(c.getTime());
edit.putString(g.getSPName(),date);
}
private void updateText(FaucetHolder f, Faucet g) {
sharedPref = context.getSharedPreferences("myPref",0);
String updatedTime = sharedPref.getString(g.getSPName(), null);
f.timeText.setText(updatedTime);
}
}
The full error text would be helpful. If you haven't done it before you can quickly check if something is wrong with your views in the adapter bei commenting them out.
Bump
Sent from my LG-F350K using Tapatalk
Hey everyone. Here is my code below. I have everything working. Got it to display the pictures and text in a list view. Only issue is that I want to be able to click on one of the list items and have it open an activity. When I added that part in, I get an error that states,
"Error44, 45) error: no suitable constructor found for Intent(<anonymous OnItemClickListener>,Class)
constructor Intent.Intent(String,Uri) is not applicable
(argument mismatch; <anonymous OnItemClickListener> cannot be converted to String)
constructor Intent.Intent(Context,Class<?>) is not applicable
(argument mismatch; <anonymous OnItemClickListener> cannot be converted to Context)"
Here is my code:
Code:
package com.example.matt.nootropicahandbook;
import android.net.Uri;
import android.app.Activity;
import android.app.ListActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import android.content.Intent;
public class Biohack extends Activity
{
ListView list;
String[] itemname = {"Nootropics", "Supplements", "Metabolic Enhancement","Stacks", "Neuro Stimulation", "Diet", "Stay Away From",};
Integer[] imgid={R.drawable.piracetam1, R.drawable.piracetam2, R.drawable.piracetam3,
R.drawable.piracetam4, R.drawable.piracetam5, R.drawable.piracetam6, R.drawable.piracetam7,};
String[] classNames = {"Main", "Lifehack"};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_biohack);
biohacksAdapter adapter=new biohacksAdapter(this, itemname, imgid, classNames);
list=(ListView)findViewById(R.id.list);
list.setAdapter(adapter);
list.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// TODO Auto-generated method stub
String openClass = classNames[position];
try{
Class selected = Class.forName("com.example.matt.nootropicahandbook."+openClass);
Intent selectedIntent = new Intent(this, selected);
startActivity(selectedIntent);
}catch (ClassNotFoundException e)
{
e.printStackTrace();
}
}
});
}
}
The error is on the line:
Code:
Intent selectedIntent = new Intent(this, selected);
And here is my adapter class for refrence
Code:
package com.example.matt.nootropicahandbook;
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class biohacksAdapter extends ArrayAdapter<String>{
private final Activity context;
private final String[] itemname;
private final Integer[] imgid;
private final String[] classNames;
public biohacksAdapter(Activity context,String[] itemname, Integer[] imgid, String[] classNames) {
super(context,R.layout.custom_row, itemname);
this.context = context;
this.itemname = itemname;
this.imgid = imgid;
this.classNames = classNames;
}
public View getView(int position, View view, ViewGroup parent)
{
LayoutInflater inflater = context.getLayoutInflater();
View rowView = inflater.inflate(R.layout.custom_row, null, true);
TextView txtTitle = (TextView) rowView.findViewById(R.id.item);
ImageView imageView = (ImageView) rowView.findViewById(R.id.icon);
TextView extratxt = (TextView) rowView.findViewById(R.id.textView1);
txtTitle.setText(itemname[position]);
imageView.setImageResource(imgid[position]);
extratxt.setText("Description "+itemname[position]);
return rowView;
}
}
replace
Intent selectedIntent = new Intent(this, selected);
to
Intent selectedIntent = new Intent(Biohack.this, selected);
because ...
Hi Everyone! I was working on an app, which needed to give a remainder on a certain time, by triggering a notification. The app seemed to work fine on the emulator. But, the notification never shows up on a real phone.
The service which sends the broadcast.
Code:
package com.example.tanmay.yourdiary;
import android.annotation.TargetApi;
import android.app.IntentService;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.app.TaskStackBuilder;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.support.v4.app.NotificationCompat;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Log;
import java.text.SimpleDateFormat;
import java.util.Calendar;
/**
* Created by Tanmay on 22-01-2016.
*/
public class MyService extends IntentService {
public MyService() {
super("com.example.tanmay.yourdiary");
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
final Context context = this;
final Intent i = new Intent("com.example.tanmay.yourdiary.MyReceiver");
i.setAction("com.example.tanmay.yourdiary.MyReceiver");
new Thread(new Runnable(){
public void run(){
while(true){
Calendar c = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
String g="";
g=sdf.format(c.getTime());
Log.i("dd",g);
if(g.equals("05:23")){
Log.i("d3d",g);
LocalBroadcastManager.getInstance(context).sendBroadcast(i);
try {
Thread.sleep(24*60*60*1000);
stopSelf();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
try {
Thread.sleep(20000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
return START_STICKY;
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
protected void onHandleIntent(Intent intent) {
}
}
The receiver
Code:
package com.example.tanmay.yourdiary;
import android.annotation.TargetApi;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.TaskStackBuilder;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
public class MyReceiver extends BroadcastReceiver {
public MyReceiver() {
}
@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
@Override
public void onReceive(Context context, Intent intent) {
// TODO: This method is called when the BroadcastReceiver is receiving
// an Intent broadcast.
Log.i("dfdfg", "bc rec");
NotificationCompat.Builder builder = new NotificationCompat.Builder(context).setSmallIcon(R.drawable.ic_launcher).setContentTitle("Reminder").setContentText("Time to write your thoughts!");
TaskStackBuilder taskstackbuilder = TaskStackBuilder.create(context);
taskstackbuilder.addParentStack(MainActivity.class);
Intent i = new Intent(context,Writing.class);
taskstackbuilder.addNextIntent(i);
PendingIntent ip = taskstackbuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
builder.setContentIntent(ip);
NotificationManager manager = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
manager.notify(1,builder.build());
}
}
Try this code to see if it works on your phone or not
Code:
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(mContext)
.setSmallIcon(R.drawable.ic_launcher).setContentTitle("Title").setContentText("Description text");
Intent resultIntent = new Intent(mContext, MainActivity.class);
resultIntent.putExtra(AN_ADITIONAL_EXTRA, "User clicked on the notification");
// Because clicking the notification opens a new ("special") activity, there's no need to create an artificial back stack.
PendingIntent resultPendingIntent = PendingIntent.getActivity(mContext, 0, resultIntent, PendingIntent.FLAG_UPDATE_CURRENT);
mBuilder.setContentIntent(resultPendingIntent);
mBuilder.setAutoCancel(true);
// Sets an ID for the notification
int mNotificationId = 10; // give it an ID you recognize within your application
// Gets an instance of the NotificationManager service
NotificationManager mNotifyMgr = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
// Builds the notification and issues it.
mNotifyMgr.notify(mNotificationId, mBuilder.build());
And in your MainActivity.class under onNewIntent / onCreate
if(getIntent.getExtras() != null){
if(intent.hasExtra(AN_ADITIONAL_EXTRA)){
// User clicked on the notification, do something
}
}