Load layout in fragment - Java for Android App Development

Hi guys. I've a problem woth fragment and layout. here is the code that give me error
MainActivity (I use onClick to load new fragment)
Code:
package com.croccio.bicimi4social.activity;
import org.holoeverywhere.ArrayAdapter;
import org.holoeverywhere.app.Activity;
import org.holoeverywhere.app.Fragment;
import org.holoeverywhere.widget.ListView;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.util.Log;
import android.view.View;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuInflater;
import com.actionbarsherlock.view.MenuItem;
import com.croccio.bicimi4social.Bicimi4Social;
import com.croccio.bicimi4social.R;
import com.croccio.bicimi4social.Utility.InternetConnection;
import com.croccio.bicimi4social.bikeSharing.BikeSharing;
import com.croccio.bicimi4social.fragment.FragmentGestionePostazioni;
import com.parse.Parse;
import com.parse.ParseAnalytics;
import com.sherlock.navigationdrawer.compat.SherlockActionBarDrawerToggle;
public class MainActivity extends Activity {
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;
private SherlockActionBarDrawerToggle mDrawerToggle;
private CharSequence mDrawerTitle;
private CharSequence mTitle;
private String[] mTitles;
private InternetConnection ic;
[user=439709]@override[/user]
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Bicimi4Social.bikeSharing=new BikeSharing(getSupportApplication());
ic = new InternetConnection(this);
ic.run();
Parse.initialize(this, "RxyJKRsDhoO7uwzfToILxNB7lMeLsSHXfrnpZ7sq", "6o3pJSeVXjF13MK7ZvLekPOdtj6RJMMHpEqM80cH");
ParseAnalytics.trackAppOpened(getIntent());
mTitle = mDrawerTitle = getTitle();
mTitles = getResources().getStringArray(R.array.sliding_menu_option);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.left_drawer);
// set a custom shadow that overlays the main content when the drawer opens
mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
// set up the drawer's list view with items and click listener
mDrawerList.setAdapter(new ArrayAdapter<String>(this,
R.layout.drawer_list_item, mTitles));
mDrawerList.setOnItemClickListener(new DrawerItemClickListener());
// enable ActionBar app icon to behave as action to toggle nav drawer
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
// ActionBarDrawerToggle ties together the the proper interactions
// between the sliding drawer and the action bar app icon
mDrawerToggle = new SherlockActionBarDrawerToggle(
this, /* host Activity */
mDrawerLayout, /* DrawerLayout object */
R.drawable.ic_drawer, /* nav drawer image to replace 'Up' caret */
R.string.drawer_open, /* "open drawer" description for accessibility */
R.string.drawer_close /* "close drawer" description for accessibility */
) {
public void onDrawerClosed(View view) {
getSupportActionBar().setTitle(mTitle);
//invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
public void onDrawerOpened(View drawerView) {
getSupportActionBar().setTitle(mDrawerTitle);
//invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()
}
};
mDrawerLayout.setDrawerListener(mDrawerToggle);
if (savedInstanceState == null) {
selectItem(0);
}
}
[user=439709]@override[/user]
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
ic.setRunning(false);
}
[user=439709]@override[/user]
protected void onResume() {
// TODO Auto-generated method stub
Log.e("MAIN ACTIVITY", "ONRESUME");
ic.setRunning(true);
ic.run();
super.onResume();
}
[user=439709]@override[/user]
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getSupportMenuInflater();
inflater.inflate(R.menu.main, menu);
return super.onCreateOptionsMenu(menu);
}
/* Called whenever we call invalidateOptionsMenu() */
[user=439709]@override[/user]
public boolean onPrepareOptionsMenu(Menu menu) {
// If the nav drawer is open, hide action items related to the content view
boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
// menu.findItem(R.id.action_websearch).setVisible(!drawerOpen);
return super.onPrepareOptionsMenu(menu);
}
[user=439709]@override[/user]
public boolean onOptionsItemSelected(MenuItem item) {
// The action bar home/up action should open or close the drawer.
// ActionBarDrawerToggle will take care of this.
if (mDrawerToggle.onOptionsItemSelected(item)) {
return true;
}
// Handle action buttons
switch(item.getItemId()) {
// case R.id.action_websearch:
// // create intent to perform web search for this planet
// Intent intent = new Intent(Intent.ACTION_WEB_SEARCH);
// intent.putExtra(SearchManager.QUERY, getActionBar().getTitle());
// // catch event that there's no activity to handle intent
// if (intent.resolveActivity(getPackageManager()) != null) {
// startActivity(intent);
// } else {
// Toast.makeText(this, R.string.app_not_available, Toast.LENGTH_LONG).show();
// }
// return true;
default:
return super.onOptionsItemSelected(item);
}
}
/* The click listner for ListView in the navigation drawer */
private class DrawerItemClickListener implements ListView.OnItemClickListener {
[user=439709]@override[/user]
public void onItemClick(android.widget.AdapterView<?> parent, View view, int position, long id) {
selectItem(position);
switch (position) {
case 0:
// update the main content by replacing fragments
Fragment fragment = new FragmentGestionePostazioni();
FragmentManager fragmentManager = getSupportFragmentManager();
fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).commit();
break;
default:
break;
}
}
}
private void selectItem(int position) {
// update selected item and title, then close the drawer
mDrawerList.setItemChecked(position, true);
setTitle(mTitles[position]);
mDrawerLayout.closeDrawer(mDrawerList);
}
[user=439709]@override[/user]
public void setTitle(CharSequence title) {
mTitle = title;
getSupportActionBar().setTitle(mTitle);
}
/**
* When using the ActionBarDrawerToggle, you must call it during
* onPostCreate() and onConfigurationChanged()...
*/
[user=439709]@override[/user]
protected void onPostCreate(Bundle savedInstanceState) {
super.onPostCreate(savedInstanceState);
// Sync the toggle state after onRestoreInstanceState has occurred.
mDrawerToggle.syncState();
}
[user=439709]@override[/user]
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Pass any configuration change to the drawer toggls
mDrawerToggle.onConfigurationChanged(newConfig);
}
}
here is fragment code
Code:
package com.croccio.bicimi4social.fragment;
import org.holoeverywhere.LayoutInflater;
import org.holoeverywhere.app.Fragment;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.ViewGroup;
import com.croccio.bicimi4social.R;
import com.croccio.bicimi4social.bikeSharing.BikeSharing;
import com.tjerkw.slideexpandable.library.ActionSlideExpandableListView;
public class FragmentGestionePostazioni extends Fragment {
ActionSlideExpandableListView list;
BikeSharing bikeSharing;
Handler handler;
int click=0;
[user=439709]@override[/user]
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View root = inflater.inflate(
R.layout.gestione_postazioni, container, false);
root.setLayoutParams(new ViewGroup.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT));
root.setBackgroundResource(org.holoeverywhere.R.color.background_light);
return root;
}
[user=439709]@override[/user]
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
}
here is the layout for fragment
Code:
<android.support.v4.widget.SlidingPaneLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:map="http://schemas.android.com/apk/res-auto"
android:id="@+id/slidingpanelayout"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<fragment
android:id="@+id/fragmentGestionePostazioniElenco"
android:name="com.croccio.bicimi4social.fragment.FragmentGestionePostazioniElenco"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@android:color/background_light" />
<fragment
android:id="@+id/fragmentGestionePostazioniMappe"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
map:cameraTargetLat="45.46545420"
map:cameraTargetLng="9.186515999999999"
map:cameraZoom="10"
map:mapType="normal"
map:uiRotateGestures="true"
map:uiScrollGestures="true"
map:uiTiltGestures="true"
map:uiZoomControls="false"
map:uiZoomGestures="true" />
</android.support.v4.widget.SlidingPaneLayout>
here is the logcat error
Code:
06-03 11:41:43.936: E/AndroidRuntime(19159): FATAL EXCEPTION: main
06-03 11:41:43.936: E/AndroidRuntime(19159): android.view.InflateException: Binary XML file line #7: Error inflating class fragment
06-03 11:41:43.936: E/AndroidRuntime(19159): at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:704)
06-03 11:41:43.936: E/AndroidRuntime(19159): at android.view.LayoutInflater.rInflate(LayoutInflater.java:746)
06-03 11:41:43.936: E/AndroidRuntime(19159): at android.view.LayoutInflater.inflate(LayoutInflater.java:489)
06-03 11:41:43.936: E/AndroidRuntime(19159): at org.holoeverywhere.LayoutInflater.inflate(LayoutInflater.java:242)
06-03 11:41:43.936: E/AndroidRuntime(19159): at android.view.LayoutInflater.inflate(LayoutInflater.java:396)
06-03 11:41:43.936: E/AndroidRuntime(19159): at org.holoeverywhere.LayoutInflater.inflate(LayoutInflater.java:227)
06-03 11:41:43.936: E/AndroidRuntime(19159): at com.croccio.bicimi4social.fragment.FragmentGestionePostazioni.onCreateView(FragmentGestionePostazioni.java:24)
06-03 11:41:43.936: E/AndroidRuntime(19159): at android.support.v4.app._HoloFragment.onCreateView(_HoloFragment.java:214)
06-03 11:41:43.936: E/AndroidRuntime(19159): at android.support.v4.app.Fragment.performCreateView(Fragment.java:1460)
06-03 11:41:43.936: E/AndroidRuntime(19159): at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:911)
06-03 11:41:43.936: E/AndroidRuntime(19159): at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1088)
06-03 11:41:43.936: E/AndroidRuntime(19159): at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:682)
06-03 11:41:43.936: E/AndroidRuntime(19159): at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1444)
06-03 11:41:43.936: E/AndroidRuntime(19159): at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:429)
06-03 11:41:43.936: E/AndroidRuntime(19159): at android.os.Handler.handleCallback(Handler.java:725)
06-03 11:41:43.936: E/AndroidRuntime(19159): at android.os.Handler.dispatchMessage(Handler.java:92)
06-03 11:41:43.936: E/AndroidRuntime(19159): at android.os.Looper.loop(Looper.java:137)
06-03 11:41:43.936: E/AndroidRuntime(19159): at android.app.ActivityThread.main(ActivityThread.java:5229)
06-03 11:41:43.936: E/AndroidRuntime(19159): at java.lang.reflect.Method.invokeNative(Native Method)
06-03 11:41:43.936: E/AndroidRuntime(19159): at java.lang.reflect.Method.invoke(Method.java:525)
06-03 11:41:43.936: E/AndroidRuntime(19159): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:799)
06-03 11:41:43.936: E/AndroidRuntime(19159): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:566)
06-03 11:41:43.936: E/AndroidRuntime(19159): at dalvik.system.NativeStart.main(Native Method)
06-03 11:41:43.936: E/AndroidRuntime(19159): Caused by: java.lang.ClassCastException: com.croccio.bicimi4social.fragment.FragmentGestionePostazioniElenco cannot be cast to android.app.Fragment
06-03 11:41:43.936: E/AndroidRuntime(19159): at android.app.Fragment.instantiate(Fragment.java:585)
06-03 11:41:43.936: E/AndroidRuntime(19159): at android.app.Fragment.instantiate(Fragment.java:560)
06-03 11:41:43.936: E/AndroidRuntime(19159): at android.app.Activity.onCreateView(Activity.java:4717)
06-03 11:41:43.936: E/AndroidRuntime(19159): at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:680)
06-03 11:41:43.936: E/AndroidRuntime(19159): ... 22 more

