I need your help.
My App works fine on GingerBread, but on ICS and HC crash.
This is the logcat
01-14 20:26:51.831: E/AndroidRuntime(698): FATAL EXCEPTION: main
01-14 20:26:51.831: E/AndroidRuntime(698): android.os.NetworkOnMainThreadException
01-14 20:26:51.831: E/AndroidRuntime(698): at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1099)
01-14 20:26:51.831: E/AndroidRuntime(698): at java.net.InetAddress.lookupHostByName(InetAddress.java:391)
01-14 20:26:51.831: E/AndroidRuntime(698): at java.net.InetAddress.getAllByNameImpl(InetAddress.java:242)
01-14 20:26:51.831: E/AndroidRuntime(698): at java.net.InetAddress.getAllByName(InetAddress.java:220)
01-14 20:26:51.831: E/AndroidRuntime(698): at libcore.net.http.HttpConnection.<init>(HttpConnection.java:71)
01-14 20:26:51.831: E/AndroidRuntime(698): at libcore.net.http.HttpConnection.<init>(HttpConnection.java:50)
01-14 20:26:51.831: E/AndroidRuntime(698): at libcore.net.http.HttpConnection$Address.connect(HttpConnection.java:351)
01-14 20:26:51.831: E/AndroidRuntime(698): at libcore.net.http.HttpConnectionPool.get(HttpConnectionPool.java:86)
01-14 20:26:51.831: E/AndroidRuntime(698): at libcore.net.http.HttpConnection.connect(HttpConnection.java:128)
01-14 20:26:51.831: E/AndroidRuntime(698): at libcore.net.http.HttpEngine.openSocketConnection(HttpEngine.java:308)
01-14 20:26:51.831: E/AndroidRuntime(698): at libcore.net.http.HttpEngine.connect(HttpEngine.java:303)
01-14 20:26:51.831: E/AndroidRuntime(698): at libcore.net.http.HttpEngine.sendSocketRequest(HttpEngine.java:282)
01-14 20:26:51.831: E/AndroidRuntime(698): at libcore.net.http.HttpEngine.sendRequest(HttpEngine.java:232)
01-14 20:26:51.831: E/AndroidRuntime(698): at libcore.net.http.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:80)
01-14 20:26:51.831: E/AndroidRuntime(698): at com.bozz.milaircraft.f23$ImageAdapter.getView(f23.java:125)
01-14 20:26:51.831: E/AndroidRuntime(698): at android.widget.AbsSpinner.onMeasure(AbsSpinner.java:192)
01-14 20:26:51.831: E/AndroidRuntime(698): at android.view.View.measure(View.java:12723)
01-14 20:26:51.831: E/AndroidRuntime(698): at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4698)
01-14 20:26:51.831: E/AndroidRuntime(698): at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1369)
01-14 20:26:51.831: E/AndroidRuntime(698): at android.widget.LinearLayout.measureVertical(LinearLayout.java:660)
01-14 20:26:51.831: E/AndroidRuntime(698): at android.widget.LinearLayout.onMeasure(LinearLayout.java:553)
01-14 20:26:51.831: E/AndroidRuntime(698): at android.view.View.measure(View.java:12723)
01-14 20:26:51.831: E/AndroidRuntime(698): at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4698)
01-14 20:26:51.831: E/AndroidRuntime(698): at android.widget.FrameLayout.onMeasure(FrameLayout.java:293)
01-14 20:26:51.831: E/AndroidRuntime(698): at android.view.View.measure(View.java:12723)
01-14 20:26:51.831: E/AndroidRuntime(698): at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4698)
01-14 20:26:51.831: E/AndroidRuntime(698): at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1369)
01-14 20:26:51.831: E/AndroidRuntime(698): at android.widget.LinearLayout.measureVertical(LinearLayout.java:660)
01-14 20:26:51.831: E/AndroidRuntime(698): at android.widget.LinearLayout.onMeasure(LinearLayout.java:553)
01-14 20:26:51.831: E/AndroidRuntime(698): at android.view.View.measure(View.java:12723)
01-14 20:26:51.831: E/AndroidRuntime(698): at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4698)
01-14 20:26:51.831: E/AndroidRuntime(698): at android.widget.FrameLayout.onMeasure(FrameLayout.java:293)
01-14 20:26:51.831: E/AndroidRuntime(698): at android.view.View.measure(View.java:12723)
01-14 20:26:51.831: E/AndroidRuntime(698): at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4698)
01-14 20:26:51.831: E/AndroidRuntime(698): at android.widget.LinearLayout.measureChildBeforeLayout(LinearLayout.java:1369)
01-14 20:26:51.831: E/AndroidRuntime(698): at android.widget.LinearLayout.measureVertical(LinearLayout.java:660)
01-14 20:26:51.831: E/AndroidRuntime(698): at android.widget.LinearLayout.onMeasure(LinearLayout.java:553)
01-14 20:26:51.831: E/AndroidRuntime(698): at android.view.View.measure(View.java:12723)
01-14 20:26:51.831: E/AndroidRuntime(698): at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4698)
01-14 20:26:51.831: E/AndroidRuntime(698): at android.widget.FrameLayout.onMeasure(FrameLayout.java:293)
01-14 20:26:51.831: E/AndroidRuntime(698): at android.view.View.measure(View.java:12723)
01-14 20:26:51.831: E/AndroidRuntime(698): at android.widget.LinearLayout.measureVertical(LinearLayout.java:812)
01-14 20:26:51.831: E/AndroidRuntime(698): at android.widget.LinearLayout.onMeasure(LinearLayout.java:553)
01-14 20:26:51.831: E/AndroidRuntime(698): at android.view.View.measure(View.java:12723)
01-14 20:26:51.831: E/AndroidRuntime(698): at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4698)
01-14 20:26:51.831: E/AndroidRuntime(698): at android.widget.FrameLayout.onMeasure(FrameLayout.java:293)
01-14 20:26:51.831: E/AndroidRuntime(698): at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2092)
01-14 20:26:51.831: E/AndroidRuntime(698): at android.view.View.measure(View.java:12723)
01-14 20:26:51.831: E/AndroidRuntime(698): at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1064)
01-14 20:26:51.831: E/AndroidRuntime(698): at android.view.ViewRootImpl.handleMessage(ViewRootImpl.java:2442)
01-14 20:26:51.831: E/AndroidRuntime(698): at android.os.Handler.dispatchMessage(Handler.java:99)
01-14 20:26:51.831: E/AndroidRuntime(698): at android.os.Looper.loop(Looper.java:137)
01-14 20:26:51.831: E/AndroidRuntime(698): at android.app.ActivityThread.main(ActivityThread.java:4424)
01-14 20:26:51.831: E/AndroidRuntime(698): at java.lang.reflect.Method.invokeNative(Native Method)
01-14 20:26:51.831: E/AndroidRuntime(698): at java.lang.reflect.Method.invoke(Method.java:511)
01-14 20:26:51.831: E/AndroidRuntime(698): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
01-14 20:26:51.831: E/AndroidRuntime(698): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
01-14 20:26:51.831: E/AndroidRuntime(698): at dalvik.system.NativeStart.main(Native Method)
Here is the layout.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<LinearLayout
android:id="#+id/linearLayout3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#000"
android:paddingBottom="5dp"
android:paddingTop="5dp" >
<Button
android:id="#+id/homebutton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:background="#drawable/homebutton" />
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_weight="1"
android:gravity="center"
android:text="#string/nomeF22Raptor"
android:textColor="#FFD800"
android:textSize="22dp"
android:textStyle="bold" />
<Button
android:id="#+id/searchbutton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:background="#drawable/searchbutton" >
</Button>
</LinearLayout>
<TabHost
android:id="#+id/tabhost"
android:layout_width="match_parent"
android:layout_height="420dp"
android:layout_weight="0.80"
android:background="#drawable/background" >
<LinearLayout
android:id="#+id/linearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TabWidget
android:id="#android:id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</TabWidget>
<FrameLayout
android:id="#android:id/tabcontent"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<LinearLayout
android:id="#+id/tab1"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<ScrollView
android:id="#+id/ScrollView01"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<LinearLayout
android:id="#+id/linearLayout2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/datiF22Raptor" />
</LinearLayout>
</ScrollView>
</LinearLayout>
<LinearLayout
android:id="#+id/tab2"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<ScrollView
android:id="#+id/ScrollView01"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<LinearLayout
android:id="#+id/linearLayout2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/cartecF22Raptor" />
</LinearLayout>
</ScrollView>
</LinearLayout>
<LinearLayout
android:id="#+id/tab3"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<ScrollView
android:id="#+id/ScrollView01"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<LinearLayout
android:id="#+id/linearLayout2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/utilizzatoriF22Raptor" />
</LinearLayout>
</ScrollView>
</LinearLayout>
<LinearLayout
android:id="#+id/tab4"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<Gallery
android:id="#+id/gallery"
android:layout_width="fill_parent"
android:layout_height="fill_parent"/>
<ImageView
android:id="#+id/ImageView01"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:layout_gravity="center" >
</ImageView>
</LinearLayout>
</FrameLayout>
</LinearLayout>
</TabHost>
</LinearLayout>
and this is the java code
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.Gallery;
import android.widget.ImageView;
import android.widget.TabHost;
import android.widget.TabHost.TabSpec;
public class f23 extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.f23);
Button bhome = (Button) findViewById(R.id.homebutton);
bhome.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
startActivity(new Intent("com.bozz.milaircraft.MENU"));
}
});
TabHost th = (TabHost) findViewById(R.id.tabhost);
th.setup();
TabSpec specs = th.newTabSpec("tag1");
specs.setContent(R.id.tab1);
specs.setIndicator("BRIEFING");
th.addTab(specs);
specs = th.newTabSpec("tag2");
specs.setContent(R.id.tab2);
specs.setIndicator("DESIGN");
th.addTab(specs);
specs = th.newTabSpec("tag3");
specs.setContent(R.id.tab3);
specs.setIndicator("USERS");
th.addTab(specs);
specs = th.newTabSpec("tag4");
specs.setContent(R.id.tab4);
specs.setIndicator("GALLERY");
th.addTab(specs);
Gallery ga = (Gallery) findViewById(R.id.gallery);
ga.setAdapter(new ImageAdapter(this));
}
public class ImageAdapter extends BaseAdapter {
/** The parent context */
private Context myContext;
int imageBackground;
/** URL-Strings to some remote images. */
private String[] myRemoteImages = {
"http://www.medicinarozzano.it/images/milair/f4_1.jpg",
"http://www.medicinarozzano.it/images/milair/f4_2.jpg",
"http://www.medicinarozzano.it/images/milair/f4_3.jpg",
"http://www.medicinarozzano.it/images/milair/f4_4.jpg",
"http://www.medicinarozzano.it/images/milair/f4_5.jpg",
"http://www.medicinarozzano.it/images/milair/f4_6.jpg",
"http://www.medicinarozzano.it/images/milair/f4_7.jpg",
"http://www.medicinarozzano.it/images/milair/f4_8.jpg",
"http://www.medicinarozzano.it/images/milair/f4_9.jpg",
"http://www.medicinarozzano.it/images/milair/f4_10.jpg"};
/** Simple Constructor saving the 'parent' context. */
public ImageAdapter(Context c) {
this.myContext = c;
}
/** Returns the amount of images we have defined. */
public int getCount() {
return this.myRemoteImages.length;
}
/* Use the array-Positions as unique IDs */
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
/**
* Returns a new ImageView to be displayed, depending on the position
* passed.
*/
public View getView(int position, View convertView, ViewGroup parent) {
ImageView i = new ImageView(this.myContext);
try {
/* Open a new URL and get the InputStream to load data from it. */
URL aURL = new URL(myRemoteImages[position]);
URLConnection conn = aURL.openConnection();
conn.connect();
InputStream is = conn.getInputStream();
/* Buffered is always good for a performance plus. */
BufferedInputStream bis = new BufferedInputStream(is);
/* Decode url-data to a bitmap. */
Bitmap bm = BitmapFactory.decodeStream(bis);
bis.close();
is.close();
/* Apply the Bitmap to the ImageView that will be returned. */
i.setImageBitmap(bm);
} catch (IOException e) {
i.setImageResource(R.drawable.f4_1);
Log.e("DEBUGTAG", "Remote Image Exception", e);
}
/* Image should be scaled as width/height are set. */
i.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
/* Set the Width/Height of the ImageView. */
i.setLayoutParams(new Gallery.LayoutParams(480, 640));
return i;
}
/**
* Returns the size (0.0f to 1.0f) of the views depending on the
* 'offset' to the center.
*/
public float getScale(boolean focused, int offset) {
/* Formula: 1 / (2 ^ offset) */
return Math.max(0, 1.0f / (float) Math.pow(2, Math.abs(offset)));
}
}
}
The App crash when I click on the Gallery Tab.
It is a bad idea to perform (potentially blocking) network operations on your app's main thread, which is what you are doing. Before Honeycomb (Android 3.0), it was just a bad idea. From Android 3.0 onwards, it is prohibited, and you receive this exception if you try to do so.
See http://developer.android.com/reference/android/os/NetworkOnMainThreadException.html
You need to farm out this network logic to a separate asynchronous thread. Or, look at a Handler. You're going to need to change your code architecture; no easy fix.
In Honeycomb networking is not allowed on the UI thread. The reason is that it slows down the user interface (UI).
Instead try to download your images in an background thread, the easiest way to implement this is using an AsyncTask.
Use it at your own risk:
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll()
.build();
StrictMode.setThreadPolicy(policy);
Resource:
http://developer.android.com/reference/android/os/StrictMode.ThreadPolicy.Builder.html
You can see the version of the OS, and execute a code depending of it.
For example:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.GINGERBREAD)
This is how I solve the problem:
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.entity.BufferedHttpEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.Gallery;
import android.widget.ImageView;
import android.widget.TabHost;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.TabHost.TabSpec;
public class f24 extends Activity {
private ImageAdapter imageAdapter;
private ArrayList<String> PhotoURLS = new ArrayList<String>();
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.f24);
Button bhome = (Button) findViewById(R.id.homebutton);
bhome.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
startActivity(new Intent ("com.bozz.milaircraft.MENU"));
}
});
TabHost th = (TabHost) findViewById(R.id.tabhost);
th.setup();
TabSpec specs = th.newTabSpec("tag1");
specs.setContent(R.id.tab1);
specs.setIndicator("BRIEFING");
th.addTab(specs);
specs = th.newTabSpec("tag2");
specs.setContent(R.id.tab2);
specs.setIndicator("DESIGN");
th.addTab(specs);
specs = th.newTabSpec("tag3");
specs.setContent(R.id.tab3);
specs.setIndicator("USERS");
th.addTab(specs);
specs = th.newTabSpec("tag4");
specs.setContent(R.id.tab4);
specs.setIndicator("GALLERY");
th.addTab(specs);
imageAdapter = new ImageAdapter(this);
final ImageView imgView = (ImageView) findViewById(R.id.GalleryView);
Gallery g = (Gallery) findViewById(R.id.Gallery);
g.setAdapter(imageAdapter);
g.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v,
int position, long id) {
imgView.setImageDrawable(LoadImageFromURL(PhotoURLS
.get(position)));
imgView.setScaleType(ImageView.ScaleType.FIT_CENTER);
}
});
// replace this code to set your image urls in list
PhotoURLS.add("http://www.medicinarozzano.it/images/milair/f4_1.jpg");
PhotoURLS.add("http://www.medicinarozzano.it/images/milair/f4_1.jpg");
new AddImageTask().execute();
}
class AddImageTask extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... unused) {
for (String url : PhotoURLS) {
String filename = url.substring(url.lastIndexOf("/") + 1,
url.length());
filename = "th_" + filename;
String thumburl = url.substring(0, url.lastIndexOf("/") + 1);
imageAdapter.addItem(LoadThumbnailFromURL(thumburl + filename));
publishProgress();
//SystemClock.sleep(200);
}
return (null);
}
#Override
protected void onProgressUpdate(Void... unused) {
imageAdapter.notifyDataSetChanged();
}
#Override
protected void onPostExecute(Void unused) {
}
}
private Drawable LoadThumbnailFromURL(String url) {
try {
URLConnection connection = new URL(url).openConnection();
String contentType = connection.getHeaderField("Content-Type");
boolean isImage = contentType.startsWith("image/");
if(isImage){
HttpGet httpRequest = new HttpGet(url);
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = (HttpResponse) httpclient
.execute(httpRequest);
HttpEntity entity = response.getEntity();
BufferedHttpEntity bufferedHttpEntity = new BufferedHttpEntity(entity);
InputStream is = bufferedHttpEntity.getContent();
Drawable d = Drawable.createFromStream(is, "src Name");
return d;
} else {
Bitmap b = BitmapFactory.decodeResource(getResources(), R.drawable.no_image);
Drawable d = new BitmapDrawable(b);
return d;
}
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "Error", Toast.LENGTH_LONG)
.show();
Log.e(e.getClass().getName(), e.getMessage(), e);
return null;
}
}
private Drawable LoadImageFromURL(String url) {
try {
URLConnection connection = new URL(url).openConnection();
String contentType = connection.getHeaderField("Content-Type");
boolean isImage = contentType.startsWith("image/");
if(isImage){
HttpGet httpRequest = new HttpGet(url);
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = (HttpResponse) httpclient
.execute(httpRequest);
HttpEntity entity = response.getEntity();
BufferedHttpEntity bufferedHttpEntity = new BufferedHttpEntity(
entity);
InputStream is = bufferedHttpEntity.getContent();
// Decode image size
BitmapFactory.Options o = new BitmapFactory.Options();
o.inJustDecodeBounds = true;
BitmapFactory.decodeStream(is, null, o);
// The new size we want to scale to
final int REQUIRED_SIZE = 150;
// Find the correct scale value. It should be the power of 2.
int width_tmp = o.outWidth, height_tmp = o.outHeight;
int scale = 1;
while (true) {
if (width_tmp / 2 < REQUIRED_SIZE
|| height_tmp / 2 < REQUIRED_SIZE)
break;
width_tmp /= 2;
height_tmp /= 2;
scale *= 2;
}
// Decode with inSampleSize
is = bufferedHttpEntity.getContent();
BitmapFactory.Options o2 = new BitmapFactory.Options();
o2.inSampleSize = scale;
Bitmap b = BitmapFactory.decodeStream(is, null, o2);
Drawable d = new BitmapDrawable(b);
return d;
} else {
Bitmap b = BitmapFactory.decodeResource(getResources(), R.drawable.no_image);
Drawable d = new BitmapDrawable(b);
return d;
}
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "Error", Toast.LENGTH_LONG)
.show();
Log.e(e.getClass().getName(), e.getMessage(), e);
return null;
}
}
public class ImageAdapter extends BaseAdapter {
int mGalleryItemBackground;
private Context mContext;
ArrayList<Drawable> drawablesFromUrl = new ArrayList<Drawable>();
public ImageAdapter(Context c) {
mContext = c;
TypedArray a = obtainStyledAttributes(R.styleable.Gallery1);
mGalleryItemBackground = a.getResourceId(
R.styleable.Gallery1_android_galleryItemBackground, 0);
a.recycle();
}
public void addItem(Drawable item) {
drawablesFromUrl.add(item);
}
public int getCount() {
return drawablesFromUrl.size();
}
public Drawable getItem(int position) {
return drawablesFromUrl.get(position);
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ImageView i = new ImageView(mContext);
i.setImageDrawable(drawablesFromUrl.get(position));
i.setLayoutParams(new Gallery.LayoutParams(150, 120));
i.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
i.setBackgroundResource(mGalleryItemBackground);
return i;
}
}
}
But now I have another problem:
If i don not declare any SDK on Android Manifest, the app works perfectly on both gingerbread and HC, and ICS. However, if i declare a minimum SDK greater than 1 or TargetSDK, the app works fine on gingerbread but not on HC and ISC. When i click on an image in the gallery nothing appears on the image viewer. Yet, a toast error pops up.
Also, if there is no internet connection the app crashes.
Best regards
Tiberio Bozotti
EDIT:
i could remove the SDK but on honeycomb it is not clear. Meaning that the layout is not compatible.
Related
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 8 years ago.
Hi I am encountering a null pointer error when I click on the activity Links. The purpose of my feature is to call a list of links in the form of list view. Below is the logcat and as far as I understand it is coming from my onItemClickListener, but I can't seem to point out the null error.:
sitesList.setOnItemClickListener(new OnItemClickListener()
Links.java
package com.example.sgrecipe;
import java.io.FileNotFoundException;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
public class Links extends Activity {
private SitesAdapter mAdapter;
private ListView sitesList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.i("StackSites", "OnCreate()");
setContentView(R.layout.activity_main);
//Get reference to our ListView
sitesList = (ListView)findViewById(R.id.sitesList);
//Set the click listener to launch the browser when a row is clicked.
sitesList.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View v, int pos,long id) {
String url = mAdapter.getItem(pos).getLink();
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
startActivity(i);
}
});
/*
* If network is available download the xml from the Internet.
* If not then try to use the local file from last time.
*/
if(isNetworkAvailable()){
Log.i("StackSites", "starting download Task");
SitesDownloadTask download = new SitesDownloadTask();
download.execute();
}else{
mAdapter = new SitesAdapter(getApplicationContext(), -1, SitesXmlPullParser.getStackSitesFromFile(Links.this));
sitesList.setAdapter(mAdapter);
}
}
//Helper method to determine if Internet connection is available.
private boolean isNetworkAvailable() {
ConnectivityManager connectivityManager
= (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
/*
* AsyncTask that will download the xml file for us and store it locally.
* After the download is done we'll parse the local file.
*/
private class SitesDownloadTask extends AsyncTask<Void, Void, Void>{
#Override
protected Void doInBackground(Void... arg0) {
//Download the file
try {
Downloader.DownloadFromUrl("https://dl.dropboxusercontent.com/u/5724095/XmlParseExample/stacksites.xml", openFileOutput("StackSites.xml", Context.MODE_PRIVATE));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result){
//setup our Adapter and set it to the ListView.
mAdapter = new SitesAdapter(Links.this, -1, SitesXmlPullParser.getStackSitesFromFile(Links.this));
sitesList.setAdapter(mAdapter);
Log.i("StackSites", "adapter size = "+ mAdapter.getCount());
}
}
}
activity_links.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".Links" >
<ListView
android:id="#+id/sitesList"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
row_site.xml (for the listview)
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10dp" >
<ProgressBar
android:id="#+id/progress"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<ImageView
android:id="#+id/iconImg"
android:layout_width="80dp"
android:layout_height="80dp"
android:layout_marginRight="8dp" />
<TextView
android:id="#+id/nameTxt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#id/iconImg"
android:textSize="16sp"
android:textStyle="bold" />
<TextView
android:id="#+id/aboutTxt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#id/iconImg"
android:textSize="12sp"
android:layout_below="#id/nameTxt"
/>
</RelativeLayout>
Here is the logcat:
02-23 15:13:10.856: E/AndroidRuntime(8201): FATAL EXCEPTION: main
02-23 15:13:10.856: E/AndroidRuntime(8201): Process: com.example.sgrecipe, PID: 8201
02-23 15:13:10.856: E/AndroidRuntime(8201): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.sgrecipe/com.example.sgrecipe.Links}: java.lang.NullPointerException
02-23 15:13:10.856: E/AndroidRuntime(8201): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2292)
02-23 15:13:10.856: E/AndroidRuntime(8201): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2350)
02-23 15:13:10.856: E/AndroidRuntime(8201): at android.app.ActivityThread.access$800(ActivityThread.java:163)
02-23 15:13:10.856: E/AndroidRuntime(8201): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1257)
02-23 15:13:10.856: E/AndroidRuntime(8201): at android.os.Handler.dispatchMessage(Handler.java:102)
02-23 15:13:10.856: E/AndroidRuntime(8201): at android.os.Looper.loop(Looper.java:157)
02-23 15:13:10.856: E/AndroidRuntime(8201): at android.app.ActivityThread.main(ActivityThread.java:5335)
02-23 15:13:10.856: E/AndroidRuntime(8201): at java.lang.reflect.Method.invokeNative(Native Method)
02-23 15:13:10.856: E/AndroidRuntime(8201): at java.lang.reflect.Method.invoke(Method.java:515)
02-23 15:13:10.856: E/AndroidRuntime(8201): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1265)
02-23 15:13:10.856: E/AndroidRuntime(8201): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1081)
02-23 15:13:10.856: E/AndroidRuntime(8201): at dalvik.system.NativeStart.main(Native Method)
02-23 15:13:10.856: E/AndroidRuntime(8201): Caused by: java.lang.NullPointerException
02-23 15:13:10.856: E/AndroidRuntime(8201): at com.example.sgrecipe.Links.onCreate(Links.java:36)
02-23 15:13:10.856: E/AndroidRuntime(8201): at android.app.Activity.performCreate(Activity.java:5389)
02-23 15:13:10.856: E/AndroidRuntime(8201): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1105)
02-23 15:13:10.856: E/AndroidRuntime(8201): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2256)
Any help is really appreciate, thank you!
Change following line
setContentView(R.layout.activity_main);
to
setContentView(R.layout.activity_links);
Seems like your using different layouts:
setContentView(R.layout.activity_main);
vs
activity_links.xml
This question already has answers here:
NullPointerException accessing views in onCreate()
(13 answers)
Closed 8 years ago.
I am having trouble finding the source of the crash in my application. I've done a clean/build. I'm very new to Android dev so I'm still learning. From looking at the logcat, I think there maybe some null error exception that might have something to do with the calculate function. Any help or guidance is appreciated.
The java code:
package com.example.rectangle;
import java.text.DecimalFormat;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.content.Context;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;
import android.os.Build;
public class MainActivity extends ActionBarActivity implements OnEditorActionListener {
//graphical variables
private EditText widthInput;
private EditText heightInput;
private TextView areaOutput;
private TextView perimeterOutput;
private Button calculateButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//assign ids to graphical variables
widthInput = (EditText) findViewById(R.id.widthEditText);
heightInput = (EditText) findViewById(R.id.heightEditText);
areaOutput = (TextView) findViewById(R.id.areaOutput);
perimeterOutput = (TextView) findViewById(R.id.perimterOutput);
calculateButton = (Button) findViewById(R.id.calculateButton);
widthInput.setOnEditorActionListener(this);
heightInput.setOnEditorActionListener(this);
//calculate and display
calculateAreaAndPerimeter();
}
//hide keyboard
//source: http://stackoverflow.com/questions/8697499/hide-keyboard-when-user-taps-anywhere-else-on-the-screen-in-android
#Override
public boolean onTouchEvent(MotionEvent event) {
InputMethodManager imm = (InputMethodManager)getSystemService(Context.
INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
return true;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, 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);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
return rootView;
}
}
//display
public void display(String area, String perimeter)
{
areaOutput.setText(area);
perimeterOutput.setText(perimeter);
}
//algorithms
private void calculateAreaAndPerimeter()
{
//get width and height
String widthInputString = widthInput.getText().toString();
String heightInputString = heightInput.getText().toString();
float width = Float.parseFloat(widthInputString);
float height = Float.parseFloat(heightInputString);
//calculate and display
DecimalFormat df = new DecimalFormat();
df.setMaximumFractionDigits(2);
float area;
area = width * height;
String areaString = (df.format(area)) + "";
float perimeter;
perimeter = (width * 2) + (height * 2);
String perimeterString = (df.format(perimeter)) + "";
display(areaString, perimeterString);
}
#Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
// TODO Auto-generated method stub
calculateAreaAndPerimeter();
return false;
}
}
The logcat:
11-12 13:05:14.049: E/AndroidRuntime(10535): FATAL EXCEPTION: main
11-12 13:05:14.049: E/AndroidRuntime(10535): Process: com.example.rectangle, PID: 10535
11-12 13:05:14.049: E/AndroidRuntime(10535): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.rectangle/com.example.rectangle.MainActivity}: java.lang.NullPointerException
11-12 13:05:14.049: E/AndroidRuntime(10535): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2198)
11-12 13:05:14.049: E/AndroidRuntime(10535): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2257)
11-12 13:05:14.049: E/AndroidRuntime(10535): at android.app.ActivityThread.access$800(ActivityThread.java:139)
11-12 13:05:14.049: E/AndroidRuntime(10535): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1210)
11-12 13:05:14.049: E/AndroidRuntime(10535): at android.os.Handler.dispatchMessage(Handler.java:102)
11-12 13:05:14.049: E/AndroidRuntime(10535): at android.os.Looper.loop(Looper.java:136)
11-12 13:05:14.049: E/AndroidRuntime(10535): at android.app.ActivityThread.main(ActivityThread.java:5086)
11-12 13:05:14.049: E/AndroidRuntime(10535): at java.lang.reflect.Method.invokeNative(Native Method)
11-12 13:05:14.049: E/AndroidRuntime(10535): at java.lang.reflect.Method.invoke(Method.java:515)
11-12 13:05:14.049: E/AndroidRuntime(10535): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
11-12 13:05:14.049: E/AndroidRuntime(10535): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
11-12 13:05:14.049: E/AndroidRuntime(10535): at dalvik.system.NativeStart.main(Native Method)
11-12 13:05:14.049: E/AndroidRuntime(10535): Caused by: java.lang.NullPointerException
11-12 13:05:14.049: E/AndroidRuntime(10535): at com.example.rectangle.MainActivity.onCreate(MainActivity.java:46)
11-12 13:05:14.049: E/AndroidRuntime(10535): at android.app.Activity.performCreate(Activity.java:5248)
11-12 13:05:14.049: E/AndroidRuntime(10535): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1110)
11-12 13:05:14.049: E/AndroidRuntime(10535): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2162)
11-12 13:05:14.049: E/AndroidRuntime(10535): ... 11 more
Fragment_main
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".MainActivity$PlaceholderFragment" >
<TextView
android:id="#+id/heightTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/widthTextView"
android:layout_below="#+id/widthTextView"
android:layout_marginTop="29dp"
android:text="Height"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/areaTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/heightTextView"
android:layout_below="#+id/heightTextView"
android:layout_marginTop="30dp"
android:text="Area"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/perimeterTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/areaTextView"
android:layout_below="#+id/areaTextView"
android:layout_marginTop="40dp"
android:text="Perimeter"
android:textAppearance="?android:attr/textAppearanceMedium" />
<EditText
android:id="#+id/heightEditText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/heightTextView"
android:layout_alignLeft="#+id/widthEditText"
android:layout_alignRight="#+id/widthEditText"
android:ems="10"
android:inputType="numberSigned"
android:text="0.0" />
<TextView
android:id="#+id/widthTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginTop="35dp"
android:text="Width"
android:textAppearance="?android:attr/textAppearanceMedium" />
<EditText
android:id="#+id/widthEditText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/heightTextView"
android:layout_alignParentRight="true"
android:ems="10"
android:inputType="numberDecimal"
android:text="0.0" />
<TextView
android:id="#+id/areaOutput"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/areaTextView"
android:layout_marginLeft="38dp"
android:layout_toRightOf="#+id/perimeterTextView"
android:text="0.0"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/perimterOutput"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/perimeterTextView"
android:layout_alignBottom="#+id/perimeterTextView"
android:layout_alignLeft="#+id/areaOutput"
android:text="0.0"
android:textAppearance="?android:attr/textAppearanceMedium" />
</RelativeLayout>
Try this:
TextView.OnEditorActionListener listener = new TextView.OnEditorActionListener() {
#Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
// TODO Auto-generated method stub
calculateAreaAndPerimeter();
return false;
}
};
The compile may still want to the one you have, and if, so create one like the above.
I think you have to tell the compiler its a listener, even though it may have created the method you have. Android Studio doesn't create listener syntax very well and I typically have to go back and surround a new public method with the listener stuff. Hope that works!
I am trying to create a simple application that can sign in / sign up users . All the data are
stored in Mysql database .
My app was installed successfully but as I opened it, it gave an error saying "Unfortunately, 'myapp' has stop working".
I have read almost all related problems posted here but no luck!
here's from logcat .
07-25 01:22:31.452: E/AndroidRuntime(2101): FATAL EXCEPTION: main
07-25 01:22:31.452: E/AndroidRuntime(2101): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.mysqltest/com.example.mobileapp.MainActivity}: android.view.InflateException: Binary XML file line #2: Error inflating class android.widget.RelativeLayout
07-25 01:22:31.452: E/AndroidRuntime(2101): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2211)
07-25 01:22:31.452: E/AndroidRuntime(2101): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
07-25 01:22:31.452: E/AndroidRuntime(2101): at android.app.ActivityThread.access$600(ActivityThread.java:141)
07-25 01:22:31.452: E/AndroidRuntime(2101): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
07-25 01:22:31.452: E/AndroidRuntime(2101): at android.os.Handler.dispatchMessage(Handler.java:99)
07-25 01:22:31.452: E/AndroidRuntime(2101): at android.os.Looper.loop(Looper.java:137)
07-25 01:22:31.452: E/AndroidRuntime(2101): at android.app.ActivityThread.main(ActivityThread.java:5103)
07-25 01:22:31.452: E/AndroidRuntime(2101): at java.lang.reflect.Method.invokeNative(Native Method)
07-25 01:22:31.452: E/AndroidRuntime(2101): at java.lang.reflect.Method.invoke(Method.java:525)
07-25 01:22:31.452: E/AndroidRuntime(2101): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
07-25 01:22:31.452: E/AndroidRuntime(2101): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
07-25 01:22:31.452: E/AndroidRuntime(2101): at dalvik.system.NativeStart.main(Native Method)
07-25 01:22:31.452: E/AndroidRuntime(2101): Caused by: android.view.InflateException: Binary XML file line #2: Error inflating class android.widget.RelativeLayout
07-25 01:22:31.452: E/AndroidRuntime(2101): at android.view.LayoutInflater.createView(LayoutInflater.java:620)
07-25 01:22:31.452: E/AndroidRuntime(2101): at com.android.internal.policy.impl.PhoneLayoutInflater.onCreateView(PhoneLayoutInflater.java:56)
07-25 01:22:31.452: E/AndroidRuntime(2101): at android.view.LayoutInflater.onCreateView(LayoutInflater.java:669)
07-25 01:22:31.452: E/AndroidRuntime(2101): at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:694)
07-25 01:22:31.452: E/AndroidRuntime(2101): at android.view.LayoutInflater.inflate(LayoutInflater.java:469)
07-25 01:22:31.452: E/AndroidRuntime(2101): at android.view.LayoutInflater.inflate(LayoutInflater.java:397)
07-25 01:22:31.452: E/AndroidRuntime(2101): at android.view.LayoutInflater.inflate(LayoutInflater.java:353)
07-25 01:22:31.452: E/AndroidRuntime(2101): at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:267)
07-25 01:22:31.452: E/AndroidRuntime(2101): at android.app.Activity.setContentView(Activity.java:1895)
07-25 01:22:31.452: E/AndroidRuntime(2101): at com.example.mobileapp.MainActivity.onCreate(MainActivity.java:45)
07-25 01:22:31.452: E/AndroidRuntime(2101): at android.app.Activity.performCreate(Activity.java:5133)
07-25 01:22:31.452: E/AndroidRuntime(2101): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
07-25 01:22:31.452: E/AndroidRuntime(2101): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2175)
07-25 01:22:31.452: E/AndroidRuntime(2101): ... 11 more
07-25 01:22:31.452: E/AndroidRuntime(2101): Caused by: java.lang.reflect.InvocationTargetException
07-25 01:22:31.452: E/AndroidRuntime(2101): at java.lang.reflect.Constructor.constructNative(Native Method)
07-25 01:22:31.452: E/AndroidRuntime(2101): at java.lang.reflect.Constructor.newInstance(Constructor.java:417)
07-25 01:22:31.452: E/AndroidRuntime(2101): at android.view.LayoutInflater.createView(LayoutInflater.java:594)
07-25 01:22:31.452: E/AndroidRuntime(2101): ... 23 more
07-25 01:22:31.452: E/AndroidRuntime(2101): Caused by: java.lang.OutOfMemoryError
07-25 01:22:31.452: E/AndroidRuntime(2101): at android.graphics.BitmapFactory.nativeDecodeAsset(Native Method)
07-25 01:22:31.452: E/AndroidRuntime(2101): at android.graphics.BitmapFactory.decodeStream(BitmapFactory.java:503)
07-25 01:22:31.452: E/AndroidRuntime(2101): at android.graphics.BitmapFactory.decodeResourceStream(BitmapFactory.java:356)
07-25 01:22:31.452: E/AndroidRuntime(2101): at android.graphics.drawable.Drawable.createFromResourceStream(Drawable.java:800)
07-25 01:22:31.452: E/AndroidRuntime(2101): at android.content.res.Resources.loadDrawable(Resources.java:2105)
07-25 01:22:31.452: E/AndroidRuntime(2101): at android.content.res.TypedArray.getDrawable(TypedArray.java:601)
07-25 01:22:31.452: E/AndroidRuntime(2101): at android.view.View.<init>(View.java:3364)
07-25 01:22:31.452: E/AndroidRuntime(2101): at android.view.View.<init>(View.java:3293)
07-25 01:22:31.452: E/AndroidRuntime(2101): at android.view.ViewGroup.<init>(ViewGroup.java:453)
07-25 01:22:31.452: E/AndroidRuntime(2101): at android.widget.RelativeLayout.<init>(RelativeLayout.java:242)
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/background" >
<TextView
android:id="#+id/tv2"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_above="#+id/password"
android:layout_alignParentLeft="true"
android:layout_marginBottom="14dp"
android:text="Password" />
<TextView
android:id="#+id/tv"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_marginBottom="20dp" />
<TextView
android:id="#+id/tv0"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/tv1"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_marginBottom="38dp"
android:gravity="center"
android:text="PhilTaxWindow User Login"
android:textSize="20sp"
android:textStyle="bold" />
<TextView
android:id="#+id/tv1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_above="#+id/username"
android:layout_alignParentLeft="true"
android:layout_marginBottom="18dp"
android:text="Username" />
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/register"
android:layout_alignBottom="#+id/register"
android:layout_marginRight="17dp"
android:layout_toLeftOf="#+id/register"
android:text="Don't Have an Account?"
android:textAppearance="?android:attr/textAppearanceSmall" />
<Button
android:id="#+id/Button01"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_above="#+id/register"
android:layout_alignParentLeft="true"
android:layout_marginBottom="60dp"
android:text="Login" />
<EditText
android:id="#+id/username"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_above="#+id/tv2"
android:layout_alignParentLeft="true"
android:layout_marginBottom="22dp"
android:ems="10"
android:inputType="textPersonName"
android:singleLine="true" >
<requestFocus />
</EditText>
<EditText
android:id="#+id/password"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_above="#+id/Button01"
android:layout_alignParentLeft="true"
android:layout_marginBottom="31dp"
android:ems="10"
android:inputType="textPassword"
android:singleLine="true" />
<Button
android:id="#+id/register"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/tv"
android:layout_alignParentRight="true"
android:layout_marginBottom="17dp"
android:layout_marginRight="29dp"
android:text="Register here" />
</RelativeLayout>
mainactivity.java
package com.example.mobileapp;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import com.example.mysqltest.R;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class MainActivity extends Activity implements OnClickListener{
private EditText Username, Password;
private Button Submit, Register;
private ProgressDialog Dialog;
JSONParser jsonParser = new JSONParser();
private static final String LOGIN_URL = "http://192.168.1.4/checkingPHP/CheckUser.php";
private static final String TAG_SUCCESS = "success";
private static final String TAG_MESSAGE = "message";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Username = (EditText)findViewById(R.id.username);
Password = (EditText)findViewById(R.id.password);
Submit = (Button)findViewById(R.id.Button01);
Register = (Button)findViewById(R.id.register);
Submit.setOnClickListener(this);
Register.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.Button01:
new AttemptLogin().execute();
break;
case R.id.register:
Intent i = new Intent(this, Register.class);
startActivity(i);
break;
default:
break;
}
}
class AttemptLogin extends AsyncTask<String, String, String> {
boolean failure = false;
#Override
protected void onPreExecute() {
super.onPreExecute();
Dialog = new ProgressDialog(MainActivity.this);
Dialog.setMessage("Validating...");
Dialog.setIndeterminate(false);
Dialog.setCancelable(true);
Dialog.show();
}
#Override
protected String doInBackground(String... args) {
int success;
String username = Username.getText().toString();
String password = Password.getText().toString();
try {
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("Username", username));
params.add(new BasicNameValuePair("Password", password));
Log.d("request!", "starting");
JSONObject json = jsonParser.makeHttpRequest(
LOGIN_URL, "POST", params);
Log.d("Login attempt", json.toString());
success = json.getInt(TAG_SUCCESS);
if (success == 1) {
Log.d("Login Successful!", json.toString());
Intent i = new Intent(MainActivity.this, WelcomPage.class);
finish();
startActivity(i);
return json.getString(TAG_MESSAGE);
}else{
Log.d("Login Failure!", json.getString(TAG_MESSAGE));
return json.getString(TAG_MESSAGE);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String file_url) {
Dialog.dismiss();
if (file_url != null){
Toast.makeText(MainActivity.this, file_url, Toast.LENGTH_LONG).show();
}
}
}
}
The emulator ran into out of memory exception
Caused by: java.lang.OutOfMemoryError due to
android:background="#drawable/background"
The image that you are trying to load is causing this. Try reducing the image resolution.
This question already has answers here:
NullPointerException accessing views in onCreate()
(13 answers)
Closed 8 years ago.
When I try to open this page it crashes. I have tried to make this button count various ways and can't get it to count! I have tried all kinds of tutorials by thenewboston and other people but it doesn't work for me.
Medical.java
package com.fullcyclestudios.rust;
import android.support.v7.app.ActionBarActivity;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.app.Activity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;
import android.content.Intent;
public class Medical extends ActionBarActivity {
Button add, sub;
int counter;
TextView textView;
TextView quantityDisplay;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_medical);
add=(Button) findViewById(R.id.addButtonMedical);
sub=(Button) findViewById(R.id.minusButtonMedical);
quantityDisplay = (TextView) findViewById(R.id.textViewQuantityMedical);
counter=1;
add.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View arg0)
{
// TODO Auto-generated method stub
counter++;
quantityDisplay.setText("it"+counter);
}
});
sub.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
// TODO Auto-generated method stub
counter--;
quantityDisplay.setText("it"+counter);
}
});
Intent intent = getIntent();
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.medical, 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);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_medical,
container, false);
return rootView;
}
}
/** Bandage button */
public String bandageMaterials(View view)
{
String materials = "Bandage\r\n\r\n2 Cloth";
textView = (TextView) findViewById(R.id.textViewMatMedical);
textView.setText(materials);
return materials;
}
/** Small Medkit button */
public String smallMedkitMaterials(View view)
{
String materials = "Small Medkit\r\n\r\n2 Cloth\r\n2 Blood";
textView = (TextView) findViewById(R.id.textViewMatMedical);
textView.setText(materials);
return materials;
}
/** Large Medkit button */
public String largeMedkitMaterials(View view)
{
String materials = "Large Medkit\r\n\r\n3 Cloth\r\n3 Blood";
textView = (TextView) findViewById(R.id.textViewMatMedical);
textView.setText(materials);
return materials;
}
}
fragment_medical.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="com.fullcyclestudios.rust.Medical$PlaceholderFragment" >
<ScrollView
android:id="#+id/scrollViewMedical"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="130dp" >
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical" >
<Button
android:id="#+id/bandageButton"
style="?android:attr/buttonStyleSmall"
android:layout_width="150dp"
android:layout_height="35dp"
android:text="#string/bandage"
android:onClick="bandageMaterials" />
<Button
android:id="#+id/smallMedkitButton"
style="?android:attr/buttonStyleSmall"
android:layout_width="150dp"
android:layout_height="35dp"
android:text="#string/smallMedkit"
android:onClick="smallMedkitMaterials" />
<Button
android:id="#+id/largeMedkitButton"
style="?android:attr/buttonStyleSmall"
android:layout_width="150dp"
android:layout_height="35dp"
android:text="#string/largeMedkit"
android:onClick="largeMedkitMaterials" />
</LinearLayout>
</ScrollView>
<TextView
android:id="#+id/textViewMatMedical"
android:layout_width="120dp"
android:layout_height="fill_parent"
android:layout_marginTop="140dp"
android:background="#color/gray"
android:text="#string/blank" />
<TextView
android:id="#+id/textViewQuantityMedical"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/minusButtonMedical"
android:layout_alignRight="#+id/minusButtonMedical"
android:layout_below="#+id/addButtonMedical"
android:gravity="center_horizontal"
android:text="#string/one"
android:textAppearance="?android:attr/textAppearanceSmall"
android:textSize="25sp" />
<Button
android:id="#+id/minusButtonMedical"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="50dp"
android:layout_marginTop="80dp"
android:layout_alignLeft="#+id/addButtonMedical"
android:layout_alignRight="#+id/addButtonMedical"
android:text="#string/minus"
android:textSize="30sp"
android:textStyle="bold" />
<Button
android:id="#+id/addButtonMedical"
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="50dp"
android:layout_alignLeft="#+id/textViewMatMedical"
android:layout_alignRight="#+id/textViewMatMedical"
android:text="#string/add"
android:textSize="30sp" />
</RelativeLayout>
ERRORS
06-08 16:10:38.890: W/dalvikvm(855): threadid=1: thread exiting with uncaught exception (group=0xb2a40ba8)
06-08 16:10:38.990: E/AndroidRuntime(855): FATAL EXCEPTION: main
06-08 16:10:38.990: E/AndroidRuntime(855): Process: com.fullcyclestudios.rust, PID: 855
06-08 16:10:38.990: E/AndroidRuntime(855): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.fullcyclestudios.rust/com.fullcyclestudios.rust.Medical}: java.lang.NullPointerException
06-08 16:10:38.990: E/AndroidRuntime(855): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195)
06-08 16:10:38.990: E/AndroidRuntime(855): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
06-08 16:10:38.990: E/AndroidRuntime(855): at android.app.ActivityThread.access$800(ActivityThread.java:135)
06-08 16:10:38.990: E/AndroidRuntime(855): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
06-08 16:10:38.990: E/AndroidRuntime(855): at android.os.Handler.dispatchMessage(Handler.java:102)
06-08 16:10:38.990: E/AndroidRuntime(855): at android.os.Looper.loop(Looper.java:136)
06-08 16:10:38.990: E/AndroidRuntime(855): at android.app.ActivityThread.main(ActivityThread.java:5017)
06-08 16:10:38.990: E/AndroidRuntime(855): at java.lang.reflect.Method.invokeNative(Native Method)
06-08 16:10:38.990: E/AndroidRuntime(855): at java.lang.reflect.Method.invoke(Method.java:515)
06-08 16:10:38.990: E/AndroidRuntime(855): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
06-08 16:10:38.990: E/AndroidRuntime(855): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
06-08 16:10:38.990: E/AndroidRuntime(855): at dalvik.system.NativeStart.main(Native Method)
06-08 16:10:38.990: E/AndroidRuntime(855): Caused by: java.lang.NullPointerException
06-08 16:10:38.990: E/AndroidRuntime(855): at com.fullcyclestudios.rust.Medical.onCreate(Medical.java:33)
06-08 16:10:38.990: E/AndroidRuntime(855): at android.app.Activity.performCreate(Activity.java:5231)
06-08 16:10:38.990: E/AndroidRuntime(855): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
06-08 16:10:38.990: E/AndroidRuntime(855): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)
06-08 16:10:38.990: E/AndroidRuntime(855): ... 11 more
06-08 16:10:43.330: I/Process(855): Sending signal. PID: 855 SIG: 9
Your issue is here:
setContentView(R.layout.activity_medical);
add=(Button) findViewById(R.id.addButtonMedical);
sub=(Button) findViewById(R.id.minusButtonMedical);
but from what you post: addButtonMedical and minusButtonMedical are inside fragment_medical and not activity_medical xml layout!
When I start the activity on my phone, it says that the app is not responding. The problem is the back button which I can't seem to program to make it gather the previous text from the textView.
Xml code for activity
<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:background="#drawable/background"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".Author" >
<TextView
android:id="#+id/textView1"
android:layout_width="300dp"
android:layout_height="300dp"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:background="#drawable/button_shape"
android:text="#string/Getstarted"
android:textColor="#FFFFFF"
android:textSize="23sp" />
<ImageButton
android:id="#+id/next"
android:layout_width="90dp"
android:layout_height="50dp"
android:layout_alignRight="#+id/textView1"
android:layout_below="#+id/textView1"
android:layout_marginTop="14dp"
android:background="#drawable/button_shape"
android:contentDescription="#string/Next"
android:onClick="NextQuote"
android:src="#drawable/navigationnextitem" />
<ImageButton
android:id="#+id/share"
android:layout_width="90dp"
android:layout_height="50dp"
android:layout_alignTop="#+id/next"
android:layout_centerHorizontal="true"
android:background="#drawable/button_shape"
android:contentDescription="#string/share"
android:onClick="Sharing"
android:src="#drawable/socialshare" />
<ImageButton
android:id="#+id/back"
android:layout_width="90dp"
android:layout_height="50dp"
android:layout_alignLeft="#+id/textView1"
android:layout_alignTop="#+id/next"
android:background="#drawable/button_shape"
android:contentDescription="#string/Back"
android:onClick="PreviousQuote"
android:src="#drawable/navigationpreviousitem" />
</RelativeLayout>
Java code for activity
package com.android.motivateme3;
import java.util.Random;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;
import android.support.v4.app.NavUtils;
import android.annotation.TargetApi;
import android.content.Intent;
import android.os.Build;
public class Author extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_author);
// Show the Up button in the action bar.
setupActionBar();
}
/**
* Set up the {#link android.app.ActionBar}, if the API is available.
*/
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
private void setupActionBar() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
getActionBar().setDisplayHomeAsUpEnabled(true);
Button NextQuote = (Button)findViewById(R.id.next);
final TextView display = (TextView) findViewById(R.id.textView1);
NextQuote.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
Random numGen = new Random();
int rNumber = numGen.nextInt(10);
if (rNumber == 0)
{
display.setText(R.string.Author1);
}
else if (rNumber == 1)
{
display.setText(R.string.Author2);
}
else if (rNumber == 2)
{
display.setText(R.string.Author3);
}
else if (rNumber == 3)
{
display.setText(R.string.Author4);
}
else if (rNumber == 4)
{
display.setText(R.string.Author5);
}
else if (rNumber == 5)
{
display.setText(R.string.Author6);
}
else if (rNumber == 6)
{
display.setText(R.string.Author7);
}
else if (rNumber == 7)
{
display.setText(R.string.Author8);
}
else if (rNumber == 8)
{
display.setText(R.string.Author9);
}
else if (rNumber == 9)
{
display.setText(R.string.Author10);
} }
});
}
ImageButton Sharing = (ImageButton)findViewById(R.id.share);
Sharing.setOnClickListener(new View.OnClickListener() {
public void onClick(View v){
TextView text = (TextView)findViewById(R.id.textView1);
String quote = text.getText().toString();{
Intent shareIntent = new Intent(android.content.Intent.ACTION_SEND);
shareIntent.setType("plain/text");
shareIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "This is a great quote (from the Motivate Me! app)");
shareIntent.putExtra(android.content.Intent.EXTRA_TEXT, quote);
startActivity(Intent.createChooser(shareIntent, "Share via:"));}}});
Button BackQuote = (Button)findViewById(R.id.back);
final TextView display = (TextView) findViewById(R.id.textView1);
BackQuote.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String prev = (String) display.getText();
display.setText(prev);
}
});}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.author, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
// This ID represents the Home or Up button. In the case of this
// activity, the Up button is shown. Use NavUtils to allow users
// to navigate up one level in the application structure. For
// more details, see the Navigation pattern on Android Design:
//
// http://developer.android.com/design/patterns/navigation.html#up-vs-back
//
NavUtils.navigateUpFromSameTask(this);
return true;
}
return super.onOptionsItemSelected(item);
}
}
This is the stack trace
04-03 14:29:34.174: E/AndroidRuntime(17383): at android.app.ActivityThread.main(ActivityThread.java:4441)
04-03 14:29:34.174: E/AndroidRuntime(17383): at java.lang.reflect.Method.invokeNative(Native Method)
04-03 14:29:34.174: E/AndroidRuntime(17383): at java.lang.reflect.Method.invoke(Method.java:511)
04-03 14:29:34.174: E/AndroidRuntime(17383): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:823)
04-03 14:29:34.174: E/AndroidRuntime(17383): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:590)
04-03 14:29:34.174: E/AndroidRuntime(17383): at dalvik.system.NativeStart.main(Native Method)
04-03 14:29:34.174: E/AndroidRuntime(17383): Caused by: java.lang.ClassCastException: android.widget.ImageButton cannot be cast to android.widget.Button
04-03 14:29:34.174: E/AndroidRuntime(17383): at com.android.motivateme3.Author.setupActionBar(Author.java:36)
04-03 14:29:34.174: E/AndroidRuntime(17383): at com.android.motivateme3.Author.onCreate(Author.java:25)
04-03 14:29:34.174: E/AndroidRuntime(17383): at android.app.Activity.performCreate(Activity.java:4465)
04-03 14:29:34.174: E/AndroidRuntime(17383): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)
04-03 14:29:34.174: E/AndroidRuntime(17383): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1931)
04-03 14:29:34.174: E/AndroidRuntime(17383): ... 11 more
04-03 14:29:41.664: I/Process(17383): Sending signal. PID: 17383 SIG: 9
It seems to me that R.id.next refers to an ImageButton, which cannot be cast into a Button, since it is not a subclass of a Button
Do you happen to see a ClassCastException?
To fix that particular issue, replace:
Button NextQuote = (Button)findViewById(R.id.next);
with
ImageButton NextQuote = (ImageButton)findViewById(R.id.next);