Am an Android newbiew. Am trying to load a bunch of images in my res/Drawable folder into a Gridview via an array adapter. unfortunately my the app crashes each time i try to view the activity with the gridView. i would like to know how to set the imageResource of image i have in the res folder to display in the Gridview.
here is my Code:
Smile.class
public class Smiley extends Activity {
GridView gridView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.smile);
gridView = (GridView) findViewById(R.id.gridView1);
String planets[] = this.getResources().getStringArray(R.array.imageme);
ArrayAdapter<String>adapter = new ArrayAdapter<String> (this,R.layout.grid_view_row,R.id.imageGrid , planets);
gridView.setAdapter(adapter);
}
}
Smile.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/blurred"
>
<GridView
android:id="#+id/gridView1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:columnWidth="90dp"
android:numColumns="auto_fit"
android:verticalSpacing="10dp"
android:horizontalSpacing="10dp"
android:stretchMode="columnWidth"
android:gravity="center"
>
</GridView>
</RelativeLayout>
grid_view_row.xml (Custom layout for the Gridview)
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<ImageView
android:id="#+id/imageGrid"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="2dp"
android:src="#drawable/a"
/>
</FrameLayout>
My String Array(xml)
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string-array name="imageme">
<item>#drawable/a</item>
<item>#drawable/b</item>
<item>#drawable/c</item>
<item>#drawable/d</item>
</string-array>
</resources>
Logcat
09-04 16:48:40.561: E/ArrayAdapter(25938): You must supply a resource ID for a TextView
09-04 16:48:40.568: E/AndroidRuntime(25938): FATAL EXCEPTION: main
09-04 16:48:40.568: E/AndroidRuntime(25938): java.lang.IllegalStateException: ArrayAdapter requires the resource ID to be a TextView
09-04 16:48:40.568: E/AndroidRuntime(25938): at android.widget.ArrayAdapter.createViewFromResource(ArrayAdapter.java:386)
09-04 16:48:40.568: E/AndroidRuntime(25938): at android.widget.ArrayAdapter.getView(ArrayAdapter.java:362)
09-04 16:48:40.568: E/AndroidRuntime(25938): at android.widget.AbsListView.obtainView(AbsListView.java:2207)
09-04 16:48:40.568: E/AndroidRuntime(25938): at android.widget.GridView.onMeasure(GridView.java:1040)
09-04 16:48:40.568: E/AndroidRuntime(25938): at android.view.View.measure(View.java:15609)
09-04 16:48:40.568: E/AndroidRuntime(25938): at android.widget.RelativeLayout.measureChildHorizontal(RelativeLayout.java:645)
09-04 16:48:40.568: E/AndroidRuntime(25938): at android.widget.RelativeLayout.onMeasure(RelativeLayout.java:425)
09-04 16:48:40.568: E/AndroidRuntime(25938): at android.view.View.measure(View.java:15609)
09-04 16:48:40.568: E/AndroidRuntime(25938): at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4916)
09-04 16:48:40.568: E/AndroidRuntime(25938): at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
09-04 16:48:40.568: E/AndroidRuntime(25938): at android.view.View.measure(View.java:15609)
09-04 16:48:40.568: E/AndroidRuntime(25938): at android.widget.LinearLayout.measureVertical(LinearLayout.java:850)
09-04 16:48:40.568: E/AndroidRuntime(25938): at android.widget.LinearLayout.onMeasure(LinearLayout.java:588)
09-04 16:48:40.568: E/AndroidRuntime(25938): at android.view.View.measure(View.java:15609)
09-04 16:48:40.568: E/AndroidRuntime(25938): at android.view.ViewGroup.measureChildWithMargins(ViewGroup.java:4916)
09-04 16:48:40.568: E/AndroidRuntime(25938): at android.widget.FrameLayout.onMeasure(FrameLayout.java:310)
09-04 16:48:40.568: E/AndroidRuntime(25938): at com.android.internal.policy.impl.PhoneWindow$DecorView.onMeasure(PhoneWindow.java:2203)
09-04 16:48:40.568: E/AndroidRuntime(25938): at android.view.View.measure(View.java:15609)
09-04 16:48:40.568: E/AndroidRuntime(25938): at android.view.ViewRootImpl.performMeasure(ViewRootImpl.java:2165)
09-04 16:48:40.568: E/AndroidRuntime(25938): at android.view.ViewRootImpl.measureHierarchy(ViewRootImpl.java:1249)
09-04 16:48:40.568: E/AndroidRuntime(25938): at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1443)
09-04 16:48:40.568: E/AndroidRuntime(25938): at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1139)
09-04 16:48:40.568: E/AndroidRuntime(25938): at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:4879)
09-04 16:48:40.568: E/AndroidRuntime(25938): at android.view.Choreographer$CallbackRecord.run(Choreographer.java:776)
09-04 16:48:40.568: E/AndroidRuntime(25938): at android.view.Choreographer.doCallbacks(Choreographer.java:579)
09-04 16:48:40.568: E/AndroidRuntime(25938): at android.view.Choreographer.doFrame(Choreographer.java:548)
09-04 16:48:40.568: E/AndroidRuntime(25938): at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:762)
09-04 16:48:40.568: E/AndroidRuntime(25938): at android.os.Handler.handleCallback(Handler.java:725)
09-04 16:48:40.568: E/AndroidRuntime(25938): at android.os.Handler.dispatchMessage(Handler.java:92)
09-04 16:48:40.568: E/AndroidRuntime(25938): at android.os.Looper.loop(Looper.java:153)
09-04 16:48:40.568: E/AndroidRuntime(25938): at android.app.ActivityThread.main(ActivityThread.java:5297)
09-04 16:48:40.568: E/AndroidRuntime(25938): at java.lang.reflect.Method.invokeNative(Native Method)
09-04 16:48:40.568: E/AndroidRuntime(25938): at java.lang.reflect.Method.invoke(Method.java:511)
09-04 16:48:40.568: E/AndroidRuntime(25938): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:833)
09-04 16:48:40.568: E/AndroidRuntime(25938): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600)
09-04 16:48:40.568: E/AndroidRuntime(25938): at dalvik.system.NativeStart.main(Native Method)
09-04 16:48:40.568: E/AndroidRuntime(25938): Caused by: java.lang.ClassCastException: android.widget.ImageView cannot be cast to android.widget.TextView
09-04 16:48:40.568: E/AndroidRuntime(25938): at android.widget.ArrayAdapter.createViewFromResource(ArrayAdapter.java:382)
09-04 16:48:40.568: E/AndroidRuntime(25938): ... 35 more
please help.Thanks
Problem is that you try to assign String-type data to ImageView.
The easiest way to fix it would be:
Change resource array type to integer-array
Instead of using simple ArrayAdapter with string data, use custom adapter like:
class ImgAdapter extends BaseAdapter {
#Override
public int getCount() {
return planets.length;
}
#Override
public Integer getItem(final int position) {
return planets[position];
}
#Override
public long getItemId(final int position) {
return position;
}
#Override
public View getView(final int position, final View convertView, final ViewGroup parent) {
final View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.grid_view_row, null);
ImageView imageView = (ImageView) view.findViewById(R.id.imageGrid);
imageView.setImageResource(getItem(position));
return view;
}
}
That is simple it. Last thing is to set new adapter to gridView
The specific answer to your issue is your constructor for your adapter is:
(this,R.layout.grid_view_row,R.id.imageGrid , planets);
R.layout.grid_view_row needs to be an xml file with only a TextView. It can't be wrapped in anything else like a LinearLayout or RelativeLayout. So you would need:
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
//attributes
/>
However, If you want to load images into a GridView I would recommend using an "image adapter" that extends BaseAdapter and then get the images from there. Very similar to this example:
public class ImageAdapter extends BaseAdapter {
private Context mContext;
public ImageAdapter(Context c) {
mContext = c;
}
public int getCount() {
return mThumbIds.length;
}
public Object getItem(int position) {
return null;
}
public long getItemId(int position) {
return 0;
}
// create a new ImageView for each item referenced by the Adapter
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView;
if (convertView == null) { // if it's not recycled, initialize some attributes
imageView = new ImageView(mContext);
imageView.setLayoutParams(new GridView.LayoutParams(85, 85));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setPadding(8, 8, 8, 8);
} else {
imageView = (ImageView) convertView;
}
imageView.setImageResource(mThumbIds[position]);
return imageView;
}
// references to your images
private Integer[] mThumbIds = {
R.drawable.sample_2, R.drawable.sample_3,
R.drawable.sample_4, R.drawable.sample_5,
R.drawable.sample_6, R.drawable.sample_7,
R.drawable.sample_0, R.drawable.sample_1,
R.drawable.sample_2, R.drawable.sample_3,
R.drawable.sample_4, R.drawable.sample_5,
R.drawable.sample_6, R.drawable.sample_7,
R.drawable.sample_0, R.drawable.sample_1,
R.drawable.sample_2, R.drawable.sample_3,
R.drawable.sample_4, R.drawable.sample_5,
R.drawable.sample_6, R.drawable.sample_7
};
}
where getView sets how the grid should look and mThumbIds is an Array of every picture that you want. From here in the Activity that you want to display the GridView in just add the code:
gridview.setAdapter(new ImageAdapter(this));
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
so I have this problem and I think code should work, but it doesnt. It crashed the app at it's start.
Logcat doesnt seem to help so how do I detect what is crashing my app?
Here is the code of my app if someone would like to check error or something
http://www23.zippyshare.com/v/472319/file.html
Here is MainActivity.java
package com.example.sqllite;
import java.util.ArrayList;
import com.example.kontaktysqllite.R;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class MainActivity extends ListActivity{
private ProgressDialog m_ProgressDialog = null;
private ArrayList<Order> m_orders = null;
private OrderAdapter m_adapter;
private Runnable viewOrders;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
m_orders = new ArrayList<Order>();
this.m_adapter = new OrderAdapter(this, R.layout.row, m_orders);
setListAdapter(this.m_adapter);
viewOrders = new Runnable(){
#Override
public void run() {
getOrders();
}
};
Thread thread = new Thread(null, viewOrders, "MagentoBackground");
thread.start();
m_ProgressDialog = ProgressDialog.show(MainActivity.this,
"Please wait...", "Retrieving data ...", true);
}
private Runnable returnRes = new Runnable() {
#Override
public void run() {
if(m_orders != null && m_orders.size() > 0){
m_adapter.notifyDataSetChanged();
for(int i=0;i<m_orders.size();i++)
m_adapter.add(m_orders.get(i));
}
m_ProgressDialog.dismiss();
m_adapter.notifyDataSetChanged();
}
};
private void getOrders(){
try{
final ZarzadcaBazy zb = new ZarzadcaBazy(this);
m_orders = new ArrayList<Order>();
Cursor k = zb.dajWszystkie();
while (k.moveToNext()) {
String message = k.getString(1);
Order order = new Order();
order.setOrderLink(message);
order.setOrderName("szablon");
m_orders.add(order);
Log.i("ARRAY", ""+ m_orders.size());
}
} catch (Exception e) {
Log.e("BACKGROUND_PROC", e.getMessage());
}
runOnUiThread(returnRes);
}
private class OrderAdapter extends ArrayAdapter<Order> {
private ArrayList<Order> items;
public OrderAdapter(Context context, int textViewResourceId, ArrayList<Order> items) {
super(context, textViewResourceId, items);
this.items = items;
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
View v = convertView;
if (v == null)
{
LayoutInflater vi = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
v = vi.inflate(R.layout.row, null);
}
Order o = items.get(position);
if (o != null)
{
TextView name = (TextView) v.findViewById(R.id.row_textView);
ImageView img = (ImageView)findViewById(R.id.row_imageview);
if (name != null)
{
name.setText("Name: "+o.getOrderName());
}
img.setOnClickListener(new View.OnClickListener()
{
public void onClick(View view)
{
Intent intent = new Intent(MainActivity.this, Activity2.class);
intent.putExtra("urlString", "https://beta2.createer.com/Action/Show/777203e8-5b53-462d-863b-c4e10a3abd5b/");
startActivity(intent);
}
});
}
return v;
}
}
}
Logcat:
09-04 14:56:37.244: I/Process(579): Sending signal. PID: 579 SIG: 9
09-04 14:56:37.374: W/ApplicationPackageManager(868): getCSCPackageItemText()
09-04 14:56:37.424: D/AbsListView(868): Get MotionRecognitionManager
09-04 14:56:37.444: D/AbsListView(868): onVisibilityChanged() is called, visibility : 8
09-04 14:56:37.444: D/AbsListView(868): unregisterIRListener() is called
09-04 14:56:37.464: I/ARRAY(868): 1
09-04 14:56:37.464: I/ARRAY(868): 2
09-04 14:56:37.464: I/ARRAY(868): 3
09-04 14:56:37.494: D/AbsListView(868): onVisibilityChanged() is called, visibility : 4
09-04 14:56:37.494: D/AbsListView(868): unregisterIRListener() is called
09-04 14:56:37.494: D/AbsListView(868): onVisibilityChanged() is called, visibility : 0
09-04 14:56:37.494: D/AbsListView(868): unregisterIRListener() is called
09-04 14:56:37.494: D/AbsListView(868): unregisterIRListener() is called
09-04 14:56:37.504: D/AbsListView(868): onVisibilityChanged() is called, visibility : 0
09-04 14:56:37.504: D/AbsListView(868): unregisterIRListener() is called
09-04 14:56:37.504: E/ViewRootImpl(868): sendUserActionEvent() mView == null
09-04 14:56:37.504: D/AbsListView(868): unregisterIRListener() is called
09-04 14:56:37.524: I/Adreno-EGL(868): <qeglDrvAPI_eglInitialize:381>: EGL 1.4 QUALCOMM build: (CL3869936)
09-04 14:56:37.524: I/Adreno-EGL(868): OpenGL ES Shader Compiler Version: 17.01.11.SPL
09-04 14:56:37.524: I/Adreno-EGL(868): Build Date: 01/17/14 Fri
09-04 14:56:37.524: I/Adreno-EGL(868): Local Branch:
09-04 14:56:37.524: I/Adreno-EGL(868): Remote Branch:
09-04 14:56:37.524: I/Adreno-EGL(868): Local Patches:
09-04 14:56:37.524: I/Adreno-EGL(868): Reconstruct Branch:
09-04 14:56:37.574: D/OpenGLRenderer(868): Enabling debug mode 0
09-04 14:56:37.715: D/dalvikvm(868): GC_FOR_ALLOC freed 204K, 34% free 17536K/26476K, paused 16ms, total 16ms
09-04 14:56:37.745: I/dalvikvm-heap(868): Grow heap (frag case) to 39.227MB for 18924856-byte allocation
09-04 14:56:37.745: W/SQLiteConnectionPool(868): A SQLiteConnection object for database '+data+data+com_example_kontaktysqllite+databases+kontakty_db' was leaked! Please fix your application to end transactions in progress properly and to close the database when it is no longer needed.
09-04 14:56:37.785: D/AndroidRuntime(868): Shutting down VM
09-04 14:56:37.785: W/dalvikvm(868): threadid=1: thread exiting with uncaught exception (group=0x418e7da0)
09-04 14:56:37.805: E/AndroidRuntime(868): FATAL EXCEPTION: main
09-04 14:56:37.805: E/AndroidRuntime(868): Process: com.example.kontaktysqllite, PID: 868
09-04 14:56:37.805: E/AndroidRuntime(868): java.lang.NullPointerException
09-04 14:56:37.805: E/AndroidRuntime(868): at com.example.sqllite.MainActivity$OrderAdapter.getView(MainActivity.java:109)
09-04 14:56:37.805: E/AndroidRuntime(868): at android.widget.AbsListView.obtainView(AbsListView.java:2715)
09-04 14:56:37.805: E/AndroidRuntime(868): at android.widget.ListView.makeAndAddView(ListView.java:1801)
09-04 14:56:37.805: E/AndroidRuntime(868): at android.widget.ListView.fillDown(ListView.java:697)
09-04 14:56:37.805: E/AndroidRuntime(868): at android.widget.ListView.fillFromTop(ListView.java:763)
09-04 14:56:37.805: E/AndroidRuntime(868): at android.widget.ListView.layoutChildren(ListView.java:1627)
09-04 14:56:37.805: E/AndroidRuntime(868): at android.widget.AbsListView.onLayout(AbsListView.java:2528)
09-04 14:56:37.805: E/AndroidRuntime(868): at android.view.View.layout(View.java:15655)
09-04 14:56:37.805: E/AndroidRuntime(868): at android.view.ViewGroup.layout(ViewGroup.java:4856)
09-04 14:56:37.805: E/AndroidRuntime(868): at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1677)
09-04 14:56:37.805: E/AndroidRuntime(868): at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1531)
09-04 14:56:37.805: E/AndroidRuntime(868): at android.widget.LinearLayout.onLayout(LinearLayout.java:1440)
09-04 14:56:37.805: E/AndroidRuntime(868): at android.view.View.layout(View.java:15655)
09-04 14:56:37.805: E/AndroidRuntime(868): at android.view.ViewGroup.layout(ViewGroup.java:4856)
09-04 14:56:37.805: E/AndroidRuntime(868): at android.widget.FrameLayout.layoutChildren(FrameLayout.java:453)
09-04 14:56:37.805: E/AndroidRuntime(868): at android.widget.FrameLayout.onLayout(FrameLayout.java:388)
09-04 14:56:37.805: E/AndroidRuntime(868): at android.view.View.layout(View.java:15655)
09-04 14:56:37.805: E/AndroidRuntime(868): at android.view.ViewGroup.layout(ViewGroup.java:4856)
09-04 14:56:37.805: E/AndroidRuntime(868): at com.android.internal.widget.ActionBarOverlayLayout.onLayout(ActionBarOverlayLayout.java:438)
09-04 14:56:37.805: E/AndroidRuntime(868): at android.view.View.layout(View.java:15655)
09-04 14:56:37.805: E/AndroidRuntime(868): at android.view.ViewGroup.layout(ViewGroup.java:4856)
09-04 14:56:37.805: E/AndroidRuntime(868): at android.widget.FrameLayout.layoutChildren(FrameLayout.java:453)
09-04 14:56:37.805: E/AndroidRuntime(868): at android.widget.FrameLayout.onLayout(FrameLayout.java:388)
09-04 14:56:37.805: E/AndroidRuntime(868): at android.view.View.layout(View.java:15655)
09-04 14:56:37.805: E/AndroidRuntime(868): at android.view.ViewGroup.layout(ViewGroup.java:4856)
09-04 14:56:37.805: E/AndroidRuntime(868): at android.view.ViewRootImpl.performLayout(ViewRootImpl.java:2283)
09-04 14:56:37.805: E/AndroidRuntime(868): at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:2003)
09-04 14:56:37.805: E/AndroidRuntime(868): at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1235)
09-04 14:56:37.805: E/AndroidRuntime(868): at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:6470)
09-04 14:56:37.805: E/AndroidRuntime(868): at android.view.Choreographer$CallbackRecord.run(Choreographer.java:803)
09-04 14:56:37.805: E/AndroidRuntime(868): at android.view.Choreographer.doCallbacks(Choreographer.java:603)
09-04 14:56:37.805: E/AndroidRuntime(868): at android.view.Choreographer.doFrame(Choreographer.java:573)
09-04 14:56:37.805: E/AndroidRuntime(868): at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:789)
09-04 14:56:37.805: E/AndroidRuntime(868): at android.os.Handler.handleCallback(Handler.java:733)
09-04 14:56:37.805: E/AndroidRuntime(868): at android.os.Handler.dispatchMessage(Handler.java:95)
09-04 14:56:37.805: E/AndroidRuntime(868): at android.os.Looper.loop(Looper.java:157)
09-04 14:56:37.805: E/AndroidRuntime(868): at android.app.ActivityThread.main(ActivityThread.java:5356)
09-04 14:56:37.805: E/AndroidRuntime(868): at java.lang.reflect.Method.invokeNative(Native Method)
09-04 14:56:37.805: E/AndroidRuntime(868): at java.lang.reflect.Method.invoke(Method.java:515)
09-04 14:56:37.805: E/AndroidRuntime(868): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1265)
09-04 14:56:37.805: E/AndroidRuntime(868): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1081)
09-04 14:56:37.805: E/AndroidRuntime(868): at dalvik.system.NativeStart.main(Native Method)
You are getting NullPointerException on
ImageView img = (ImageView)findViewById(R.id.row_imageview);
Please use
ImageView img = (ImageView)v.findViewById(R.id.row_imageview);
as img is in View v same as TextView name.
Hope this helps.
firstly i am sorry for my broken english. I wanna read txt file and into 2d array. this code is succesfully running on java. but android emulator gives warning message: "Sorry! the application has stopped unexpectedly. please try again"
how can I fix that? thanks
here is my code:
package com.example.hocam;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class Konular extends ActionBarActivity {
private ListView konuListe;
private List<KonuBilgileri> konuBilgileri;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_konular);
Bundle dersadi = getIntent().getExtras();
String dersinadi= dersadi.getString("Ders");
switch(dersinadi) {
case "Turkce":
KonuGetir turkce=new KonuGetir("turkce.txt");
String[][] turkcekonular=turkce.getKonular();
System.out.println(turkcekonular[0][0]); // it is the problem and give error
konuListe = (ListView) findViewById(R.id.konu_listesi);
konuBilgileri = new ArrayList<KonuBilgileri>();
konuBilgileri.add(new KonuBilgileri(turkcekonular[0][0],R.drawable.turkce, turkcekonular[0][1])); // array is problem
MyAdapter adapter = new MyAdapter(Konular.this, R.layout.custom_list_item, konuBilgileri);
konuListe.setAdapter(adapter);
break;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.konular, 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);
}
}
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;
public class KonuGetir {
final int maxLines = 10100;
String[][] resultArray = new String[maxLines][];
public KonuGetir(String Ders){
File file = new File(Ders);
Scanner scanner;
try {
scanner = new Scanner(file,"utf-8");
int linesCounter = 0;
while (scanner.hasNextLine() && linesCounter < maxLines) {
resultArray[linesCounter] = scanner.nextLine().split("#");
linesCounter++;
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public String[][] getKonular() {
return resultArray;
}
}
logfile:
> 09-04 16:18:22.262: E/AndroidRuntime(1164): FATAL EXCEPTION: main
09-04 16:18:22.262: E/AndroidRuntime(1164): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.hocam/com.example.hocam.Konular}: java.lang.NullPointerException
09-04 16:18:22.262: E/AndroidRuntime(1164): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2663)
09-04 16:18:22.262: E/AndroidRuntime(1164): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
09-04 16:18:22.262: E/AndroidRuntime(1164): at android.app.ActivityThread.access$2300(ActivityThread.java:125)
09-04 16:18:22.262: E/AndroidRuntime(1164): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
09-04 16:18:22.262: E/AndroidRuntime(1164): at android.os.Handler.dispatchMessage(Handler.java:99)
09-04 16:18:22.262: E/AndroidRuntime(1164): at android.os.Looper.loop(Looper.java:123)
09-04 16:18:22.262: E/AndroidRuntime(1164): at android.app.ActivityThread.main(ActivityThread.java:4627)
09-04 16:18:22.262: E/AndroidRuntime(1164): at java.lang.reflect.Method.invokeNative(Native Method)
09-04 16:18:22.262: E/AndroidRuntime(1164): at java.lang.reflect.Method.invoke(Method.java:521)
09-04 16:18:22.262: E/AndroidRuntime(1164): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
09-04 16:18:22.262: E/AndroidRuntime(1164): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
09-04 16:18:22.262: E/AndroidRuntime(1164): at dalvik.system.NativeStart.main(Native Method)
09-04 16:18:22.262: E/AndroidRuntime(1164): Caused by: java.lang.NullPointerException
09-04 16:18:22.262: E/AndroidRuntime(1164): at com.example.hocam.Konular.onCreate(Konular.java:66)
09-04 16:18:22.262: E/AndroidRuntime(1164): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
09-04 16:18:22.262: E/AndroidRuntime(1164): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627)
09-04 16:18:22.262: E/AndroidRuntime(1164): ... 11 more
09-04 16:42:10.422: E/AndroidRuntime(1178): FATAL EXCEPTION: main
09-04 16:42:10.422: E/AndroidRuntime(1178): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.hocam/com.example.hocam.Konular}: java.lang.NullPointerException
09-04 16:42:10.422: E/AndroidRuntime(1178): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2663)
09-04 16:42:10.422: E/AndroidRuntime(1178): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
09-04 16:42:10.422: E/AndroidRuntime(1178): at android.app.ActivityThread.access$2300(ActivityThread.java:125)
09-04 16:42:10.422: E/AndroidRuntime(1178): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
09-04 16:42:10.422: E/AndroidRuntime(1178): at android.os.Handler.dispatchMessage(Handler.java:99)
09-04 16:42:10.422: E/AndroidRuntime(1178): at android.os.Looper.loop(Looper.java:123)
09-04 16:42:10.422: E/AndroidRuntime(1178): at android.app.ActivityThread.main(ActivityThread.java:4627)
09-04 16:42:10.422: E/AndroidRuntime(1178): at java.lang.reflect.Method.invokeNative(Native Method)
09-04 16:42:10.422: E/AndroidRuntime(1178): at java.lang.reflect.Method.invoke(Method.java:521)
09-04 16:42:10.422: E/AndroidRuntime(1178): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
09-04 16:42:10.422: E/AndroidRuntime(1178): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
09-04 16:42:10.422: E/AndroidRuntime(1178): at dalvik.system.NativeStart.main(Native Method)
09-04 16:42:10.422: E/AndroidRuntime(1178): Caused by: java.lang.NullPointerException
09-04 16:42:10.422: E/AndroidRuntime(1178): at com.example.hocam.Konular.onCreate(Konular.java:66)
09-04 16:42:10.422: E/AndroidRuntime(1178): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
09-04 16:42:10.422: E/AndroidRuntime(1178): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627)
09-04 16:42:10.422: E/AndroidRuntime(1178): ... 11 more
09-04 16:43:28.802: E/AndroidRuntime(1207): FATAL EXCEPTION: main
09-04 16:43:28.802: E/AndroidRuntime(1207): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.hocam/com.example.hocam.Konular}: java.lang.NullPointerException
09-04 16:43:28.802: E/AndroidRuntime(1207): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2663)
09-04 16:43:28.802: E/AndroidRuntime(1207): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
09-04 16:43:28.802: E/AndroidRuntime(1207): at android.app.ActivityThread.access$2300(ActivityThread.java:125)
09-04 16:43:28.802: E/AndroidRuntime(1207): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
09-04 16:43:28.802: E/AndroidRuntime(1207): at android.os.Handler.dispatchMessage(Handler.java:99)
09-04 16:43:28.802: E/AndroidRuntime(1207): at android.os.Looper.loop(Looper.java:123)
09-04 16:43:28.802: E/AndroidRuntime(1207): at android.app.ActivityThread.main(ActivityThread.java:4627)
09-04 16:43:28.802: E/AndroidRuntime(1207): at java.lang.reflect.Method.invokeNative(Native Method)
09-04 16:43:28.802: E/AndroidRuntime(1207): at java.lang.reflect.Method.invoke(Method.java:521)
09-04 16:43:28.802: E/AndroidRuntime(1207): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
09-04 16:43:28.802: E/AndroidRuntime(1207): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
09-04 16:43:28.802: E/AndroidRuntime(1207): at dalvik.system.NativeStart.main(Native Method)
09-04 16:43:28.802: E/AndroidRuntime(1207): Caused by: java.lang.NullPointerException
09-04 16:43:28.802: E/AndroidRuntime(1207): at com.example.hocam.Konular.onCreate(Konular.java:66)
09-04 16:43:28.802: E/AndroidRuntime(1207): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
09-04 16:43:28.802: E/AndroidRuntime(1207): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627)
09-04 16:43:28.802: E/AndroidRuntime(1207): ... 11 more
android manifest file:
<uses-permission android:name="android.permission.INTERNET" />
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="21" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".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=".YGS"
android:label="#string/title_activity_ygs" >
</activity>
<activity
android:name=".Konular"
android:label="#string/title_activity_konular" >
</activity>
<activity
android:name=".Video"
android:screenOrientation="landscape"
android:label="#string/title_activity_video" >
</activity>
</application>
You are using the following code:
String[][] turkcekonular=turkce.getKonular();
System.out.println(turkcekonular[0][0]);
But get java.lang.NullPointerException.
The reason for this because getKonular() returns an array initalised to size 10100, however scanner does not contain any lines so scanner.hasNextLine() is false.
This means that turkcekonular[0] is null, as it was never set.
Which means that turkcekonular[0][0] is trying to access a null object, so throws a NullPointerException
You should check if the object is null before trying to access it..
if(turkcekonular[0] != null)
System.out.println(turkcekonular[0][0]);
and else where that this issue occurs.
(and you should figure out why your file is not read. Is it named correctly and exists in the specified path?)
MainActivity.java
package com.example.myfirstapp;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.EditText;
import android.content.Intent;
public class MainActivity extends Activity {
public final static String EXTRA_MESSAGE = "com.example.myfirstapp.MESSAGE";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#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;
}
/** Called when the user clicks the Send button */
public void sendMessage(View view) {
Intent intent = new Intent(this, DisplayMessageActivity.class);
EditText editText = (EditText) findViewById(R.id.edit_message);
String message = editText.getText().toString();
intent.putExtra(EXTRA_MESSAGE, message);
startActivity(intent);
}
}
activitymain.xml
<?xml version="1.0" encoding="utf-8"?>
<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="match_parent"
android:orientation="horizontal" >
<EditText android:id="#+id/edit_message"
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:hint="#string/edit_message"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/button_send"
android:onClick="sendMessage" />
</LinearLayout>
DisplayMessageActivity.java
import android.support.v7.app.ActionBarActivity;
import android.support.v4.app.Fragment;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class DisplayMessageActivity extends ActionBarActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Get the message from the intent
Intent intent = getIntent();
String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);
// Create the text view
TextView textView = new TextView(this);
textView.setTextSize(40);
textView.setText(message);
// Set the text view as the activity layout
setContentView(textView);
}
#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_display_message,
container, false);
return rootView;
}
}
}
Error Log
04-10 01:37:00.460: W/dalvikvm(1650): threadid=1: thread exiting with uncaught exception (group=0xb3aaeba8)
04-10 01:37:00.520: E/AndroidRuntime(1650): FATAL EXCEPTION: main
04-10 01:37:00.520: E/AndroidRuntime(1650): Process: com.example.myfirstapp, PID: 1650
04-10 01:37:00.520: E/AndroidRuntime(1650): java.lang.IllegalStateException: Could not find a method sendMessage(View) in the activity class com.example.myfirstapp.MainActivity for onClick handler on view class android.widget.Button
04-10 01:37:00.520: E/AndroidRuntime(1650): at android.view.View$1.onClick(View.java:3810)
04-10 01:37:00.520: E/AndroidRuntime(1650): at android.view.View.performClick(View.java:4438)
04-10 01:37:00.520: E/AndroidRuntime(1650): at android.view.View$PerformClick.run(View.java:18422)
04-10 01:37:00.520: E/AndroidRuntime(1650): at android.os.Handler.handleCallback(Handler.java:733)
04-10 01:37:00.520: E/AndroidRuntime(1650): at android.os.Handler.dispatchMessage(Handler.java:95)
04-10 01:37:00.520: E/AndroidRuntime(1650): at android.os.Looper.loop(Looper.java:136)
04-10 01:37:00.520: E/AndroidRuntime(1650): at android.app.ActivityThread.main(ActivityThread.java:5017)
04-10 01:37:00.520: E/AndroidRuntime(1650): at java.lang.reflect.Method.invokeNative(Native Method)
04-10 01:37:00.520: E/AndroidRuntime(1650): at java.lang.reflect.Method.invoke(Method.java:515)
04-10 01:37:00.520: E/AndroidRuntime(1650): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
04-10 01:37:00.520: E/AndroidRuntime(1650): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
04-10 01:37:00.520: E/AndroidRuntime(1650): at dalvik.system.NativeStart.main(Native Method)
04-10 01:37:00.520: E/AndroidRuntime(1650): Caused by: java.lang.NoSuchMethodException: sendMessage [class android.view.View]
04-10 01:37:00.520: E/AndroidRuntime(1650): at java.lang.Class.getConstructorOrMethod(Class.java:472)
04-10 01:37:00.520: E/AndroidRuntime(1650): at java.lang.Class.getMethod(Class.java:857)
04-10 01:37:00.520: E/AndroidRuntime(1650): at android.view.View$1.onClick(View.java:3803)
04-10 01:37:00.520: E/AndroidRuntime(1650): ... 11 more
04-10 01:37:04.820: I/Process(1650): Sending signal. PID: 1650 SIG: 9
I've tried to look at other questions answered similar to mine, but I can't find an answer that seems to help my situation. Can anyone help?
I was struggling with a similar error following the android tutorial
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.myfirstapp, PID: 18300
java.lang.IllegalStateException: Could not find method sendMessage (MainActivity)(View) in a parent or ancestor Context for android:onClick attribute defined on view class android.support.v7.widget.AppCompatButton with id 'button'
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.resolveMethod(AppCompatViewInflater.java:327)
at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:284)
at android.view.View.performClick(View.java:5197)
at android.view.View$PerformClick.run(View.java:20909)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:145)
at android.app.ActivityThread.main(ActivityThread.java:5944)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1399)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1194)
but in my case the WYSIWYG editor (IntelliJ w/Android Studio plugin) ended up populating the onClick property in activity_main.xml with some extra junk about MainActivity:
android:onClick="sendMessage (MainActivity)"
So I deleted " (MainActivity)" and it stopped crashing. I see this is different from your problem as your xml file already seems correct with android:onClick="sendMessage". But wanted to add it here for any others struggling with what I saw. This was the closest post to the issue I was seeing. I'm just getting started and this was killing me, so hope it helps someone else.
The problem is the onClick property in one of your Button tags:
android:onClick="sendMessage" />
Just make sure you have a method sendMessage(View) in your Activity.
It is because you need to implement implements android.view.View.OnClickListener in your class, therefore add the correct imports i.e. import android.view.View.
so Im trying to make an app that when you click on a button, it displays a lot of images. The problem is that when I click the button, the application crashes.
Here is a part of my XML file. It has 36 different images:
<ImageView
android:id="#+id/imageView31"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:src="#drawable/veh1" />
<ImageView
android:id="#+id/imageView32"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:src="#drawable/veh2" />
<ImageView
android:id="#+id/imageView33"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:src="#drawable/veh3" />
...
And here is the LogCat:
02-18 22:47:00.263: E/AndroidRuntime(366): FATAL EXCEPTION: main
02-18 22:47:00.263: E/AndroidRuntime(366): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.guzi.samphelptools/com.guzi.samphelptools.Vehicles}: android.view.InflateException: Binary XML file line #81: Error inflating class <unknown>
02-18 22:47:00.263: E/AndroidRuntime(366): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1647)
02-18 22:47:00.263: E/AndroidRuntime(366): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663)
02-18 22:47:00.263: E/AndroidRuntime(366): at android.app.ActivityThread.access$1500(ActivityThread.java:117)
02-18 22:47:00.263: E/AndroidRuntime(366): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931)
02-18 22:47:00.263: E/AndroidRuntime(366): at android.os.Handler.dispatchMessage(Handler.java:99)
02-18 22:47:00.263: E/AndroidRuntime(366): at android.os.Looper.loop(Looper.java:130)
02-18 22:47:00.263: E/AndroidRuntime(366): at android.app.ActivityThread.main(ActivityThread.java:3683)
02-18 22:47:00.263: E/AndroidRuntime(366): at java.lang.reflect.Method.invokeNative(Native Method)
02-18 22:47:00.263: E/AndroidRuntime(366): at java.lang.reflect.Method.invoke(Method.java:507)
02-18 22:47:00.263: E/AndroidRuntime(366): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
02-18 22:47:00.263: E/AndroidRuntime(366): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
02-18 22:47:00.263: E/AndroidRuntime(366): at dalvik.system.NativeStart.main(Native Method)
02-18 22:47:00.263: E/AndroidRuntime(366): Caused by: android.view.InflateException: Binary XML file line #81: Error inflating class <unknown>
02-18 22:47:00.263: E/AndroidRuntime(366): at android.view.LayoutInflater.createView(LayoutInflater.java:518)
02-18 22:47:00.263: E/AndroidRuntime(366): at com.android.internal.policy.impl.PhoneLayoutInflater.onCreateView(PhoneLayoutInflater.java:56)
02-18 22:47:00.263: E/AndroidRuntime(366): at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:568)
02-18 22:47:00.263: E/AndroidRuntime(366): at android.view.LayoutInflater.rInflate(LayoutInflater.java:623)
02-18 22:47:00.263: E/AndroidRuntime(366): at android.view.LayoutInflater.rInflate(LayoutInflater.java:626)
02-18 22:47:00.263: E/AndroidRuntime(366): at android.view.LayoutInflater.rInflate(LayoutInflater.java:626)
02-18 22:47:00.263: E/AndroidRuntime(366): at android.view.LayoutInflater.inflate(LayoutInflater.java:408)
02-18 22:47:00.263: E/AndroidRuntime(366): at android.view.LayoutInflater.inflate(LayoutInflater.java:320)
02-18 22:47:00.263: E/AndroidRuntime(366): at android.view.LayoutInflater.inflate(LayoutInflater.java:276)
02-18 22:47:00.263: E/AndroidRuntime(366): at com.android.internal.policy.impl.PhoneWindow.setContentView(PhoneWindow.java:207)
02-18 22:47:00.263: E/AndroidRuntime(366): at android.app.Activity.setContentView(Activity.java:1657)
02-18 22:47:00.263: E/AndroidRuntime(366): at com.guzi.samphelptools.Vehicles.onCreate(Vehicles.java:14)
02-18 22:47:00.263: E/AndroidRuntime(366): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
02-18 22:47:00.263: E/AndroidRuntime(366): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1611)
02-18 22:47:00.263: E/AndroidRuntime(366): ... 11 more
02-18 22:47:00.263: E/AndroidRuntime(366): Caused by: java.lang.reflect.InvocationTargetException
02-18 22:47:00.263: E/AndroidRuntime(366): at java.lang.reflect.Constructor.constructNative(Native Method)
02-18 22:47:00.263: E/AndroidRuntime(366): at java.lang.reflect.Constructor.newInstance(Constructor.java:415)
02-18 22:47:00.263: E/AndroidRuntime(366): at android.view.LayoutInflater.createView(LayoutInflater.java:505)
02-18 22:47:00.263: E/AndroidRuntime(366): ... 24 more
02-18 22:47:00.263: E/AndroidRuntime(366): Caused by: java.lang.OutOfMemoryError: bitmap size exceeds VM budget
02-18 22:47:00.263: E/AndroidRuntime(366): at android.graphics.BitmapFactory.nativeDecodeAsset(Native Method)
02-18 22:47:00.263: E/AndroidRuntime(366): at android.graphics.BitmapFactory.decodeStream(BitmapFactory.java:460)
02-18 22:47:00.263: E/AndroidRuntime(366): at android.graphics.BitmapFactory.decodeResourceStream(BitmapFactory.java:336)
02-18 22:47:00.263: E/AndroidRuntime(366): at android.graphics.drawable.Drawable.createFromResourceStream(Drawable.java:697)
02-18 22:47:00.263: E/AndroidRuntime(366): at android.content.res.Res`enter code here`ources.loadDrawable(Resources.java:1709)
02-18 22:47:00.263: E/AndroidRuntime(366): at android.content.res.TypedArray.getDrawable(TypedArray.java:601)
02-18 22:47:00.263: E/AndroidRuntime(366): at android.widget.ImageView.<init>(ImageView.java:118)
02-18 22:47:00.263: E/AndroidRuntime(366): at android.widget.ImageView.<init>(ImageView.java:108)
02-18 22:47:00.263: E/AndroidRuntime(366): ... 27 more
Okay, so I found this simple listview thing, but i cant get it running.
import android.os.Bundle;
import android.app.Activity;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import android.widget.ListView;
import android.widget.SimpleAdapter;
public class MainActivity extends Activity {
// Array of integers points to images stored in /res/drawable-hdpi/
int[] vehs = new int[]{
R.drawable.veh1,
R.drawable.veh2,
R.drawable.veh3,
R.drawable.veh4,
R.drawable.veh5,
R.drawable.veh6,
R.drawable.veh7,
R.drawable.veh8,
R.drawable.veh9,
R.drawable.veh10,
R.drawable.veh11,
R.drawable.veh12,
R.drawable.veh13,
R.drawable.veh14,
R.drawable.veh15,
R.drawable.veh16,
R.drawable.veh17,
R.drawable.veh18,
R.drawable.veh19,
R.drawable.veh20,
R.drawable.veh21,
R.drawable.veh22,
R.drawable.veh23,
R.drawable.veh24,
R.drawable.veh25,
R.drawable.veh26,
R.drawable.veh27,
R.drawable.veh28,
R.drawable.veh29,
R.drawable.veh30,
R.drawable.veh31,
R.drawable.veh32,
R.drawable.veh33,
R.drawable.veh34,
R.drawable.veh35,
R.drawable.veh36,
};
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Each row in the list stores country name, currency and flag
List<HashMap<String,String>> aList = new ArrayList<HashMap<String,String>>();
for(int i=0;i<10;i++){
HashMap<String, String> hm = new HashMap<String,String>();
hm.put("", Integer.toString(vehs[i]) );
aList.add(hm);
}
// Keys used in Hashmap
String[] from = { "flag","txt","cur" };
// Ids of views in listview_layout
int[] to = { R.id.vehs};
// Instantiating an adapter to store each items
// R.layout.listview_layout defines the layout of each item
SimpleAdapter adapter = new SimpleAdapter(getBaseContext(), aList, R.layout.listview_layout, from, to);
// Getting a reference to listview of main.xml layout file
ListView listView = ( ListView ) findViewById(R.id.listview);
// Setting the adapter to the listView
listView.setAdapter(adapter);
}
}
If you could help me with this, that would be great! :D
The problem you have here is you are loading everything at the same time, I guess. You should try using a ListView and inflate each row! The way this would work is that your app will load an ImageView or two at once and the rest will be left on the side, until the user scrolls close to it. The tutorial I found for this is (watch #71 to about #87 - you can get all his videos at slidenerd.com):
http://www.youtube.com/watch?v=uic3TVp_j3M#t=0
You should also resize your bitmaps so they aren't loaded in full resolution. You don't need a 1920x1080 image for a 540*420 screen, for example. The following link shows you how to take care of this.
http://developer.android.com/training/displaying-bitmaps/index.html
So, in the end, you will have only 1 ListView, 1 ImageView and way less code and way less confusion :P
EDIT: QUICK GUIDE:
I'll walk you through the ListView method only, because I think the scaling down of an image example by Google is easy to follow.
So, first of all, you will have the following:
myActivity.xml (the main Activity where you need these images)
Single row (the layout of what a single row looks like)
MyActivity.java (The java class for your activity)
myActivity.xml will contain a ListView:
<ListView
android:id="#+id/lvList"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true" >
</ListView>
singleRow.xml will contain just an ImageView - you will use the same ImageView's LayoutParamaters and mirror them 36 times:
<ImageView
android:id="#+id/ivImage"
android:layout_width="50dp"
android:layout_height="85dp"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:src="#drawable/ic_launcher" />
MyActivity.java - where all the magic happens!
public class MyActivity extends Activity implements OnItemClickListener {
ListView lv;
#Override
protected void onCreate(Bundle savedInstanceState) {
lv = (ListView) findViewById(R.id.lvList);
MyAdapter adapter = new MyAdapter(this);
lv.setAdapter(adapter);
lv.setOnItemClickListener(this);
}
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
MyView holder = (MyView) view.getTag(); // This will get the tag of the item click - that is set up below
}
//Create a holder for the image that will be in an ImageView
class SingleRowData {
int img;
SingleRowData(int img) {
this.img = img;
}
}
//A reference to the ImageView that needs to be copied
private class MyView {
ImageView ivImg;
MyView(View v) {
ivImg = (ImageView) v.findViewById(R.id.ivHomePageRow);
}
}
class MyAdapter extends BaseAdapter{
ArrayList<SingleHPSRow> list;
Context context;
public MyAdapter(Context context) {
this.context = context;
list = new ArrayList<SingleRowData>();
...
int[] imgId = ...; // let's say you are getting all the images from your resources .. you will have to set this up, I'm guessing you know how to.
for(int item = 0; item < imgUrl.length; i++) {
list.add(imgId[item]);
}
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int position) {
return list.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
view row = convertView; //This will try to see if the row has already been loaded b4
MyView holder = null; initialize our custome View for the row
if(row == null) { // new row
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); //Get the LayoutInflater
row = inflater.inflate(R.layout.singleRow, parent, false); //Reference to the row layout
holder = new MyView(row);
row.setTag(holder); // Give the row a tag - the holder that contains the item
} else { // old row
holder = (MyView) row.getTag(); //Get the tag that was assigned
}
SingleRowData item = list.get(position); //Get the item at the current position
int image = item.img; //Get the imgId assigned to the current item
holder.ivImg.setImageResource(image); //Load image for the current position
return row; // Return the current row
}
}
}
Hopefull this is well explained, I copied and shortened one of my codes. Let me know if there's something you don't understand
I am new to android application development. I was doing this tutorial app.It's a very simple one. It adds one and subtracts one from the counter.When I run it in the emulator ,it says "Unfortunately tutorial has stopped working." There are no errors in the code. The API level is 17. Please help me out.
Code for java:
public class Startingpoint extends Activity {
int counter=0;
Button add,subtract;
TextView display;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.startingpoint);
add = (Button) findViewById(R.id.bAdd);
subtract= (Button) findViewById(R.id.bSubtract);
display= (Button) findViewById(R.id.text);
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
counter++;
display.setText("The total is " + counter);
}
});
subtract.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
counter--;
display.setText("The total is " + counter);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.startingpoint, menu);
return true;
}
}
Layout code in 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" >
<TextView android:id="#+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Your total is 0"
android:textSize="35dp"
android:layout_gravity="center"
android:gravity="center"/>
<Button android:layout_width="250dp"
android:layout_height="wrap_content"
android:text="Add One"
android:layout_gravity="center"
android:textSize="25dp"
android:id="#+id/bAdd"/>
<Button android:layout_width="250dp"
android:layout_height="wrap_content"
android:text="Subtract One"
android:layout_gravity="center"
android:textSize="25dp"
android:id="#+id/bSubtract"/>
</LinearLayout>
Here is the logcat :
03-02 02:45:10.730: D/AndroidRuntime(780): Shutting down VM
03-02 02:45:10.730: W/dalvikvm(780): threadid=1: thread exiting with uncaught exception (group=0x40a71930)
03-02 02:45:10.750: E/AndroidRuntime(780): FATAL EXCEPTION: main
03-02 02:45:10.750: E/AndroidRuntime(780): java.lang.RuntimeException: Unable to start activity ComponentInfo{tutorial.example.tutorial/tutorial.example.tutorial.Startingpoint}: java.lang.ClassCastException: android.widget.TextView cannot be cast to android.widget.Button
03-02 02:45:10.750: E/AndroidRuntime(780): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
03-02 02:45:10.750: E/AndroidRuntime(780): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
03-02 02:45:10.750: E/AndroidRuntime(780): at android.app.ActivityThread.access$600(ActivityThread.java:141)
03-02 02:45:10.750: E/AndroidRuntime(780): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
03-02 02:45:10.750: E/AndroidRuntime(780): at android.os.Handler.dispatchMessage(Handler.java:99)
03-02 02:45:10.750: E/AndroidRuntime(780): at android.os.Looper.loop(Looper.java:137)
03-02 02:45:10.750: E/AndroidRuntime(780): at android.app.ActivityThread.main(ActivityThread.java:5041)
03-02 02:45:10.750: E/AndroidRuntime(780): at java.lang.reflect.Method.invokeNative(Native Method)
03-02 02:45:10.750: E/AndroidRuntime(780): at java.lang.reflect.Method.invoke(Method.java:511)
03-02 02:45:10.750: E/AndroidRuntime(780): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
03-02 02:45:10.750: E/AndroidRuntime(780): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
03-02 02:45:10.750: E/AndroidRuntime(780): at dalvik.system.NativeStart.main(Native Method)
03-02 02:45:10.750: E/AndroidRuntime(780): Caused by: java.lang.ClassCastException: android.widget.TextView cannot be cast to android.widget.Button
03-02 02:45:10.750: E/AndroidRuntime(780): at tutorial.example.tutorial.Startingpoint.onCreate(Startingpoint.java:22)
03-02 02:45:10.750: E/AndroidRuntime(780): at android.app.Activity.performCreate(Activity.java:5104)
03-02 02:45:10.750: E/AndroidRuntime(780): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
03-02 02:45:10.750: E/AndroidRuntime(780): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
03-02 02:45:10.750: E/AndroidRuntime(780): ... 11 more
display= (Button) findViewById(R.id.text);
should be
display= (TextView) findViewById(R.id.text);
Since display is supposed to reference a TextView instance, but you're explictly casting into a Button, and these are not compatible types.
As you got the answer from A-C this time, but for next time in android application development a important suggestion:
Always see the logcat for error, and see the "Caused by:" tag, It specifies what was the cause of the problem with sufficient detail, Also see the line no that caused that error.
And try to find what can be wrong with that line of code.
For example: in your logcat it is showing-
Caused by: java.lang.ClassCastException: android.widget.TextView cannot be cast to android.widget.Button
at tutorial.example.tutorial.Startingpoint.onCreate(Startingpoint.java:22)
So you can try to read the log, and you will understand that in your file Startingpoint.java at line 22 which is located in onCreate method the error is android.widget.TextView cannot be cast to android.widget.Button. So you can easily remove your errors without any help.
Hope that helps not only you current problem but prevented your future time and efforts.