croccio said:
Hi guys. I've a problem woth fragment and layout. here is the code that give me error
Click to expand...
Click to collapse
This logcat line is interesting:
Code:
Caused by: java.lang.ClassCastException: com.croccio.bicimi4social.fragment.FragmentGestionePostazioniElenco cannot be cast to android.app.Fragment
I can think of two solutions:
1) Make sure your Fragment is a android.support.v4.app.Fragment and not a regular Fragment.
You'll have to add
Code:
import android.support.v4.app.Fragment;
to the FragmentGestionePostazioni file.
2) Try making your main Activity a FragmentActivity - change 'extends Activity' to 'extends FragmentActivity'
Hope that helps!

Alkonic said:
This logcat line is interesting:
Code:
Caused by: java.lang.ClassCastException: com.croccio.bicimi4social.fragment.FragmentGestionePostazioniElenco cannot be cast to android.app.Fragment
I can think of two solutions:
1) Make sure your Fragment is a android.support.v4.app.Fragment and not a regular Fragment.
You'll have to add
Code:
import android.support.v4.app.Fragment;
to the FragmentGestionePostazioni file.
2) Try making your main Activity a FragmentActivity - change 'extends Activity' to 'extends FragmentActivity'
Hope that helps!
Click to expand...
Click to collapse
thank you. i've used holo fragment and as i can't resolve the problem i changed layout and now it works. Thank you for your answer

Related

Need help with a title menu

Hey everyone,
I'm working on a minesweeper-like game for my independent project in school this semester, but I'm running into a but of trouble with the title screen. What I'm trying to do is have a seperate activity launch for MainGame.java and Options.java when their respective buttons are clicked. When I click on Start, it launches the MainGame activity, but whenever I click on Options the app force closes. It's really weird because I'm doing essentially the same thing with both buttons. Here's the code for Title.java, let me know if you need to see anything else:
Code:
package com.freekyfrogy.treasure;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class Title extends Activity implements OnClickListener {
Button buttonStart, buttonScores, buttonOptions, buttonExit;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.title);
buttonStart = (Button) findViewById(R.id.buttonStart);
buttonStart.setOnClickListener(this);
buttonScores = (Button) findViewById(R.id.buttonScores);
buttonScores.setOnClickListener(this);
buttonOptions = (Button) findViewById(R.id.buttonOptions);
buttonOptions.setOnClickListener(this);
buttonExit = (Button) findViewById(R.id.buttonExit);
buttonExit.setOnClickListener(this);
}
public void onClick(View v) {
switch(v.getId()){
case R.id.buttonStart:
if(buttonStart.isPressed()){
startActivity(new Intent(getApplicationContext(),MainGame.class));
}
break;
case R.id.buttonScores:
if(buttonScores.isPressed()){
Toast.makeText(this, R.string.toastComingSoon, Toast.LENGTH_SHORT).show();
}
break;
case R.id.buttonOptions:
if(buttonOptions.isPressed()){
startActivity(new Intent(getApplicationContext(), Options.class));
}
break;
case R.id.buttonExit:
if(buttonExit.isPressed()){
finish();
}
break;
}
}
}
If i had to guess id say you didnt declare both activities in your manifest...
what does the debugger say is the problem?
I declared them both in the manifest, here's it's XML code:
Code:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.freekyfrogy.treasure"
android:versionCode="1"
android:versionName="1.0">
<uses-sdk android:minSdkVersion="4" />
<application android:icon="@drawable/icon" android:label="@string/app_name" android:theme="@android:style/Theme.NoTitleBar">
<activity android:name="Title"
android:label="@string/app_name"
android:screenOrientation="portrait">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name="MainGame"
android:screenOrientation="portrait">
</activity>
<activity android:name="Options"
android:screenOrientation="portrait">
</activity>
</application>
</manifest>
and the Error I'm getting is this:
Code:
02-28 16:57:54.086: ERROR/AndroidRuntime(17450): FATAL EXCEPTION: main
02-28 16:57:54.086: ERROR/AndroidRuntime(17450): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.freekyfrogy.treasure/com.freekyfrogy.treasure.Options}: java.lang.NullPointerException
02-28 16:57:54.086: ERROR/AndroidRuntime(17450): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1664)
02-28 16:57:54.086: ERROR/AndroidRuntime(17450): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1768)
02-28 16:57:54.086: ERROR/AndroidRuntime(17450): at android.app.ActivityThread.access$1500(ActivityThread.java:123)
02-28 16:57:54.086: ERROR/AndroidRuntime(17450): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:936)
02-28 16:57:54.086: ERROR/AndroidRuntime(17450): at android.os.Handler.dispatchMessage(Handler.java:99)
02-28 16:57:54.086: ERROR/AndroidRuntime(17450): at android.os.Looper.loop(Looper.java:123)
02-28 16:57:54.086: ERROR/AndroidRuntime(17450): at android.app.ActivityThread.main(ActivityThread.java:3812)
02-28 16:57:54.086: ERROR/AndroidRuntime(17450): at java.lang.reflect.Method.invokeNative(Native Method)
02-28 16:57:54.086: ERROR/AndroidRuntime(17450): at java.lang.reflect.Method.invoke(Method.java:507)
02-28 16:57:54.086: ERROR/AndroidRuntime(17450): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:841)
02-28 16:57:54.086: ERROR/AndroidRuntime(17450): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:599)
02-28 16:57:54.086: ERROR/AndroidRuntime(17450): at dalvik.system.NativeStart.main(Native Method)
02-28 16:57:54.086: ERROR/AndroidRuntime(17450): Caused by: java.lang.NullPointerException
02-28 16:57:54.086: ERROR/AndroidRuntime(17450): at android.app.Activity.findViewById(Activity.java:1647)
02-28 16:57:54.086: ERROR/AndroidRuntime(17450): at com.freekyfrogy.treasure.Options.<init>(Options.java:16)
02-28 16:57:54.086: ERROR/AndroidRuntime(17450): at java.lang.Class.newInstanceImpl(Native Method)
02-28 16:57:54.086: ERROR/AndroidRuntime(17450): at java.lang.Class.newInstance(Class.java:1409)
02-28 16:57:54.086: ERROR/AndroidRuntime(17450): at android.app.Instrumentation.newActivity(Instrumentation.java:1021)
02-28 16:57:54.086: ERROR/AndroidRuntime(17450): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1656)
02-28 16:57:54.086: ERROR/AndroidRuntime(17450): ... 11 more
Can you post your Options class? It looks to me like there may be something wrong in there.
Options class:
Code:
package com.freekyfrogy.treasure;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class Options extends Activity implements OnClickListener {
int intX = 5;
int intY = 5;
EditText sizeX = (EditText) findViewById(R.id.editX);
EditText sizeY = (EditText) findViewById(R.id.editY);
Button setXY = (Button) findViewById(R.id.setXY);
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.options);
setXY.setOnClickListener(this);
}
public void onClick(View v) {
String strX = sizeX.getText().toString();
String strY = sizeY.getText().toString();
intX = Integer.parseInt(strX);
intY = Integer.parseInt(strY);
Toast.makeText(this, "this is a toast: "+ intX+ " "+ intY, Toast.LENGTH_SHORT).show();
}
}
Hi freekyfrogy,
you should declare there controls of in onCreate method of Options activity
EditText sizeX = (EditText) findViewById(R.id.editX);
EditText sizeY = (EditText) findViewById(R.id.editY);
Button setXY = (Button) findViewById(R.id.setXY);
your option activity code look like this:
package com.freekyfrogy.treasure;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class Options extends Activity implements OnClickListener {
int intX = 5;
int intY = 5;
Button setXY = (Button) findViewById(R.id.setXY);
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.options);
EditText sizeX = (EditText) findViewById(R.id.editX);
EditText sizeY = (EditText) findViewById(R.id.editY);
setXY.setOnClickListener(this);
}
public void onClick(View v) {
String strX = sizeX.getText().toString();
String strY = sizeY.getText().toString();
intX = Integer.parseInt(strX);
intY = Integer.parseInt(strY);
Toast.makeText(this, "this is a toast: "+ intX+ " "+ intY, Toast.LENGTH_SHORT).show();
}
}
Oh I see now!!! Thanks so much, now it's not force closing haha

[Q] What is wrong with my project?

Hi all, I'm fairly new to Java and my overall coding skills are not as advanced as I'd like them to be but I really would appreciate it if someone could help me with this problem.
My first goal is to code an application for Android which measures the acceleration (X, Y, Z directions) and displays the values in a TextView.
There will be other user configurable options like unit conversion or limits with audio warnings etc. later on.
Right now I only have a few lines of code and the application already force closes right after starting.
I am posting my MainActivity.java, my activity_main.xml and the sensoractivity2 Manifest. Please point me in the right direction!
MainActivity.java:
Code:
package com.example.sensoractivity2;
import android.app.Activity;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.widget.TextView;
public class MainActivity extends Activity implements SensorEventListener{
private SensorManager sensorManager;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
sensorManager=(SensorManager) getSystemService(SENSOR_SERVICE);
sensorManager.registerListener(this, sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_NORMAL);
}
public void onSensorChanged(SensorEvent event) {
float x, y, z = 0;
if (event.sensor.getType()==Sensor.TYPE_ACCELEROMETER) {
x=event.values[0];
y=event.values[1];
z=event.values[2];
TextView tx = (TextView) findViewById(R.id.textView1);
tx.setText((int) x);
TextView ty = (TextView) findViewById(R.id.textView2);
ty.setText((int) y);
TextView tz = (TextView) findViewById(R.id.textView3);
tz.setText((int) z);
}
}
[user=439709]@override[/user]
public void onAccuracyChanged(Sensor arg0, int arg1) {
// TODO Auto-generated method stub
}
}
activity_main.xml
Code:
<?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" >
<TextView
android:id="@+id/textView1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="X-Wert" />
<TextView
android:id="@+id/textView2"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="Y-Wert" />
<TextView
android:id="@+id/textView3"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="Z-Wert" />
</LinearLayout>
sensoractivity2 Manifest:
Code:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.sensoractivity2"
android:versionCode="1"
android:versionName="1.0">
<uses-sdk
android:minSdkVersion="8"/>
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme">
<activity android:name="com.example.sensoractivity2.MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
</application>
</manifest>
First thing I see is that you are not setting your view in your activity classes "oncreate" method. Can you post your logcat output when the app force closes? That will help the most.
Could you please post a logcat?
Just the lines of your app. Get it using the logcat view in Eclipse.
Look at the bold for changes that will help you. When you are working with view objects, you shouldn't create the object in a listener or something that is called over and over. You will be creating a memory leak.
Code:
package com.example.sensoractivity2;
import android.app.Activity;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.widget.TextView;
public class MainActivity extends Activity implements SensorEventListener{
private SensorManager sensorManager;
[B]TextView tx = null;
TextView ty = null;
TextView tz = null;[/B]
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
sensorManager=(SensorManager) getSystemService(SENSOR_SERVICE);
[B] setContentView(R.layout.activity_main);[/B]
sensorManager.registerListener(this, sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_NORMAL);
[B]tx = (TextView) findViewById(R.id.textView1);
ty = (TextView) findViewById(R.id.textView2);
tz = (TextView) findViewById(R.id.textView3);[/B]
}
public void onSensorChanged(SensorEvent event) {
float x, y, z = 0;
if (event.sensor.getType()==Sensor.TYPE_ACCELEROMETER) {
x=event.values[0];
y=event.values[1];
z=event.values[2];
[B]tx.setText((int) x);
ty.setText((int) y);
tz.setText((int) z);[/B]
}
}
[user=439709]@override[/user]
public void onAccuracyChanged(Sensor arg0, int arg1) {
// TODO Auto-generated method stub
}
}
Here is the part of the catlog which I believe to be relevant when the crash occurs:
Code:
04-28 18:34:24.628: E/SurfaceFlinger(36): ro.sf.lcd_density must be defined as a build property
04-28 18:34:25.750: E/Trace(1735): error opening trace file: No such file or directory (2)
04-28 18:34:27.452: I/ARMAssembler(36): generated scanline__00000077:03515104_00009002_00000000 [127 ipp] (149 ins) at [0x40f081f0:0x40f08444] in 34521256 ns
04-28 18:34:29.430: I/Choreographer(1153): Skipped 388 frames! The application may be doing too much work on its main thread.
04-28 18:34:29.462: I/ARMAssembler(36): generated scanline__00000077:03010104_00008002_00000000 [ 89 ipp] (110 ins) at [0x40f08450:0x40f08608] in 17654283 ns
04-28 18:34:30.825: W/ActivityManager(1003): Launch timeout has expired, giving up wake lock!
04-28 18:34:31.673: D/AndroidRuntime(1735): Shutting down VM
04-28 18:34:31.673: W/dalvikvm(1735): threadid=1: thread exiting with uncaught exception (group=0x40a71930)
04-28 18:34:31.737: E/AndroidRuntime(1735): FATAL EXCEPTION: main
04-28 18:34:31.737: E/AndroidRuntime(1735): java.lang.NullPointerException
04-28 18:34:31.737: E/AndroidRuntime(1735): at com.example.sensoractivity2.MainActivity.onSensorChanged(MainActivity.java:27)
04-28 18:34:31.737: E/AndroidRuntime(1735): at android.hardware.SystemSensorManager$ListenerDelegate$1.handleMessage(SystemSensorManager.java:204)
04-28 18:34:31.737: E/AndroidRuntime(1735): at android.os.Handler.dispatchMessage(Handler.java:99)
04-28 18:34:31.737: E/AndroidRuntime(1735): at android.os.Looper.loop(Looper.java:137)
04-28 18:34:31.737: E/AndroidRuntime(1735): at android.app.ActivityThread.main(ActivityThread.java:5041)
04-28 18:34:31.737: E/AndroidRuntime(1735): at java.lang.reflect.Method.invokeNative(Native Method)
04-28 18:34:31.737: E/AndroidRuntime(1735): at java.lang.reflect.Method.invoke(Method.java:511)
04-28 18:34:31.737: E/AndroidRuntime(1735): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
04-28 18:34:31.737: E/AndroidRuntime(1735): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
04-28 18:34:31.737: E/AndroidRuntime(1735): at dalvik.system.NativeStart.main(Native Method)
04-28 18:34:31.813: W/ActivityManager(1003): Force finishing activity com.example.sensoractivity2/.MainActivity
04-28 18:34:31.893: W/WindowManager(1003): Failure taking screenshot for (328x583) to layer 21010
04-28 18:34:32.643: D/dalvikvm(1003): GC_FOR_ALLOC freed 588K, 26% free 7082K/9496K, paused 471ms, total 481ms
Thanks for your hints, zalez! Going to try that now.
The logcat states a nullpointer error. I believe my corrections will fix at least that error.
spelaben said:
Here is the part of the catlog which I believe to be relevant when the crash occurs:
Code:
04-28 18:34:24.628: E/SurfaceFlinger(36): ro.sf.lcd_density must be defined as a build property
04-28 18:34:25.750: E/Trace(1735): error opening trace file: No such file or directory (2)
04-28 18:34:27.452: I/ARMAssembler(36): generated scanline__00000077:03515104_00009002_00000000 [127 ipp] (149 ins) at [0x40f081f0:0x40f08444] in 34521256 ns
04-28 18:34:29.430: I/Choreographer(1153): Skipped 388 frames! The application may be doing too much work on its main thread.
04-28 18:34:29.462: I/ARMAssembler(36): generated scanline__00000077:03010104_00008002_00000000 [ 89 ipp] (110 ins) at [0x40f08450:0x40f08608] in 17654283 ns
04-28 18:34:30.825: W/ActivityManager(1003): Launch timeout has expired, giving up wake lock!
04-28 18:34:31.673: D/AndroidRuntime(1735): Shutting down VM
04-28 18:34:31.673: W/dalvikvm(1735): threadid=1: thread exiting with uncaught exception (group=0x40a71930)
04-28 18:34:31.737: E/AndroidRuntime(1735): FATAL EXCEPTION: main
04-28 18:34:31.737: E/AndroidRuntime(1735): java.lang.NullPointerException
04-28 18:34:31.737: E/AndroidRuntime(1735): at com.example.sensoractivity2.MainActivity.onSensorChanged(MainActivity.java:27)
04-28 18:34:31.737: E/AndroidRuntime(1735): at android.hardware.SystemSensorManager$ListenerDelegate$1.handleMessage(SystemSensorManager.java:204)
04-28 18:34:31.737: E/AndroidRuntime(1735): at android.os.Handler.dispatchMessage(Handler.java:99)
04-28 18:34:31.737: E/AndroidRuntime(1735): at android.os.Looper.loop(Looper.java:137)
04-28 18:34:31.737: E/AndroidRuntime(1735): at android.app.ActivityThread.main(ActivityThread.java:5041)
04-28 18:34:31.737: E/AndroidRuntime(1735): at java.lang.reflect.Method.invokeNative(Native Method)
04-28 18:34:31.737: E/AndroidRuntime(1735): at java.lang.reflect.Method.invoke(Method.java:511)
04-28 18:34:31.737: E/AndroidRuntime(1735): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
04-28 18:34:31.737: E/AndroidRuntime(1735): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
04-28 18:34:31.737: E/AndroidRuntime(1735): at dalvik.system.NativeStart.main(Native Method)
04-28 18:34:31.813: W/ActivityManager(1003): Force finishing activity com.example.sensoractivity2/.MainActivity
04-28 18:34:31.893: W/WindowManager(1003): Failure taking screenshot for (328x583) to layer 21010
04-28 18:34:32.643: D/dalvikvm(1003): GC_FOR_ALLOC freed 588K, 26% free 7082K/9496K, paused 471ms, total 481ms
Thanks for your hints, zalez! Going to try that now.
Click to expand...
Click to collapse
zalez said:
The logcat states a nullpointer error. I believe my corrections will fix at least that error.
Click to expand...
Click to collapse
True, nullpointer errors are fixed. After debugging it again, I'm getting these errors now:
Code:
04-28 19:07:59.466: E/AndroidRuntime(858): FATAL EXCEPTION: main
04-28 19:07:59.466: E/AndroidRuntime(858): android.content.res.Resources$NotFoundException: String resource ID #0x0
04-28 19:07:59.466: E/AndroidRuntime(858): at android.content.res.Resources.getText(Resources.java:230)
04-28 19:07:59.466: E/AndroidRuntime(858): at android.widget.TextView.setText(TextView.java:3769)
04-28 19:07:59.466: E/AndroidRuntime(858): at com.example.sensoractivity2.MainActivity.onSensorChanged(MainActivity.java:33)
04-28 19:07:59.466: E/AndroidRuntime(858): at android.hardware.SystemSensorManager$ListenerDelegate$1.handleMessage(SystemSensorManager.java:204)
04-28 19:07:59.466: E/AndroidRuntime(858): at android.os.Handler.dispatchMessage(Handler.java:99)
04-28 19:07:59.466: E/AndroidRuntime(858): at android.os.Looper.loop(Looper.java:137)
04-28 19:07:59.466: E/AndroidRuntime(858): at android.app.ActivityThread.main(ActivityThread.java:5041)
04-28 19:07:59.466: E/AndroidRuntime(858): at java.lang.reflect.Method.invokeNative(Native Method)
04-28 19:07:59.466: E/AndroidRuntime(858): at java.lang.reflect.Method.invoke(Method.java:511)
04-28 19:07:59.466: E/AndroidRuntime(858): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
04-28 19:07:59.466: E/AndroidRuntime(858): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
04-28 19:07:59.466: E/AndroidRuntime(858): at dalvik.system.NativeStart.main(Native Method)
Any ideas?
spelaben said:
True, nullpointer errors are fixed. After debugging it again, I'm getting these errors now:
Code:
04-28 19:07:59.466: E/AndroidRuntime(858): FATAL EXCEPTION: main
04-28 19:07:59.466: E/AndroidRuntime(858): android.content.res.Resources$NotFoundException: String resource ID #0x0
04-28 19:07:59.466: E/AndroidRuntime(858): at android.content.res.Resources.getText(Resources.java:230)
04-28 19:07:59.466: E/AndroidRuntime(858): at android.widget.TextView.setText(TextView.java:3769)
04-28 19:07:59.466: E/AndroidRuntime(858): at com.example.sensoractivity2.MainActivity.onSensorChanged(MainActivity.java:33)
04-28 19:07:59.466: E/AndroidRuntime(858): at android.hardware.SystemSensorManager$ListenerDelegate$1.handleMessage(SystemSensorManager.java:204)
04-28 19:07:59.466: E/AndroidRuntime(858): at android.os.Handler.dispatchMessage(Handler.java:99)
04-28 19:07:59.466: E/AndroidRuntime(858): at android.os.Looper.loop(Looper.java:137)
04-28 19:07:59.466: E/AndroidRuntime(858): at android.app.ActivityThread.main(ActivityThread.java:5041)
04-28 19:07:59.466: E/AndroidRuntime(858): at java.lang.reflect.Method.invokeNative(Native Method)
04-28 19:07:59.466: E/AndroidRuntime(858): at java.lang.reflect.Method.invoke(Method.java:511)
04-28 19:07:59.466: E/AndroidRuntime(858): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
04-28 19:07:59.466: E/AndroidRuntime(858): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
04-28 19:07:59.466: E/AndroidRuntime(858): at dalvik.system.NativeStart.main(Native Method)
Any ideas?
Click to expand...
Click to collapse
It needs to be
Code:
tx.setText(String.valueOf(x));
ty.setText(String.valueOf(y));
tz.setText(String.valueOf(z));
If you pass an int, the TextView thinks that it is a resource id. That is why you need to convert it to a String first.
I over looked the bold part. When setting text for a Textview, it has to be in string format. There is no implied conversion.
Code:
package com.example.sensoractivity2;
import android.app.Activity;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.widget.TextView;
public class MainActivity extends Activity implements SensorEventListener{
private SensorManager sensorManager;
TextView tx = null;
TextView ty = null;
TextView tz = null;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
sensorManager=(SensorManager) getSystemService(SENSOR_SERVICE);
setContentView(R.layout.activity_main);
sensorManager.registerListener(this, sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_NORMAL);
tx = (TextView) findViewById(R.id.textView1);
ty = (TextView) findViewById(R.id.textView2);
tz = (TextView) findViewById(R.id.textView3);
}
public void onSensorChanged(SensorEvent event) {
float x, y, z = 0;
if (event.sensor.getType()==Sensor.TYPE_ACCELEROMETER) {
x=event.values[0];
y=event.values[1];
z=event.values[2];
tx.setText[B](Integer.toString(x)[/B]);
ty.setText([B]Integer.toString(y)[/B]);
tz.setText([B]Integer.toString(z)[/B]);
}
}
[user=439709]@override[/user]
public void onAccuracyChanged(Sensor arg0, int arg1) {
// TODO Auto-generated method stub
}
}
nikwen said:
It needs to be
Code:
tx.setText(String.valueOf(x));
ty.setText(String.valueOf(y));
tz.setText(String.valueOf(z));
If you pass an int, the TextView thinks that it is a resource id. That is why you need to convert it to a String first.
Click to expand...
Click to collapse
Yes! That did the trick! Now my next problem is that I only see one value instead of three, from there on I will try to move on by myself.
Sorry, I'm not sure if this is relevant, but you aren't overriding your onCreate method? Could that have anything to do with it?
MaartenXDA said:
Sorry, I'm not sure if this is relevant, but you aren't overriding your onCreate method? Could that have anything to do with it?
Click to expand...
Click to collapse
He does:
public void onCreate(Bundle savedInstanceState) {
Click to expand...
Click to collapse
He just did not wrote the @override annotation before that. As far as i know, you do not have to use it.
EDIT: Yep, it does not matter. See this: http://stackoverflow.com/questions/94361/when-do-you-use-javas-override-annotation-and-why
It says that it is just for ensuring that you are overriding the right method and for making the code easier to read.
Hi all, I am a bit further with my project since I found some time to work on it again.
//edit, force closes on starting fixed!
Here is what it is supposed to be doing: It reads the x, y and z values for acceleration from the LINEAR_ACCELERATION sensor. If a certain value is exceeded a timer will be started. If the amount of seconds the timer counts is higher than a defined threshold, it will play the default notifcation sound.
If the value from the sensor is below the threshold, it will stop the timer. The whole timer thing isn't working, the notification is played as soon as the normal acceleration threshold is passed and the time is ignored.
Please review my code below and tell me what I'm not seeing here, note that I'm still a noob.
Also I'm interested in a method to capture the maximum values read from the sensor and put it in a textview, can you help me?
AccelMeter.java:
Code:
package com.example.accelmeter;
import android.app.Activity;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.SystemClock;
import android.view.View;
import android.widget.Button;
import android.widget.Chronometer;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class AccelMeter extends Activity implements SensorEventListener {
private SensorManager sensorManager;
// Objekte deklarieren
TextView xC;
TextView yC;
TextView zC;
Chronometer chrono;
/* accThreshold = Schwellenwert in m/s² für die Beschleunigung
* accInterval = Zeitraum in Sekunden, über den der Wert für die Beschleunigung überwacht wird
*/
private float accThreshold = 50;
private float accInterval = 0;
[user=439709]@override[/user]
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_accel_meter);
// Achsen Objekte erstellen
xC=(TextView)findViewById(R.id.xCoordinate);
yC=(TextView)findViewById(R.id.yCoordinate);
zC=(TextView)findViewById(R.id.zCoordinate);
/* Sensor.TYPE_LINEAR_ACCELERATION = Beschleunigung auf jeder Achse ohne Gravitation in m/s²
* SENSOR_DELAY_FASTEST = schnellster Modus für Messung. Alternativen z.B. _GAME, _NORMAL oder _UI
*/
sensorManager=(SensorManager)getSystemService(SENSOR_SERVICE);
sensorManager.registerListener(this,
sensorManager.getDefaultSensor(Sensor.TYPE_LINEAR_ACCELERATION),
SensorManager.SENSOR_DELAY_NORMAL);
// Schwellenwert festlegen und mit einer Toast-Benachrichtigung bestätigen, Fehlerbehandlung wenn kein Wert eingegeben wurde
Button setThreshold = (Button)findViewById(R.id.setThreshold);
setThreshold.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
try {
EditText et = (EditText)findViewById(R.id.threshold);
accThreshold = Float.valueOf(et.getText().toString());
Toast.makeText(getApplicationContext(), "Neuer Schwellenwert festgelegt!", Toast.LENGTH_SHORT).show();
}
catch (Exception e) {
Toast.makeText(getApplicationContext(), "Es wurde noch kein Wert eingegeben!", Toast.LENGTH_SHORT).show();
}
}
});
// Intervall festlegen und mit einer Toast-Benachrichtigung bestätigen, Fehlerbehandlung wenn kein Wert eingegeben wurde
Button setInterval = (Button)findViewById(R.id.setInterval);
setInterval.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
try {
EditText et = (EditText)findViewById(R.id.editInterval);
accInterval = Float.valueOf(et.getText().toString());
Toast.makeText(getApplicationContext(), "Neues Intervall festgelegt!", Toast.LENGTH_SHORT).show();
}
catch (Exception e) {
Toast.makeText(getApplicationContext(), "Es wurde noch kein Wert eingegeben!", Toast.LENGTH_SHORT).show();
}
}
});
// Programm beenden
Button exit = (Button)findViewById(R.id.exit);
exit.setOnClickListener(new Button.OnClickListener() {
public void onClick(View v) {
finish();
System.exit(0);
}
});
}
public void onSensorChanged(SensorEvent event){
// Sensor Typ überprüfen
if(event.sensor.getType()==Sensor.TYPE_LINEAR_ACCELERATION){
// Richtungen verknüpfen
float x=event.values[0];
float y=event.values[1];
float z=event.values[2];
// Gerundete Ergebnisse mit vier Nachkommastellen ausgeben
xC.setText("X: "+(Math.abs(Math.round(x * 1000) / 1000.0)));
yC.setText("Y: "+(Math.abs(Math.round(y * 1000) / 1000.0)));
zC.setText("Z: "+(Math.abs(Math.round(z * 1000) / 1000.0)));
// Wenn Beschleunigung über Schwellenwert liegt, starte Timer. Wenn Timer das festgelete Intervall überschreitet, spiele Benachrichtigungston
if (x + y + z > accThreshold)
{
chrono = new Chronometer(this);
chrono.setBase(SystemClock.elapsedRealtime());
chrono.start();
long seconds = ((chrono.getBase()-SystemClock.elapsedRealtime()/1000%60));
if (seconds >= accInterval)
{
Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
Ringtone r = RingtoneManager.getRingtone(getApplicationContext(), notification);
r.play();
}
else
{
chrono.stop();
}
}
}
}
[user=439709]@override[/user]
public void onAccuracyChanged(Sensor sensor, int accuracy) {
// TODO Auto-generated method stub
}
}
activity_accel_meter.xml:
Code:
<?xml version="1.0" encoding="utf-8"?>
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<TableRow tools:ignore="ExtraText" >
<TextView
android:id="@+id/xCoordinate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="X Koordinate: "
android:textAppearance="?android:attr/textAppearanceLarge"
tools:ignore="HardcodedText" />
/>
</TableRow>
<TableRow>
<TextView
android:id="@+id/yCoordinate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Y Koordinate: "
android:textAppearance="?android:attr/textAppearanceLarge"
tools:ignore="HardcodedText" />
/>
</TableRow>
<TableRow>
<TextView
android:id="@+id/zCoordinate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Z Koordinate: "
android:textAppearance="?android:attr/textAppearanceLarge"
tools:ignore="HardcodedText" />
/>
</TableRow>
<EditText
android:id="@+id/threshold"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10"
android:hint="Schwellenwert (float)"
android:inputType="numberDecimal"
tools:ignore="HardcodedText" />
<Button
android:id="@+id/setThreshold"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Schwellenwert festlegen"
tools:ignore="HardcodedText" />
<EditText
android:id="@+id/editInterval"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10"
android:hint="Zeit in Sekunden"
android:inputType="number"
tools:ignore="HardcodedText" >
<requestFocus />
</EditText>
<Button
android:id="@+id/setInterval"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Zeitraum für Überwachung festlegen"
tools:ignore="HardcodedText" />
<Button
android:id="@+id/exit"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Beenden"
tools:ignore="HardcodedText" />
</TableLayout>
Yay German code (live there, too) xD Initialise your seconds in your onCreate, it's much nicer and probably the problem. A method gets the highest value the sensor measured would be a simple
Code:
double savedVal=0; //or any other type
private void updateMaxVal(){
double currentVal =// get the value from the specific sensor
if(savedVal<currentVal) {
savedVal = currentVal;
// maybe save the time as well
}
You'd have to put that method in the onsensorchanged so it will be called often. Then update your text View with the new saved value
SimplicityApks said:
Yay German code (live there, too) xD Initialise your seconds in your onCreate, it's much nicer and probably the problem. A method gets the highest value the sensor measured would be a simple
Code:
double savedVal=0; //or any other type
private void updateMaxVal(){
double currentVal =// get the value from the specific sensor
if(savedVal<currentVal) {
savedVal = currentVal;
// maybe save the time as well
}
You'd have to put that method in the onsensorchanged so it will be called often. Then update your text View with the new saved value
Click to expand...
Click to collapse
Hey fellow German!
If I initialise the seconds variable in the onCreate part it says that the variable is not being used (yellow marking) and in the code below I get an error obviously stating that the variable is unknown. ^^
I have three different values, how can I link the x, y and z variables in the method and how can I make sure the variables are known inside of the method? (Same problem as above)
Since I don't know how to do it with a method I just wrote the following code in my onsensorchanged part, the problem is that the max value textviews always show the same as the current value textviews:
float savedValX = 0;
float savedValY = 0;
float savedValZ = 0;
float currentValX = event.values[0];
float currentValY = event.values[1];
float currentValZ = event.values[2];
if (savedValX < currentValX) {
savedValX = currentValX;
xM.setText("X max: "+(Math.abs(Math.round(currentValX * 1000) / 1000.0)));
}
if (savedValY < currentValY) {
savedValY = currentValY;
yM.setText("Y max: "+(Math.abs(Math.round(currentValY * 1000) / 1000.0)));
}
if (savedValZ < currentValZ) {
savedValZ = currentValZ;
zM.setText("Z max: "+(Math.abs(Math.round(currentValZ * 1000) / 1000.0)));
}
Also I still have the problem that my seconds interval is being ignored.
//edit, fixed it! Now I only need the max value method.
OK so I now understand what you are trying to do with your Chronometer, the problem is that you reinitialize it every time the onSensorChanged is called so if you then ask for the seconds it has just started. To fix this, you could set an onChronometerTickListener and set your textViews in that method. To avoid recreating the Chrono use
Code:
if(chrono==null){
chrono = new Chronometer();
chrono.start();
}
If u don't want the tick listener or it doesn't work ( haven't used it yet) you can put your if(seconds<...)in the else {}of above method. But remember that the onSensorChanged is called EVERYTIME the sensor registers a change, this might be very often or just sometimes, so there is no guarantee that the text views will be updated if the else clause in that method is used
PS forget about the initializing of the seconds, I don't know what I was thinking yesterday, but I guess it was too late ...
/*edit:
What I meant with
Code:
double savedVal=0; //or any other type
private void updateMaxVal(){
is that you save your value in your class ("globally"), so that it is accessible to the whole class.
and to do it nicely you can do it like this:
Code:
float savedValX = 0;
float savedValY = 0;
float savedValZ = 0;
boolean change = false;
private void updateMaxVals(SensorEvent event){ // call this method in your onSensorChanged
change = false;
savedValX = getMax(event.values[0], savedValX);
if(change){
xM.setText("X max: "+(Math.abs(Math.round(savedValX * 1000) / 1000.0)));
}
savedValY = getMax(event.values[1], savedValY);
if(change){
yM.setText("Y max: "+(Math.abs(Math.round(savedValY * 1000) / 1000.0)));
}
savedValZ = getMax(event.values[2], savedValZ);
if(change){
yM.setText("Z max: "+(Math.abs(Math.round(savedValZ * 1000) / 1000.0)));
}
}
private float getMax(float currentVal, float savedVal){
if(currentVal > savedVal){
change = true;
return currentVal;
}else{
change = false;
return savedVal;
}
}

Browser not working! Please help :(

Hi, I was trying to make a browser. But obviously, its not working. Please help me out. I will be providing all the codes here:
Thanks in advance ...
manifest:
Code:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.browser"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<uses-premission android:name="android.content.permissions.INTERNET" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.example.browser.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name="com.example.browser.ta"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.TA" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
</application>
</manifest>
MainActivity.class:
Code:
package com.example.browser;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends Activity implements OnClickListener {
EditText search = (EditText) findViewById(R.id.editText1);
WebView wb = (WebView) findViewById(R.id.webView1);
Button back = (Button) findViewById(R.id.button2);
Button forward = (Button) findViewById(R.id.button1);
Button Bsearch = (Button) findViewById(R.id.dd);
String s = search.getText().toString();
ta t = new ta();
[user=439709]@override[/user]
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
wb.getSettings().setBuiltInZoomControls(true);
wb.getSettings().setJavaScriptEnabled(true);
wb.getSettings().setLoadWithOverviewMode(true);
wb.getSettings().setSavePassword(true);
wb.getSettings().setAllowFileAccess(true);
back.setOnClickListener(this);
forward.setOnClickListener(this);
Bsearch.setOnClickListener(this);
wb.setWebViewClient(t);
wb.loadUrl("http://www.google.com");
}
[user=439709]@override[/user]
public void onClick(View arg0) {
// TODO Auto-generated method stub
switch (arg0.getId()) {
case R.id.dd: // search
ProgressDialog d = ProgressDialog.show(this, "loading",
"Please wait");
wb.loadUrl("http://" + s);
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(search.getWindowToken(), 0);
break;
case R.id.button2: // back
if (wb.canGoBack())
wb.goBack();
break;
case R.id.button1: // forward
if (wb.canGoForward())
wb.goForward();
break;
}
}
}
ta.class:
Code:
package com.example.browser;
import android.app.ProgressDialog;
import android.content.Context;
import android.view.inputmethod.InputMethodManager;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class ta extends WebViewClient {
public boolean shouldOverrideUrlLoading(WebView v, String url) {
v.loadUrl(url);
return true;
}
}
Logcat?
nikwen said:
Logcat?
Click to expand...
Click to collapse
Sorry, I completely forgot, about that!!
Here it is:
Code:
07-14 16:12:46.367: E/AndroidRuntime(287): FATAL EXCEPTION: main
07-14 16:12:46.367: E/AndroidRuntime(287): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.browser/com.example.browser.MainActivity}: java.lang.NullPointerException
07-14 16:12:46.367: E/AndroidRuntime(287): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2585)
07-14 16:12:46.367: E/AndroidRuntime(287): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
07-14 16:12:46.367: E/AndroidRuntime(287): at android.app.ActivityThread.access$2300(ActivityThread.java:125)
07-14 16:12:46.367: E/AndroidRuntime(287): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
07-14 16:12:46.367: E/AndroidRuntime(287): at android.os.Handler.dispatchMessage(Handler.java:99)
07-14 16:12:46.367: E/AndroidRuntime(287): at android.os.Looper.loop(Looper.java:123)
07-14 16:12:46.367: E/AndroidRuntime(287): at android.app.ActivityThread.main(ActivityThread.java:4627)
07-14 16:12:46.367: E/AndroidRuntime(287): at java.lang.reflect.Method.invokeNative(Native Method)
07-14 16:12:46.367: E/AndroidRuntime(287): at java.lang.reflect.Method.invoke(Method.java:521)
07-14 16:12:46.367: E/AndroidRuntime(287): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
07-14 16:12:46.367: E/AndroidRuntime(287): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
07-14 16:12:46.367: E/AndroidRuntime(287): at dalvik.system.NativeStart.main(Native Method)
07-14 16:12:46.367: E/AndroidRuntime(287): Caused by: java.lang.NullPointerException
07-14 16:12:46.367: E/AndroidRuntime(287): at android.app.Activity.findViewById(Activity.java:1637)
07-14 16:12:46.367: E/AndroidRuntime(287): at com.example.browser.MainActivity.<init>(MainActivity.java:17)
07-14 16:12:46.367: E/AndroidRuntime(287): at java.lang.Class.newInstanceImpl(Native Method)
07-14 16:12:46.367: E/AndroidRuntime(287): at java.lang.Class.newInstance(Class.java:1429)
07-14 16:12:46.367: E/AndroidRuntime(287): at android.app.Instrumentation.newActivity(Instrumentation.java:1021)
07-14 16:12:46.367: E/AndroidRuntime(287): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2577)
07-14 16:12:46.367: E/AndroidRuntime(287): ... 11 more
Read This http://forum.xda-developers.com/showthread.php?t=2325164
then look at your logcat
Code:
07-14 16:12:46.367: E/AndroidRuntime(287): Caused by: java.lang.NullPointerException
07-14 16:12:46.367: E/AndroidRuntime(287): at android.app.Activity.findViewById(Activity.java:1637)
07-14 16:12:46.367: E/AndroidRuntime(287): at com.example.browser.MainActivity.<init>(MainActivity.java:17)
then count from the top, and your error is your edittext
I looked at the edit-text. But i still cannot find any wrong. However, I modified one of my buttons with this:
Code:
case R.id.dd: // search
wb.loadUrl("http://" + search.getText().toString());
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(search.getWindowToken(), 0);
break;
Still. no help...
Code:
07-14 16:12:46.367: E/AndroidRuntime(287): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{com.example.browser/com.example.browser.MainActivity}: java.lang.NullPointerException
What is this about??
I think, there is something wrong with the manifest, Please take a look at it!
read nikwens debugging guide I linked again.
then here
07-14 16:12:46.367: E/AndroidRuntime(287): at com.example.browser.MainActivity.<init>(MainActivity.java:17
thats the name of your app, and the line you have the problem at.
nullpointers could be a million things, look for your app and the line it errors on.
also intent.action.TA isnt a thing. take that out.
out of ideas said:
read nikwens debugging guide I linked again.
then here
07-14 16:12:46.367: E/AndroidRuntime(287): at com.example.browser.MainActivity.<init>(MainActivity.java:17
thats the name of your app, and the line you have the problem at.
nullpointers could be a million things, look for your app and the line it errors on.
also intent.action.TA isnt a thing. take that out.
Click to expand...
Click to collapse
Hey, thanks for linking it.
It even tells you that the method which fails is findViewById().
nikwen said:
Hey, thanks for linking it.
It even tells you that the method which fails is findViewById().
Click to expand...
Click to collapse
Yeah, you were right, there were couple of wrong ids, in that code. But I have edited all of them now.. Still the app is crashing and I am getting the same error, for "findByView".
I am also pasting, the new code and the UI xml.
activity_main.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" >
<EditText
android:id="@+id/editText1"
android:layout_width="291dp"
android:layout_height="wrap_content"
android:layout_x="0dp"
android:layout_y="4dp"
android:hint="Enter Search!" />
<WebView
android:id="@+id/webView1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignLeft="@+id/editText1"
android:layout_alignParentBottom="true"
android:layout_below="@+id/back" />
<Button
android:id="@+id/s"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignTop="@+id/back"
android:text="Search" />
<Button
android:id="@+id/dd"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/editText1"
android:layout_toRightOf="@+id/s"
android:text="Forward" />
<Button
android:id="@+id/back"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/dd"
android:layout_alignBottom="@+id/dd"
android:layout_toRightOf="@+id/dd"
android:text="Back" />
</RelativeLayout>
MainActivity:
Code:
package com.example.browser;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends Activity implements OnClickListener {
EditText search = (EditText) findViewById(R.id.editText1);
WebView wb = (WebView) findViewById(R.id.webView1);
Button back = (Button) findViewById(R.id.s);
Button forward = (Button) findViewById(R.id.back);
Button Bsearch = (Button) findViewById(R.id.dd);
ta t = new ta();
[user=439709]@override[/user]
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
back.setOnClickListener(this);
forward.setOnClickListener(this);
Bsearch.setOnClickListener(this);
wb.loadUrl("http://www.google.com");
wb.setWebViewClient(t);
}
[user=439709]@override[/user]
public void onClick(View arg0) {
// TODO Auto-generated method stub
switch (arg0.getId()) {
case R.id.dd: // search
wb.loadUrl("http://" + search.getText().toString());
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(search.getWindowToken(), 0);
break;
case R.id.back: // back
if (wb.canGoBack())
wb.goBack();
break;
case R.id.s: // forward
if (wb.canGoForward())
wb.goForward();
break;
}
}
}
Please help me out! I know I am dumb. But I am learning it all by myself, without a mentor at the age of 16. Its little complex for me. I have spent, a lot of time finding the error. But its not working.
It doesn't like trying to find the view where you are declaring your variables. The findviewbyid should be moved in to your oncreate.
This works:
Code:
public class MainActivity extends Activity implements OnClickListener {
EditText search;
WebView wb;
Button back;
Button forward;
Button Bsearch;
ta t = new ta();
[user=439709]@override[/user]
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
search = (EditText) findViewById(R.id.editText1);
wb = (WebView) findViewById(R.id.webView1);
back = (Button) findViewById(R.id.s);
forward = (Button) findViewById(R.id.back);
Bsearch = (Button) findViewById(R.id.dd);
back.setOnClickListener(this);
forward.setOnClickListener(this);
Bsearch.setOnClickListener(this);
wb.loadUrl("http://www.google.com");
wb.setWebViewClient(t);
}
After looking in to the reason why it would crash, my only educated guess is because you are trying to find the view without the view being set. View is set in the oncreate method.
zalez said:
It doesn't like trying to find the view where you are declaring your variables. The findviewbyid should be moved in to your oncreate.
This works:
Code:
public class MainActivity extends Activity implements OnClickListener {
EditText search;
WebView wb;
Button back;
Button forward;
Button Bsearch;
ta t = new ta();
[user=439709]@override[/user]
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
search = (EditText) findViewById(R.id.editText1);
wb = (WebView) findViewById(R.id.webView1);
back = (Button) findViewById(R.id.s);
forward = (Button) findViewById(R.id.back);
Bsearch = (Button) findViewById(R.id.dd);
back.setOnClickListener(this);
forward.setOnClickListener(this);
Bsearch.setOnClickListener(this);
wb.loadUrl("http://www.google.com");
wb.setWebViewClient(t);
}
After looking in to the reason why it would crash, my only educated guess is because you are trying to find the view without the view being set. View is set in the oncreate method.
Click to expand...
Click to collapse
Code:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
search = (EditText) findViewById(R.id.editText1);
wb = (WebView) findViewById(R.id.webView1);
back = (Button) findViewById(R.id.s);
forward = (Button) findViewById(R.id.back);
Bsearch = (Button) findViewById(R.id.dd);
back.setOnClickListener(this);
forward.setOnClickListener(this);
Bsearch.setOnClickListener(this);
wb.loadUrl("http://www.google.com");
wb.setWebViewClient(t);
}
I modified my code, with this.. But, its still crashing
Post your entire MainActivity.class. I copied all of your code and changed what I posted back and do not get a crash.
This is working for me:
Code:
package com.example.browser;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.EditText;
public class MainActivity extends Activity implements OnClickListener {
EditText search;
WebView wb;
Button back;
Button forward;
Button Bsearch;
ta t = new ta();
[user=439709]@override[/user]
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
search = (EditText) findViewById(R.id.editText1);
wb = (WebView) findViewById(R.id.webView1);
back = (Button) findViewById(R.id.s);
forward = (Button) findViewById(R.id.back);
Bsearch = (Button) findViewById(R.id.dd);
back.setOnClickListener(this);
forward.setOnClickListener(this);
Bsearch.setOnClickListener(this);
wb.loadUrl("http://www.google.com");
wb.setWebViewClient(t);
}
[user=439709]@override[/user]
public void onClick(View arg0) {
// TODO Auto-generated method stub
switch (arg0.getId()) {
case R.id.dd: // search
wb.loadUrl("http://" + search.getText().toString());
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(search.getWindowToken(), 0);
break;
case R.id.back: // back
if (wb.canGoBack())
wb.goBack();
break;
case R.id.s: // forward
if (wb.canGoForward())
wb.goForward();
break;
}
}
}
hiphop12ism said:
Code:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
search = (EditText) findViewById(R.id.editText1);
wb = (WebView) findViewById(R.id.webView1);
back = (Button) findViewById(R.id.s);
forward = (Button) findViewById(R.id.back);
Bsearch = (Button) findViewById(R.id.dd);
back.setOnClickListener(this);
forward.setOnClickListener(this);
Bsearch.setOnClickListener(this);
wb.loadUrl("http://www.google.com");
wb.setWebViewClient(t);
}
I modified my code, with this.. But, its still crashing
Click to expand...
Click to collapse
It is still crashing. However, keep that code as it is right. The setContentView method needs to be called before getting the views.
In your xml there are some errors though:
You always use @+id/...
Use that just for android:id="@+id/myId".
Everywhere else do it without the plus, e.g. android:layout_below="@id/asdf".
The plus tells the compiler to create a new id. However, you do not want it to create a new id in android:layout_below but to use an already existing id.
Are all ids in the xml you load with setContentView? Is the logcat still the same? Could you please highlight the line which makes it crash?
nikwen said:
It is still crashing. However, keep that code as it is right. The setContentView method needs to be called before getting the views.
In your xml there are some errors though:
You always use @+id/...
Use that just for android:id="@+id/myId".
Everywhere else do it without the plus, e.g. android:layout_below="@id/asdf".
The plus tells the compiler to create a new id. However, you do not want it to create a new id in android:layout_below but to use an already existing id.
Are all ids in the xml you load with setContentView? Is the logcat still the same? Could you please highlight the line which makes it crash?
Click to expand...
Click to collapse
Actually, I fixed it. I made a new project. I thought of another way of making the browser.
I realised, there were lots of mistakes in the xml file.
here are my new codes. (Thank you everbody its over finally)
the UI
Code:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<EditText
android:id="@+id/editText1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="enter url" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="100"
android:orientation="horizontal" >
<Button
android:id="@+id/s"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="search" />
<Button
android:id="@+id/back"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="30"
android:text="back" />
<Button
android:id="@+id/forward"
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:layout_weight="35"
android:text="forward" />
</LinearLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<WebView
android:layout_width="match_parent"
android:layout_height="308dp"
android:id="@+id/wd" />
</LinearLayout>
</LinearLayout>
MainActivity:
Code:
package com.example.asd;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends Activity implements OnClickListener {
EditText et;
Button search, back, forward;
WebView wb;
[user=439709]@override[/user]
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
et = (EditText) findViewById(R.id.editText1);
search = (Button) findViewById(R.id.s);
back = (Button) findViewById(R.id.back);
forward = (Button) findViewById(R.id.forward);
wb = (WebView) findViewById(R.id.wd);
search.setOnClickListener(this);
wb.getSettings().setJavaScriptEnabled(true);
wb.getSettings().setAllowFileAccess(true);
wb.getSettings().setBuiltInZoomControls(true);
}
[user=439709]@override[/user]
public void onClick(View arg0) {
// TODO Auto-generated method stub
switch (arg0.getId()) {
case R.id.s:
wb.loadUrl(et.getText().toString());
wb.setWebViewClient(new callb());
break;
}
}
private class callb extends WebViewClient {
[user=439709]@override[/user]
public boolean shouldOverrideUrlLoading(WebView view, String url) {
// TODO Auto-generated method stub
wb.loadUrl(url);
return true;
}
}
}
But can you tell me, how can I make it more advanced. Like, when hit a editText on a website itslf.. Nothing Happens
You have to request focus on the webview:
wb.requestFocus(View.FOCUS_DOWN);

[Q] Error receiving Intent from IntentService

I'm trying to make an app that displays and image which will be downloaded in background in an IntentService class. When the IntentService finishes to download it sends the intent to be catched by a BroadcastReceiver in the MainActivity but I'm getting this error:
Code:
07-17 14:27:21.003 19189-19189/com.example.matt95.myapplication E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.example.matt95.myapplication, PID: 19189
java.lang.RuntimeException: Error receiving broadcast Intent { act=TRANSACTION_DONE flg=0x10 (has extras) } in [email protected]
at android.app.LoadedApk$ReceiverDispatcher$Args.run(LoadedApk.java)
at android.os.Handler.handleCallback(Handler.java)
at android.os.Handler.dispatchMessage(Handler.java)
at android.os.Looper.loop(Looper.java)
at android.app.ActivityThread.main(ActivityThread.java)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.example.matt95.myapplication.MyActivity$1.onReceive(MyActivity.java:74)
************at android.app.LoadedApk$ReceiverDispatcher$Args.run(LoadedApk.java)
************at android.os.Handler.handleCallback(Handler.java)
************at android.os.Handler.dispatchMessage(Handler.java)
************at android.os.Looper.loop(Looper.java)
************at android.app.ActivityThread.main(ActivityThread.java)
************at java.lang.reflect.Method.invokeNative(Native Method)
************at java.lang.reflect.Method.invoke(Method.java)
This is MainActivity class:
Code:
package com.example.matt95.myapplication;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ImageView;
import android.widget.Toast;
import java.io.File;
public class MyActivity extends Activity {
ProgressDialog pd;
// Custom BroadcastReceiver for catching and showing images
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
}
@Override
protected void onStart() {
super.onStart();
Intent i = new Intent(this, ImageIntentService.class);
i.putExtra("url", "http://samsung-wallpapers.com/uploads/allimg/130527/1-13052F02118.jpg");
startService(i);
pd = ProgressDialog.show(this, "Fetching image", "Go intent service go!");
}
@Override
protected void onResume() {
super.onResume();
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(ImageIntentService.TRANSACTION_DONE);
registerReceiver(imageReceiver, intentFilter);
}
@Override
protected void onPause() {
super.onPause();
unregisterReceiver(imageReceiver);
}
private BroadcastReceiver imageReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String location = intent.getExtras().getString("imageLocation");
if (location == null || location.length() == 0) {
String failedString = "Failed to download image";
Toast.makeText(context, failedString, Toast.LENGTH_LONG).show();
}
File imageFile = new File(location);
if (!imageFile.exists()) {
pd.dismiss();
String downloadFail = "Unable to download the image";
Toast.makeText(context, downloadFail, Toast.LENGTH_LONG).show();
return;
}
Bitmap image = BitmapFactory.decodeFile(location);
ImageView iv = (ImageView) findViewById(R.id.show_image);
iv.setImageBitmap(image);
pd.dismiss();
}
};
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.my, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
This is the IntentService class:
Code:
package com.example.matt95.myapplication;
import android.app.IntentService;
import android.content.Intent;
import android.os.Environment;
import android.util.Log;
import android.widget.Toast;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
public class ImageIntentService extends IntentService {
private File cacheDir;
private static final String CACHE_FOLDER = "/myapp/image_cache/";
public static String TRANSACTION_DONE = "com.example.matt95.myapplication.ImageIntentService.TRANSACTION_DONE";
//Constructor method
public ImageIntentService() {
super("ImageIntentService");
}
@Override
public void onCreate() {
super.onCreate();
String tmpLocation = Environment.getExternalStorageDirectory().getPath() + CACHE_FOLDER;
cacheDir = new File(tmpLocation);
if (!cacheDir.exists())
cacheDir.mkdirs();
}
@Override
protected void onHandleIntent(Intent intent) {
if (intent.hasExtra("url")) {
String remoteUrl = intent.getExtras().getString("url");
String imageLocation;
String fileName = remoteUrl.substring(remoteUrl.lastIndexOf(File.separator) + 1);
File tmpImage = new File(cacheDir + "/" + fileName);
if (tmpImage.exists()) {
imageLocation = tmpImage.getAbsolutePath();
notifyFinished(imageLocation, remoteUrl);
stopSelf();
return;
}
try {
URL url = new URL(remoteUrl);
HttpURLConnection httpCon = (HttpURLConnection) url.openConnection();
if (httpCon.getResponseCode() != 200)
throw new Exception("Failed to connect");
InputStream is = httpCon.getInputStream();
FileOutputStream fos = new FileOutputStream(tmpImage);
writeStream(is, fos);
fos.flush();
fos.close();
is.close();
imageLocation = tmpImage.getAbsolutePath();
notifyFinished(imageLocation, remoteUrl);
} catch (Exception e) {
Log.e("Service", "Failed!", e);
}
}
}
private void writeStream(InputStream is, OutputStream fos) throws Exception {
byte buffer[] = new byte[80000];
int read = is.read(buffer);
while (read != -1) {
fos.write(buffer, 0, read);
read = is.read(buffer);
}
}
private void notifyFinished(String imageLocation, String remoteUrl) {
Intent i = new Intent(TRANSACTION_DONE);
i.putExtra("imageLocation", imageLocation);
i.putExtra("url", remoteUrl);
ImageIntentService.this.sendBroadcast(i);
}
}
And this is the Manifest file:
Code:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.matt95.myapplication" >
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".MyActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name=".ImageIntentService" />
</application>
</manifest>
What am I doing wrong?
Code:
Caused by: java.lang.NullPointerException
at com.example.matt95.myapplication.MyActivity$1.onReceive(MyActivity.java:74)
tells you there, you are asking an object that is of type "x" that is NULL to do something on line 74
Why not just use the picasso library or similar to download the image asynchronously in the background?
Sent from my HTC One using Tapatalk
deanwray said:
Code:
Caused by: java.lang.NullPointerException
at com.example.matt95.myapplication.MyActivity$1.onReceive(MyActivity.java:74)
tells you there, you are asking an object that is of type "x" that is NULL to do something on line 74
Click to expand...
Click to collapse
Thanks, I knew that but I'lll take a closer look at the code again :good:
Jonny said:
Why not just use the picasso library or similar to download the image asynchronously in the background?
Sent from my HTC One using Tapatalk
Click to expand...
Click to collapse
I'm a beginner in Android application so I don't have the proper knowledge right now, thanks for the suggestion though, I'll definitely try to take a look at that library :good:
matt95 said:
Thanks, I knew that but I'lll take a closer look at the code again :good:
I'm a beginner in Android application so I don't have the proper knowledge right now, thanks for the suggestion though, I'll definitely try to take a look at that library :good:
Click to expand...
Click to collapse
Better use asynctask for loading images
Sent from my Moto G using XDA Premium 4 mobile app
arpitkh96 said:
Better use asynctask for loading images
Sent from my Moto G using XDA Premium 4 mobile app
Click to expand...
Click to collapse
Yeah but I also need to download it and then load it, and it's not good to download that amount of data on the main thread
matt95 said:
Yeah but I also need to download it and then load it, and it's not good to download that amount of data on the main thread
Click to expand...
Click to collapse
AsyncTask runs in the background on a separate thread via the doInBackground method.
Sent from my HTC One using Tapatalk
Also, when there is a possibility that one of the objects included in the intent is null you can trap the error with a try/catch around the sendBroadcast() to prevent the exception from crashing the entire app.

[Q] Webview with a longonclicklistener help request!

Hello,
I am currently trying to have a webview that listens to a long click and loads a website once longclicked.
However, it crashes and i would love to find out why, or how to fix it
I do have to state that this crash Occurs on Samsung and LG hardware, but not on the Nexus 4 or the Emulator (Nexus 7)
Code:
package com.example.homehub;
import android.app.Activity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnLongClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;
public class MainActivity extends Activity {
WebView webView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Go Fullscreen (Just in case)
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
// Display the layout
setContentView(R.layout.activity_main);
// Define the Web View
webView = (WebView) findViewById(R.id.webView1);
// Setup
webView.getSettings().setCacheMode( WebSettings.LOAD_DEFAULT );
webView.setLongClickable(true);
// Handle Links internally
webView.setWebViewClient(new WebViewClient() { });
// Using Latest Chrome Client
webView.setWebChromeClient(new WebChromeClient());
// Browser Settings
webView.getSettings().setAllowFileAccess( true );
webView.getSettings().setAppCacheEnabled( true );
webView.getSettings().setJavaScriptEnabled( true );
// Go to Default URL
webView.loadUrl("http://google.com" );
// Long Click Listener
webView.setOnLongClickListener(new OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
// Grab URL
String webUrl = webView.getUrl();
// Show the URL (This works)
Toast.makeText(getApplicationContext(), webUrl, Toast.LENGTH_SHORT).show();
// This request crashes
webView.loadUrl("http://www.yahoo.com");
return true;
}
});
}
// Back Button behaviour (Either browser back, or exit)
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
WebView webView = (WebView) findViewById(R.id.webView1);
if(event.getAction() == KeyEvent.ACTION_DOWN){
switch(keyCode)
{
case KeyEvent.KEYCODE_BACK:
if(webView.canGoBack()){
webView.goBack();
}else{
finish();
}
return true;
}
}
return super.onKeyDown(keyCode, event);
}
}
And my Logcat:
Code:
12-01 01:48:40.579: W/dalvikvm(15534): threadid=1: thread exiting with uncaught exception (group=0x418eac08)
12-01 01:48:40.584: E/AndroidRuntime(15534): FATAL EXCEPTION: main
12-01 01:48:40.584: E/AndroidRuntime(15534): Process: com.example.homehub, PID: 15534
12-01 01:48:40.584: E/AndroidRuntime(15534): java.lang.NullPointerException
12-01 01:48:40.584: E/AndroidRuntime(15534): at com.android.org.chromium.content.browser.LongPressDetector.dispatchLongPress(LongPressDetector.java:158)
12-01 01:48:40.584: E/AndroidRuntime(15534): at com.android.org.chromium.content.browser.LongPressDetector.access$000(LongPressDetector.java:21)
12-01 01:48:40.584: E/AndroidRuntime(15534): at com.android.org.chromium.content.browser.LongPressDetector$LongPressHandler.handleMessage(LongPressDetector.java:58)
12-01 01:48:40.584: E/AndroidRuntime(15534): at android.os.Handler.dispatchMessage(Handler.java:102)
12-01 01:48:40.584: E/AndroidRuntime(15534): at android.os.Looper.loop(Looper.java:146)
12-01 01:48:40.584: E/AndroidRuntime(15534): at android.app.ActivityThread.main(ActivityThread.java:5653)
12-01 01:48:40.584: E/AndroidRuntime(15534): at java.lang.reflect.Method.invokeNative(Native Method)
12-01 01:48:40.584: E/AndroidRuntime(15534): at java.lang.reflect.Method.invoke(Method.java:515)
12-01 01:48:40.584: E/AndroidRuntime(15534): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1291)
12-01 01:48:40.584: E/AndroidRuntime(15534): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1107)
12-01 01:48:40.584: E/AndroidRuntime(15534): at dalvik.system.NativeStart.main(Native Method)

Categories

Resources