Update and remove GridView items at runtime - java

i am developing a project where i compare the images of two items,So if two items will have same image after clicking these items should be hide. my code is given below and this code encounter a problem. is this a logical error or any other issue? i try to solve the issue but did't resolve.. Please guide me... here is my main Activity.
MainActivity.java
public class MainActivity extends Activity {
Context ctx;
int imagesArray[];
ImageAdapter adapter;
List<Integer> pictures;
boolean flage = false;
GridView gridView;
int save1, save2;
int img1 = -1, img2 = -1;
public int OriginalArray[] = { R.drawable.sample_0, R.drawable.sample_1,
R.drawable.sample_2, R.drawable.sample_3, R.drawable.sample_0,
R.drawable.sample_1, R.drawable.sample_2, R.drawable.sample_3 };
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final ImageView myimage = new ImageView(ctx);
gridView = (GridView) findViewById(R.id.gv_memory);
gridView.setAdapter(adapter);
shuffleArray();
gridView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1,
int position, long arg3) {
// TODO Auto-generated method stub
myimage.setImageResource(pictures.get(position));
if (flage == false) {
img1 = pictures.get(position);
flage = true;
} else if (flage == true) {
img2 = pictures.get(position);
checkResult();
flage = false;
}
}
private void checkResult() {
// TODO Auto-generated method stub
if (img1 == img2) {
adapter.pictureList.remove(img1);
adapter.pictureList.remove(img2);
adapter.notifyDataSetChanged();
Toast.makeText(MainActivity.this, "Congratualatin !!!!",
Toast.LENGTH_LONG).show();
} else {
Toast.makeText(MainActivity.this, "Sorry!!!!",
Toast.LENGTH_LONG).show();
}
}
});
}
private void shuffleArray() {
// TODO Auto-generated method stub
pictures = new ArrayList<Integer>();
for (int index = 0; index < OriginalArray.length; index++) {
pictures.add(OriginalArray[index]);
}
Collections.shuffle(pictures);
}
}
ImageAdapter.java
public class ImageAdapter extends BaseAdapter {
private Context context;
List<Integer> pictureList = new ArrayList<Integer>();
public ImageAdapter(Context c) {
context = c;
for (int i = 0; i < 8; i++) {
pictureList.add(R.drawable.question);
}
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return (pictureList.size());
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return pictureList.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
ImageView myimage = new ImageView(context);
myimage.setImageResource(pictureList.get(position));
myimage.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
myimage.setLayoutParams(new GridView.LayoutParams(70, 70));
return myimage;
}
}
LogCat.
03-14 06:09:03.793: D/dalvikvm(2877): GC_FOR_ALLOC freed 54K, 8% free 2771K/2996K, paused 111ms, total 117ms
03-14 06:09:03.802: I/dalvikvm-heap(2877): Grow heap (frag case) to 3.943MB for 1127536-byte allocation
03-14 06:09:03.922: D/dalvikvm(2877): GC_FOR_ALLOC freed 2K, 6% free 3870K/4100K, paused 118ms, total 118ms
03-14 06:09:03.962: D/AndroidRuntime(2877): Shutting down VM
03-14 06:09:03.962: W/dalvikvm(2877): threadid=1: thread exiting with uncaught exception (group=0x41465700)
03-14 06:09:03.972: E/AndroidRuntime(2877): FATAL EXCEPTION: main
03-14 06:09:03.972: E/AndroidRuntime(2877): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.memory/com.example.memory.MainActivity}: java.lang.NullPointerException
03-14 06:09:03.972: E/AndroidRuntime(2877): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2211)
03-14 06:09:03.972: E/AndroidRuntime(2877): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
03-14 06:09:03.972: E/AndroidRuntime(2877): at android.app.ActivityThread.access$600(ActivityThread.java:141)
03-14 06:09:03.972: E/AndroidRuntime(2877): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
03-14 06:09:03.972: E/AndroidRuntime(2877): at android.os.Handler.dispatchMessage(Handler.java:99)
03-14 06:09:03.972: E/AndroidRuntime(2877): at android.os.Looper.loop(Looper.java:137)
03-14 06:09:03.972: E/AndroidRuntime(2877): at android.app.ActivityThread.main(ActivityThread.java:5103)
03-14 06:09:03.972: E/AndroidRuntime(2877): at java.lang.reflect.Method.invokeNative(Native Method)
03-14 06:09:03.972: E/AndroidRuntime(2877): at java.lang.reflect.Method.invoke(Method.java:525)
03-14 06:09:03.972: E/AndroidRuntime(2877): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
03-14 06:09:03.972: E/AndroidRuntime(2877): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
03-14 06:09:03.972: E/AndroidRuntime(2877): at dalvik.system.NativeStart.main(Native Method)
03-14 06:09:03.972: E/AndroidRuntime(2877): Caused by: java.lang.NullPointerException
03-14 06:09:03.972: E/AndroidRuntime(2877): at android.view.ViewConfiguration.get(ViewConfiguration.java:318)
03-14 06:09:03.972: E/AndroidRuntime(2877): at android.view.View.<init>(View.java:3264)
03-14 06:09:03.972: E/AndroidRuntime(2877): at android.widget.ImageView.<init>(ImageView.java:112)
03-14 06:09:03.972: E/AndroidRuntime(2877): at com.example.memory.MainActivity.onCreate(MainActivity.java:33)
03-14 06:09:03.972: E/AndroidRuntime(2877): at android.app.Activity.performCreate(Activity.java:5133)
03-14 06:09:03.972: E/AndroidRuntime(2877): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
03-14 06:09:03.972: E/AndroidRuntime(2877): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2175)
03-14 06:09:03.972: E/AndroidRuntime(2877): ... 11 more
03-14 06:14:04.503: I/Process(2877): Sending signal. PID: 2877 SIG: 9

You have
final ImageView myimage = new ImageView(ctx);
ctz is not initialized. Its only declared as Context ctx;
You have this
gridView.setAdapter(adapter);
But you need to intialize adapter before using the same
So change to
setContentView(R.layout.main);
final ImageView myimage = new ImageView(this); //this refers to Activity context
gridView = (GridView) findViewById(R.id.gv_memory);
adapter = new ImageAdapter(this)
gridView.setAdapter(adapter);

Related

How can I make an Adapter ListView on a Fragment using an SQL database?

I'm trying to call or see a ListView with this kind of specification:
Wireframe
Here is my code. This is the fragment named EducacionFragment, and here is where I want to call the layout "eventos":
public class EducacionFragment extends ListFragment{
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.eventos_layout, container, false);
//((MainActivity) getActivity()).getSupportActionBar().setTitle("Eventos");
//Elementos_Eventos elementos_eventos = new Elementos_Eventos();
ListView listview =(ListView)view.findViewById(R.id.listView2);
Adaptador_Eventos adaptador = new Adaptador_Eventos(getActivity());
//adaptador = new Adaptador_Eventos(getActivity());
listview.setAdapter(adaptador);
return view;
}
}'
Here is my class named Elementos_Eventos, where I get all the information from my database, and put in a list:
public class Elementos_Eventos {
//URL to get JSON Array
private static String url = "http://ucwm.co.nf/Evento_app.php";
//JSON Node Names
private static final String TAG_EVENTOS = "eventos";
private static final String TAG_ID = "idEvento";
private static final String TAG_NAME = "Nombre";
private static final String TAG_DESCRIP = "Descripcion";
private static final String TAG_FECHAI = "FechaInicio";
private static final String TAG_HORA = "Hora";
private static final String TAG_FECHAF = "FechaFinal";
private static final String TAG_LUGAR = "Lugar";
private static JSONArray eventos = null;
public static List<Elemento_Eventos> listaElementos = elementos();
public Elementos_Eventos() {
listaElementos = elementos();
}
static Elemento_Eventos elemento(int id) {
return listaElementos.get(id);
}
public static ArrayList<Elemento_Eventos> elementos() {
JSONParser jParser = new JSONParser();
JSONObject json;
// Getting JSON from URL
json = jParser.getJSONFromUrl(url);
ArrayList<Elemento_Eventos> elementos;
elementos = null;
try {
// Getting JSON Array from URL
eventos = json.getJSONArray(TAG_EVENTOS);
elementos = new ArrayList<Elemento_Eventos>();
for (int i = 0; i < eventos.length(); i++) {
JSONObject c = eventos.getJSONObject(i);
// Storing JSON item in a Variable
String id = c.getString(TAG_ID);
String nombre = c.getString(TAG_NAME);
String descripcion = c.getString(TAG_DESCRIP);
String fechaInicio = c.getString(TAG_FECHAI);
String hora = c.getString(TAG_HORA);
String fechaFinal = c.getString(TAG_FECHAF);
String lugar = c.getString(TAG_LUGAR);
elementos.add(new Elemento_Eventos(id, nombre,descripcion, fechaInicio, hora, fechaFinal, lugar));
}
}
catch (JSONException e) {
e.printStackTrace();
}
return elementos;
}
public List<String> listaElementos()
{
ArrayList<String> todos = new ArrayList<String>();
for (Elemento_Eventos e:listaElementos)
todos.add(e.getNombre());
return todos;
}
public static int size() {
return listaElementos.size();
}
Here is my class named Elemento_Eventos, where I declare a element one by one:
public class Elemento_Eventos {
private String id;
private String nombre;
private String descripcion;
private String feInicio;
private String hora;
private String feFinal;
private String lugar;
public Elemento_Eventos(String id,String nombre, String descripcion, String feInicio, String hora, String feFinal, String lugar){
setId(id);
setNombre(nombre);
setDescripcion(descripcion);
setFeInicio(feInicio);
setHora(hora);
setFeFinal(feFinal);
setLugar(lugar);
}
//*********INICIO DE LOS SETS******************
public void setId(String id){
this.id=id;
}
public void setNombre(String nombre){
this.nombre=nombre;
}
public void setDescripcion(String descripcion){
this.descripcion=descripcion;
}
public void setFeInicio(String feInicio){
this.feInicio=feInicio;
}
public void setHora(String hora){
this.hora=hora;
}
public void setFeFinal(String feFinal){
this.feFinal=feFinal;
}
public void setLugar(String lugar){
this.lugar=lugar;
}
//*********FINAL DE LOS SETS******************
//*********INICIO DE LOS GETS******************
public String getId(){
return id;
}
public String getNombre(){
return nombre;
}
public String getDescripcion(){
return descripcion;
}
public String getFeInicio(){
return feInicio;
}
public String getHora(){
return hora;
}
public String getFeFinal(){
return feFinal;
}
public String getLugar(){
return lugar;
}
//*********FINAL DE LOS SETS******************
}
And finally here is my class named Adaptador_Eventos, where I put all this information in textViews:
public class Adaptador_Eventos extends BaseAdapter{
private final Activity actividad;
public Adaptador_Eventos(Activity actividad) {
super();
this.actividad = actividad;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
Elemento_Eventos elemento = Elementos_Eventos.elemento(position);
LayoutInflater inflater = actividad.getLayoutInflater();
View view = inflater.inflate(R.layout.elemento_eventos, null,true);
TextView nombreDelEvento, lugar, fecha, descripcion;
ImageView logo_tipo;
nombreDelEvento = (TextView) view.findViewById(R.id.nom_evento);
lugar = (TextView) view.findViewById(R.id.lugar_evento);
fecha = (TextView) view.findViewById(R.id.fecha_evento);
descripcion = (TextView) view.findViewById(R.id.desc_evento);
logo_tipo = (ImageView) view.findViewById(R.id.imageView);
nombreDelEvento.setText(elemento.getNombre());
lugar.setText(elemento.getLugar());
fecha.setText(elemento.getFeInicio());
descripcion.setText(elemento.getDescripcion());
int id = R.drawable.kcc;
logo_tipo.setImageResource(id);
logo_tipo.setScaleType(ImageView.ScaleType.FIT_END);
return view;
}
#Override
public int getCount() {
return Elementos_Eventos.size();
}
#Override
public Object getItem(int position) {
return Elementos_Eventos.elemento(position);
}
#Override
public long getItemId(int position) {
return position;
}
}
And when I call the fragment Educacion, it crashes my aplication with the message
Unfortunately, Unidas Contigo A.C. has stopped
Here's the stack trace that appears:
11-12 05:10:00.279 7414-7414/? D/dalvikvm? Late-enabling CheckJNI
11-12 05:10:01.059 7414-7414/com.example.juanisaac.unidascontigoac W/dalvikvm? VFY: unable to find class referenced in signature (Landroid/view/SearchEvent;)
11-12 05:10:01.095 7414-7414/com.example.juanisaac.unidascontigoac I/dalvikvm? Could not find method android.view.Window$Callback.onSearchRequested, referenced from method android.support.v7.internal.view.WindowCallbackWrapper.onSearchRequested
11-12 05:10:01.107 7414-7414/com.example.juanisaac.unidascontigoac W/dalvikvm? VFY: unable to resolve interface method 15449: Landroid/view/Window$Callback;.onSearchRequested (Landroid/view/SearchEvent;)Z
11-12 05:10:01.119 7414-7414/com.example.juanisaac.unidascontigoac D/dalvikvm? VFY: replacing opcode 0x72 at 0x0002
11-12 05:10:01.123 7414-7414/com.example.juanisaac.unidascontigoac I/dalvikvm? Could not find method android.view.Window$Callback.onWindowStartingActionMode, referenced from method android.support.v7.internal.view.WindowCallbackWrapper.onWindowStartingActionMode
11-12 05:10:01.139 7414-7414/com.example.juanisaac.unidascontigoac W/dalvikvm? VFY: unable to resolve interface method 15453: Landroid/view/Window$Callback;.onWindowStartingActionMode (Landroid/view/ActionMode$Callback;I)Landroid/view/ActionMode;
11-12 05:10:01.139 7414-7414/com.example.juanisaac.unidascontigoac D/dalvikvm? VFY: replacing opcode 0x72 at 0x0002
11-12 05:10:01.407 7414-7414/com.example.juanisaac.unidascontigoac I/AppCompatViewInflater? app:theme is now deprecated. Please move to using android:theme instead.
11-12 05:10:01.419 7414-7414/com.example.juanisaac.unidascontigoac I/dalvikvm? Could not find method android.content.res.TypedArray.getChangingConfigurations, referenced from method android.support.v7.internal.widget.TintTypedArray.getChangingConfigurations
11-12 05:10:01.423 7414-7414/com.example.juanisaac.unidascontigoac W/dalvikvm? VFY: unable to resolve virtual method 426: Landroid/content/res/TypedArray;.getChangingConfigurations ()I
11-12 05:10:01.423 7414-7414/com.example.juanisaac.unidascontigoac D/dalvikvm? VFY: replacing opcode 0x6e at 0x0002
11-12 05:10:01.431 7414-7414/com.example.juanisaac.unidascontigoac I/dalvikvm? Could not find method android.content.res.TypedArray.getType, referenced from method android.support.v7.internal.widget.TintTypedArray.getType
11-12 05:10:01.439 7414-7414/com.example.juanisaac.unidascontigoac W/dalvikvm? VFY: unable to resolve virtual method 448: Landroid/content/res/TypedArray;.getType (I)I
11-12 05:10:01.439 7414-7414/com.example.juanisaac.unidascontigoac D/dalvikvm? VFY: replacing opcode 0x6e at 0x0002
11-12 05:10:01.479 7414-7414/com.example.juanisaac.unidascontigoac I/AppCompatViewInflater? app:theme is now deprecated. Please move to using android:theme instead.
11-12 05:10:01.547 7414-7416/com.example.juanisaac.unidascontigoac D/dalvikvm? GC_CONCURRENT freed 192K, 3% free 8841K/9068K, paused 13ms+0ms, total 26ms
11-12 05:10:01.631 7414-7414/com.example.juanisaac.unidascontigoac D/dalvikvm? GC_FOR_ALLOC freed 5K, 3% free 8858K/9068K, paused 13ms, total 14ms
11-12 05:10:01.707 7414-7414/com.example.juanisaac.unidascontigoac I/dalvikvm-heap? Grow heap (frag case) to 10.120MB for 1517220-byte allocation
11-12 05:10:01.719 7414-7424/com.example.juanisaac.unidascontigoac D/dalvikvm? GC_FOR_ALLOC freed <1K, 3% free 10340K/10552K, paused 14ms, total 14ms
11-12 05:10:01.739 7414-7416/com.example.juanisaac.unidascontigoac D/dalvikvm? GC_CONCURRENT freed 0K, 3% free 10340K/10552K, paused 8ms+0ms, total 11ms
11-12 05:10:01.759 7414-7414/com.example.juanisaac.unidascontigoac D/dalvikvm? GC_FOR_ALLOC freed <1K, 3% free 10339K/10552K, paused 6ms, total 6ms
11-12 05:10:01.875 7414-7414/com.example.juanisaac.unidascontigoac I/dalvikvm-heap? Grow heap (frag case) to 15.908MB for 6068844-byte allocation
11-12 05:10:01.887 7414-7424/com.example.juanisaac.unidascontigoac D/dalvikvm? GC_FOR_ALLOC freed <1K, 2% free 16266K/16480K, paused 12ms, total 12ms
11-12 05:10:01.919 7414-7416/com.example.juanisaac.unidascontigoac D/dalvikvm? GC_CONCURRENT freed <1K, 2% free 16266K/16480K, paused 7ms+0ms, total 20ms
11-12 05:10:02.051 7414-7414/com.example.juanisaac.unidascontigoac D/libEGL? loaded /system/lib/egl/libEGL_genymotion.so
11-12 05:10:02.067 7414-7414/com.example.juanisaac.unidascontigoac D/? HostConnection::get() New Host Connection established 0xb92c56a8, tid 7414
11-12 05:10:02.087 7414-7414/com.example.juanisaac.unidascontigoac D/libEGL? loaded /system/lib/egl/libGLESv1_CM_genymotion.so
11-12 05:10:02.087 7414-7414/com.example.juanisaac.unidascontigoac D/libEGL? loaded /system/lib/egl/libGLESv2_genymotion.so
11-12 05:10:02.147 7414-7414/com.example.juanisaac.unidascontigoac W/EGL_genymotion? eglSurfaceAttrib not implemented
11-12 05:10:02.171 7414-7414/com.example.juanisaac.unidascontigoac D/OpenGLRenderer? Enabling debug mode 0
11-12 05:10:04.511 7414-7414/com.example.juanisaac.unidascontigoac I/Choreographer? Skipped 46 frames! The application may be doing too much work on its main thread.
11-12 05:10:05.599 7414-7414/com.example.juanisaac.unidascontigoac W/dalvikvm? Exception Landroid/os/NetworkOnMainThreadException; thrown while initializing Lcom/example/juanisaac/unidascontigoac/Elementos_Eventos;
11-12 05:10:05.599 7414-7414/com.example.juanisaac.unidascontigoac D/AndroidRuntime? Shutting down VM
11-12 05:10:05.603 7414-7414/com.example.juanisaac.unidascontigoac W/dalvikvm? threadid=1: thread exiting with uncaught exception (group=0xa620e908)
11-12 05:10:05.615 7414-7414/com.example.juanisaac.unidascontigoac E/AndroidRuntime? FATAL EXCEPTION: main
java.lang.ExceptionInInitializerError
at com.example.juanisaac.unidascontigoac.Adaptador_Eventos.getCount(Adaptador_Eventos.java:57)
at android.widget.ListView.setAdapter(ListView.java:462)
at com.example.juanisaac.unidascontigoac.Fragments.EducacionFragment.onCreateView(EducacionFragment.java:40)
at android.support.v4.app.Fragment.performCreateView(Fragment.java:1962)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1016)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1197)
at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:738)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1562)
at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:483)
at android.os.Handler.handleCallback(Handler.java:725)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5041)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
at dalvik.system.NativeStart.main(Native Method)
Caused by: android.os.NetworkOnMainThreadException
at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1117)
at java.net.InetAddress.lookupHostByName(InetAddress.java:385)
at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
at java.net.InetAddress.getAllByName(InetAddress.java:214)
at org.apache.http.impl.conn.DefaultClientConnectionOperator.openConnection(DefaultClientConnectionOperator.java:137)
at org.apache.http.impl.conn.AbstractPoolEntry.open(AbstractPoolEntry.java:164)
at org.apache.http.impl.conn.AbstractPooledConnAdapter.open(AbstractPooledConnAdapter.java:119)
at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:360)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
at com.example.juanisaac.unidascontigoac.JSONParser.getJSONFromUrl(JSONParser.java:37)
at com.example.juanisaac.unidascontigoac.Elementos_Eventos.elementos(Elementos_Eventos.java:55)
at com.example.juanisaac.unidascontigoac.Elementos_Eventos.<clinit>(Elementos_Eventos.java:39)
at com.example.juanisaac.unidascontigoac.Adaptador_Eventos.getCount(Adaptador_Eventos.java:57)
at android.widget.ListView.setAdapter(ListView.java:462)
at com.example.juanisaac.unidascontigoac.Fragments.EducacionFragment.onCreateView(EducacionFragment.java:40)
at android.support.v4.app.Fragment.performCreateView(Fragment.java:1962)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1016)
at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1197)
at android.support.v4.app.BackStackRecord.run(BackStackRecord.java:738)
at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1562)
at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:483)
at android.os.Handler.handleCallback(Handler.java:725)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5041)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
at dalvik.system.NativeStart.main(Native Method)
11-12 05:10:08.059 7414-7414/com.example.juanisaac.unidascontigoac I/Process? Sending signal. PID: 7414 SIG: 9
There are two problems with the above code. When a class is loaded the first time, it is getting data from a URL in elementos() function which is happening by call to setAdapter in onCreate().
Network activity on the main/UI thread is not allowed on Android. Hence, it is throwing NetworkOnMainThread as an exception.
Second, you should connect to the URL using asyncTask and create listaElements list in onPostExecute() preferrably.
You'll need to create a list variable and use it to return the object in your getCount() function;
List<Elemento_Eventos> myList = new ArrayList<Elemento_Eventos>();
public Adaptador_Eventos(Activity actividad, List<Elemento_Eventos> myList){
super();
this.actividad = actividad;
this.myList = myList;
}
Then in your getCount function:
#Override
public int getCount() {
return myList.size();
}
For class Adaptador_Eventos, change
public static List<Elemento_Eventos> listaElementos = elementos();
public Elementos_Eventos() {
listaElementos = elementos();
}
to
public static List<Elemento_Eventos> listaElementos ;
public Elementos_Eventos() {
}
public static void init(){
listaElementos = elementos();
}
For class EducacionFragment, change
public class EducacionFragment extends ListFragment{
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.eventos_layout, container, false);
//((MainActivity) getActivity()).getSupportActionBar().setTitle("Eventos");
//Elementos_Eventos elementos_eventos = new Elementos_Eventos();
ListView listview =(ListView)view.findViewById(R.id.listView2);
Adaptador_Eventos adaptador = new Adaptador_Eventos(getActivity());
//adaptador = new Adaptador_Eventos(getActivity());
listview.setAdapter(adaptador);
return view;
}
}
to
public class EducacionFragment extends ListFragment{
private ListView listview;
private Adaptador_Eventos adaptador;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.eventos_layout, container, false);
//((MainActivity) getActivity()).getSupportActionBar().setTitle("Eventos");
//Elementos_Eventos elementos_eventos = new Elementos_Eventos();
listview =(ListView)view.findViewById(R.id.listView2);
adaptador = new Adaptador_Eventos(getActivity());
//adaptador = new Adaptador_Eventos(getActivity());
new AsyncTask(){
#Override
protected Object doInBackground(Object[] params) {
Elementos_Eventos.init();
return null;
}
#Override
protected void onPostExecute(Object o) {
super.onPostExecute(o);
listview.setAdapter(adaptador);
}
}.execute();
return view;
}
}
Try it, and use AsyncTask to avoid a NetworkOnMainThread exception.

Remove GridView items at run time if two items have same images

i am developing a project where i compare two item images,So if two items will have same image after clicking these items it should be permanently delete from the GridView. my code is given below and this code encounter a problem. please any one help me.
MainActivity.java
public class MainActivity extends Activity {
Context ctx;
int imagesArray[];
GridViewContent adapter;
List<Integer> pictures, pictureList;
boolean flage = false;
int save1, save2;
int img1 = -1, img2 = -1;
public int OriginalArray[] = { R.drawable.sample_0, R.drawable.sample_1,
R.drawable.sample_2, R.drawable.sample_3, R.drawable.sample_0,
R.drawable.sample_1, R.drawable.sample_2, R.drawable.sample_3 };
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
shuffleArray();
final GridView grid = (GridView) findViewById(R.id.gv_memory);
grid.setAdapter(new GridViewContent(this));
}
private void shuffleArray() {
// TODO Auto-generated method stub
pictures = new ArrayList<Integer>();
for (int index = 0; index < OriginalArray.length; index++) {
pictures.add(OriginalArray[index]);
}
Collections.shuffle(pictures);
}
public class GridViewContent extends BaseAdapter {
private Context context;
private List<Integer> pictureList = new ArrayList<Integer>();
public GridViewContent(Context c) {
context = c;
for (int i = 0; i < 8; i++) {
pictureList.add(R.drawable.question);
}
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return (pictureList.size());
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return pictureList.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(final int position, final View arg1,
final ViewGroup arg2) {
// TODO Auto-generated method stub
final ImageView myimage = new ImageView(context);
myimage.setImageResource(pictureList.get(position));
// myimage.setImageResource(pictures.get(pictureArray[position]));
myimage.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
myimage.setLayoutParams(new GridView.LayoutParams(70, 70));
final GridView grid = (GridView) findViewById(R.id.gv_memory);
myimage.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
myimage.setImageResource(pictures.get(position));
// View v1 = new View(context);
if (flage == false) {
img1 = pictures.get(position);
// v1 = arg2.getChildAt(position);
save1 = position;
flage = true;
} else if (flage == true) {
img2 = pictures.get(position);
save2 = position;
checkResult(save1, save2);
flage = false;
}
// else if(f)
}
});
return myimage;
}
}
public void checkResult(int s1, int s2) {
if (img1 == img2) {
pictureList.remove(s1); //this is line no 116
pictureList.remove(s1);
adapter.notifyDataSetChanged();
Toast.makeText(MainActivity.this, "Congratualatin !!!!",
Toast.LENGTH_LONG).show();
} else {
Toast.makeText(MainActivity.this, "Sorry!!!!", Toast.LENGTH_LONG)
.show();
final GridView grid = (GridView) findViewById(R.id.gv_memory);
grid.setAdapter(new GridViewContent(this));
}
}
}
LogCat.
03-14 01:07:12.791: D/dalvikvm(1598): GC_FOR_ALLOC freed 38K, 7% free 2771K/2980K, paused 183ms, total 185ms
03-14 01:07:12.811: I/dalvikvm-heap(1598): Grow heap (frag case) to 3.943MB for 1127536-byte allocation
03-14 01:07:12.941: D/dalvikvm(1598): GC_FOR_ALLOC freed 2K, 6% free 3870K/4084K, paused 128ms, total 128ms
03-14 01:07:13.111: D/dalvikvm(1598): GC_FOR_ALLOC freed 4K, 5% free 4253K/4448K, paused 25ms, total 26ms
03-14 01:07:13.143: I/dalvikvm-heap(1598): Grow heap (frag case) to 5.688MB for 1440016-byte allocation
03-14 01:07:13.271: D/dalvikvm(1598): GC_FOR_ALLOC freed <1K, 4% free 5659K/5856K, paused 127ms, total 127ms
03-14 01:07:13.481: I/Choreographer(1598): Skipped 49 frames! The application may be doing too much work on its main thread.
03-14 01:07:13.571: D/gralloc_goldfish(1598): Emulator without GPU emulation detected.
03-14 01:08:36.011: D/dalvikvm(1598): GC_FOR_ALLOC freed 357K, 9% free 5587K/6116K, paused 34ms, total 35ms
03-14 01:08:36.021: I/dalvikvm-heap(1598): Grow heap (frag case) to 6.543MB for 971296-byte allocation
03-14 01:08:36.154: D/dalvikvm(1598): GC_FOR_ALLOC freed 1K, 8% free 6534K/7068K, paused 123ms, total 123ms
03-14 01:08:39.422: D/dalvikvm(1598): GC_FOR_ALLOC freed 2385K, 8% free 5419K/5876K, paused 76ms, total 78ms
03-14 01:08:39.492: D/dalvikvm(1598): GC_FOR_ALLOC freed 1K, 4% free 5654K/5876K, paused 40ms, total 41ms
03-14 01:08:41.352: D/AndroidRuntime(1598): Shutting down VM
03-14 01:08:41.352: W/dalvikvm(1598): threadid=1: thread exiting with uncaught exception (group=0x41465700)
03-14 01:08:41.532: E/AndroidRuntime(1598): FATAL EXCEPTION: main
03-14 01:08:41.532: E/AndroidRuntime(1598): java.lang.NullPointerException
03-14 01:08:41.532: E/AndroidRuntime(1598): at com.example.memoryforkids.MainActivity.checkResult(MainActivity.java:116)
03-14 01:08:41.532: E/AndroidRuntime(1598): at com.example.memoryforkids.MainActivity$GridViewContent$1.onClick(MainActivity.java:102)
03-14 01:08:41.532: E/AndroidRuntime(1598): at android.view.View.performClick(View.java:4240)
03-14 01:08:41.532: E/AndroidRuntime(1598): at android.view.View$PerformClick.run(View.java:17721)
03-14 01:08:41.532: E/AndroidRuntime(1598): at android.os.Handler.handleCallback(Handler.java:730)
03-14 01:08:41.532: E/AndroidRuntime(1598): at android.os.Handler.dispatchMessage(Handler.java:92)
03-14 01:08:41.532: E/AndroidRuntime(1598): at android.os.Looper.loop(Looper.java:137)
03-14 01:08:41.532: E/AndroidRuntime(1598): at android.app.ActivityThread.main(ActivityThread.java:5103)
03-14 01:08:41.532: E/AndroidRuntime(1598): at java.lang.reflect.Method.invokeNative(Native Method)
03-14 01:08:41.532: E/AndroidRuntime(1598): at java.lang.reflect.Method.invoke(Method.java:525)
03-14 01:08:41.532: E/AndroidRuntime(1598): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
03-14 01:08:41.532: E/AndroidRuntime(1598): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
03-14 01:08:41.532: E/AndroidRuntime(1598): at dalvik.system.NativeStart.main(Native Method)
main.xml
<?xml version="1.0" encoding="utf-8"?>
<GridView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/gv_memory"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:columnWidth="90dp"
android:gravity="center"
android:horizontalSpacing="10dp"
android:numColumns="auto_fit"
android:stretchMode="columnWidth"
android:verticalSpacing="10dp" >
</GridView>
Thanks in advance..
Ok so, I found the bug, you have defined the pictureList variable in two places, the one being initialized inside the adapter class is a local variable. When checkResult is called, it uses the pictureList variable belonging to the main activity class. Do the following:
1) Remove the local variable inside the adapter class.
2) Initialize the pictureList variable that has been defined in the activity class.
This fixes the error. Its working fine on my machine now!
Also, there are a lot of issues with the logic you are using, you will realize that once you fix this error.

Shutting down VM

I m learning android please help me. It gives me following errors in logcat.
02-27 14:14:42.455: D/dalvikvm(1655): GC_FOR_ALLOC freed 46K, 5% free 2891K/3020K, paused 152ms, total 156ms
02-27 14:14:42.465: I/dalvikvm-heap(1655): Grow heap (frag case) to 3.668MB for 810016-byte allocation
02-27 14:14:42.545: D/dalvikvm(1655): GC_FOR_ALLOC freed 2K, 4% free 3680K/3812K, paused 76ms, total 77ms
02-27 14:14:43.425: I/Choreographer(1655): Skipped 35 frames! The application may be doing too much work on its main thread.
02-27 14:14:43.645: D/gralloc_goldfish(1655): Emulator without GPU emulation detected.
02-27 14:14:48.395: I/Choreographer(1655): Skipped 58 frames! The application may be doing too much work on its main thread.
02-27 14:14:49.725: I/Choreographer(1655): Skipped 58 frames! The application may be doing too much work on its main thread.
02-27 14:14:52.355: I/Choreographer(1655): Skipped 61 frames! The application may be doing too much work on its main thread.
02-27 14:14:55.195: D/AndroidRuntime(1655): Shutting down VM
02-27 14:14:55.195: W/dalvikvm(1655): threadid=1: thread exiting with uncaught exception (group=0xb3aaaba8)
02-27 14:14:55.275: E/AndroidRuntime(1655): FATAL EXCEPTION: main
02-27 14:14:55.275: E/AndroidRuntime(1655): Process: com.example.dreamhome, PID: 1655
02-27 14:14:55.275: E/AndroidRuntime(1655): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.dreamhome/com.example.dreamhome.LoginFormActivity}: java.lang.NullPointerException
02-27 14:14:55.275: E/AndroidRuntime(1655): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2195)
02-27 14:14:55.275: E/AndroidRuntime(1655): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
02-27 14:14:55.275: E/AndroidRuntime(1655): at android.app.ActivityThread.access$800(ActivityThread.java:135)
02-27 14:14:55.275: E/AndroidRuntime(1655): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
02-27 14:14:55.275: E/AndroidRuntime(1655): at android.os.Handler.dispatchMessage(Handler.java:102)
02-27 14:14:55.275: E/AndroidRuntime(1655): at android.os.Looper.loop(Looper.java:136)
02-27 14:14:55.275: E/AndroidRuntime(1655): at android.app.ActivityThread.main(ActivityThread.java:5017)
02-27 14:14:55.275: E/AndroidRuntime(1655): at java.lang.reflect.Method.invokeNative(Native Method)
02-27 14:14:55.275: E/AndroidRuntime(1655): at java.lang.reflect.Method.invoke(Method.java:515)
02-27 14:14:55.275: E/AndroidRuntime(1655): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
02-27 14:14:55.275: E/AndroidRuntime(1655): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
02-27 14:14:55.275: E/AndroidRuntime(1655): at dalvik.system.NativeStart.main(Native Method)
02-27 14:14:55.275: E/AndroidRuntime(1655): Caused by: java.lang.NullPointerException
02-27 14:14:55.275: E/AndroidRuntime(1655): at com.example.dreamhome.LoginFormActivity.onCreate(LoginFormActivity.java:45)
02-27 14:14:55.275: E/AndroidRuntime(1655): at android.app.Activity.performCreate(Activity.java:5231)
02-27 14:14:55.275: E/AndroidRuntime(1655): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
02-27 14:14:55.275: E/AndroidRuntime(1655): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)
02-27 14:14:55.275: E/AndroidRuntime(1655): ... 11 more
02-27 14:15:03.295: I/Process(1655): Sending signal. PID: 1655 SIG: 9
HomeActivity.java
public class HomeActivity extends Activity
{
Button search_property, log_in, exit;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
search_property=(Button)findViewById(R.id.homebutton1);
log_in=(Button)findViewById(R.id.homebutton2);
exit=(Button)findViewById(R.id.homebutton3);
search_property.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
Intent main1=new Intent(HomeActivity.this,EndUserSearchPropertyActivity.class);
startActivity(main1);
}
});
log_in.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
Intent main2 = new Intent(HomeActivity.this,LoginFormActivity.class);
startActivity(main2);
}
});
exit.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
finish();
System.exit(0);
}
});
// Show the Up button in the action bar.
setupActionBar();
}
/**
* Set up the {#link android.app.ActionBar}.
*/
private void setupActionBar()
{
getActionBar().setDisplayHomeAsUpEnabled(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.home, 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 LoginFormActivity.java
public class LoginFormActivity extends Activity
{
private Button sign_up = null;
private Button btnSignIn = null;
LoginDataBaseAdapter loginDataBaseAdapter = null;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login_form);
// create a instance of SQLite Database
loginDataBaseAdapter=new LoginDataBaseAdapter(this);
loginDataBaseAdapter=loginDataBaseAdapter.open();
final Dialog dialog = new Dialog(LoginFormActivity.this);
// get the Refferences of views
final EditText editTextUserName=(EditText)dialog.findViewById(R.id.login_editText1);
final EditText editTextPassword=(EditText)dialog.findViewById(R.id.login_editText2);
btnSignIn = (Button)dialog.findViewById(R.id.login_form_button1);
// Set On ClickListener
btnSignIn.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
// get The User name and Password
String userName = editTextUserName.getText().toString();
String password = editTextPassword.getText().toString();
// fetch the Password form database for respective user name
String storedPassword=loginDataBaseAdapter.getSinlgeEntry(userName);
// check if the Stored password matches with Password entered by user
if(password.equals(storedPassword))
{
Toast.makeText(LoginFormActivity.this, "Congrats: Login Successfull", Toast.LENGTH_LONG).show();
dialog.dismiss();
}
else
{
Toast.makeText(LoginFormActivity.this, "User Name or Password does not match", Toast.LENGTH_LONG).show();
}
}
});
dialog.show();
}
#Override
protected void onDestroy()
{
super.onDestroy();
// Close The Database
loginDataBaseAdapter.close();
sign_up = (Button)findViewById(R.id.login_form_button2);
sign_up.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
Intent main2=new Intent(LoginFormActivity.this,SignupFormActivity.class);
startActivity(main2);
}
});
// Show the Up button in the action bar.
setupActionBar();
}
/**
* Set up the {#link android.app.ActionBar}.
*/
private void setupActionBar()
{
getActionBar().setDisplayHomeAsUpEnabled(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.login_form, 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);
}
}
final Dialog dialog = new Dialog(LoginFormActivity.this);
Merely instantiating a dialog doesn't inflate/create its layout. All the subsequent dialog.findViewById() calls return null and you'll get the NPE here attempting to call a method on null reference:
btnSignIn = (Button)dialog.findViewById(R.id.login_form_button1);
// Set On ClickListener
btnSignIn.setOnClickListener(new View.OnClickListener()
You probably need to set a content view to your dialog with all the views you want to reference. The views are available with findViewById() after the dialog is showing.

Show GridView images from JSON Android

I have a problem when displaying images from JSON to GridView could help me .
GalleryActivity.java
public class GalleryActivity extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.gallery_layout);
Intent i = getIntent();
String tempid = i.getStringExtra("tempid");
GridView gridView = (GridView) findViewById(R.id.grid_view);
gridView.setAdapter(new ImageAdapter(this,tempid));
gridView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v,
int position, long id) {
}
});
}
}
ImageAdapter.java
public class ImageAdapter extends BaseAdapter {
private Context mContext;
public String[] mThumbIds;
private static String KEY_SUCCESS = "success";
private static String KEY_IMAGES = "images";
private static String KEY_IMAGE = "url_img";
// Constructor
public ImageAdapter(Context c,String tempID){
mContext = c;
final DealerFunctions dealerFunction = new DealerFunctions();
JSONObject json = dealerFunction.getImages(tempID);
try {
if (json.getString(KEY_SUCCESS) != null) {
String res = json.getString(KEY_SUCCESS);
if (Integer.parseInt(res) == 1) {
JSONArray imagesFields = json
.getJSONArray(KEY_IMAGES);
for (int i = 0; i < imagesFields.length(); i++) {
JSONObject x = imagesFields.getJSONObject(i);
mThumbIds[i] = x.getString(KEY_IMAGE);
}
} else {
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
public int getCount() {
return mThumbIds.length;
}
public Object getItem(int position) {
return mThumbIds[position];
}
public long getItemId(int position) {
return 0;
}
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView;
if (convertView==null){
imageView = new ImageView(mContext);
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setLayoutParams(new GridView.LayoutParams(70, 70));
}else{
imageView = (ImageView) convertView;
}
imageView.setBackgroundDrawable(Drawable.createFromPath(mThumbIds[position]));
return imageView;
}
}
Don't Work...
when I run the application, closes immediately assume that the problem comes in imageView.setBackgroundDrawable (Drawable.createFromPath (mThumbIds [position]));
I need your help guys
Logcat Errors as follows.
03-27 10:50:12.658: D/AndroidRuntime(1782): Shutting down VM
03-27 10:50:12.658: W/dalvikvm(1782): threadid=1: thread exiting with uncaught exception (group=0x4001d800)
03-27 10:50:12.678: E/AndroidRuntime(1782): FATAL EXCEPTION: main
03-27 10:50:12.678: E/AndroidRuntime(1782): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.montalvo.dealer/com.montalvo.dealer.GalleryActivity}: java.lang.NullPointerException
03-27 10:50:12.678: E/AndroidRuntime(1782): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2663)
03-27 10:50:12.678: E/AndroidRuntime(1782): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
03-27 10:50:12.678: E/AndroidRuntime(1782): at android.app.ActivityThread.access$2300(ActivityThread.java:125)
03-27 10:50:12.678: E/AndroidRuntime(1782): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
03-27 10:50:12.678: E/AndroidRuntime(1782): at android.os.Handler.dispatchMessage(Handler.java:99)
03-27 10:50:12.678: E/AndroidRuntime(1782): at android.os.Looper.loop(Looper.java:123)
03-27 10:50:12.678: E/AndroidRuntime(1782): at android.app.ActivityThread.main(ActivityThread.java:4627)
03-27 10:50:12.678: E/AndroidRuntime(1782): at java.lang.reflect.Method.invokeNative(Native Method)
03-27 10:50:12.678: E/AndroidRuntime(1782): at java.lang.reflect.Method.invoke(Method.java:521)
03-27 10:50:12.678: E/AndroidRuntime(1782): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
03-27 10:50:12.678: E/AndroidRuntime(1782): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
03-27 10:50:12.678: E/AndroidRuntime(1782): at dalvik.system.NativeStart.main(Native Method)
03-27 10:50:12.678: E/AndroidRuntime(1782): Caused by: java.lang.NullPointerException
03-27 10:50:12.678: E/AndroidRuntime(1782): at com.montalvo.dealer.ImageAdapter.<init>(ImageAdapter.java:57)
03-27 10:50:12.678: E/AndroidRuntime(1782): at com.montalvo.dealer.GalleryActivity.onCreate(GalleryActivity.java:25)
03-27 10:50:12.678: E/AndroidRuntime(1782): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
03-27 10:50:12.678: E/AndroidRuntime(1782): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627)
03-27 10:50:12.678: E/AndroidRuntime(1782): ... 11 more
03-27 10:50:15.501: I/Process(1782): Sending signal. PID: 1782 SIG: 9
You are mixing things up here, use this
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView;
imageView = new ImageView(mContext);
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setLayoutParams(new GridView.LayoutParams(70, 70));
imageView.setBackgroundDrawable(Drawable.createFromPath(mThumbIds[position]));
return imageView;
}
The pattern you have used is that of the ViewHolder but you are not creating any views. If you do want to use the ViewHolder model then,
first create an xml with an ImageView.
Create a ViewHolder class in your ImageAdapter with an ImageView.
In the getView() method, inflate the xml.
create the viewholder for the case of convertview == null
set the viewholder as the TAG of the convertview.
in the else condtion, assign the previously created viewholder to the convertview.

Custom list starting new activity?

I have built a customized list item to replace the android's simple list item by inflating each list item. The customized list is working and it consists of an image view and a text view.
My problem is, when I try to launch a new activity after a list item is clicked nothing happens even the app wont crash. So, is there a way to launch an activity using list view???
public class activityone extends ListActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activitylayout);
setListAdapter(new MyAdapter(this, android.R.layout.simple_list_item_1, R.id.textView1,
getResources().getStringArray(R.array.names)));
}
public void onListItemClick(ListView l, View v, int position,
long id) {
// TODO Auto-generated method stub
super.onListItemClick(l, v, position, id);
Object o = this.getListAdapter().getItem(position);
if(getSelectedItemPosition() == 0){
Intent intent = new Intent(activityone.this,no1.class);
startActivity(intent);
}
.
.
.
.
}
private class MyAdapter extends ArrayAdapter<String>{
public MyAdapter(Context context, int resource, int textViewResourceId,
String[] strings) {
super(context, textViewResourceId, strings);
// TODO Auto-generated constructor stub
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View row = inflater.inflate(R.layout.list_item, parent, false);
String[] items = getResources().getStringArray(R.array.names);
ImageView iv = (ImageView) row.findViewById(R.id.imageView1);
TextView tv = (TextView) row.findViewById(R.id.textView1);
tv.setText(items[position]);
if(items[position].equals("john")){
iv.setImageResource(R.drawable.john);
}
.
.
.
.
return row;
}
}
}
And here is the no1 class
public class no1 extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.name_profile);
CharSequence t1 = "Name: john";
CharSequence t2 = "Age: 31";
CharSequence t3 = "Nationality: Saudi";
CharSequence t4 = "Number: 765646454";
ImageView iv = (ImageView) findViewById(R.drawable.imageView1);
TextView tv1 = (TextView) findViewById(R.id.textView1);
TextView tv2 = (TextView) findViewById(R.id.textView2);
TextView tv3 = (TextView) findViewById(R.id.textView3);
TextView tv4 = (TextView) findViewById(R.id.textView4);
iv.setImageResource(R.drawable.john);
tv1.setText(t1);
tv2.setText(t2);
tv3.setText(t3);
tv4.setText(t4);
}
}
And yes my activities are added to the manifest xml file.
Thanks for your help.
#Vineet Shukla I don't know how to do this i placed a break point but I couldn't debug i am new to eclipse environment could you explain more please
#Divyesh
I edited the code and the app now crashes when i press a list item here is the Logcat trace
09-17 10:10:57.686: ERROR/AndroidRuntime(365): FATAL EXCEPTION: main
09-17 10:10:57.686: ERROR/AndroidRuntime(365): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.abc.act/com.abc.act.no1}: java.lang.NullPointerException
09-17 10:10:57.686: ERROR/AndroidRuntime(365): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2663)
09-17 10:10:57.686: ERROR/AndroidRuntime(365): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
09-17 10:10:57.686: ERROR/AndroidRuntime(365): at android.app.ActivityThread.access$2300(ActivityThread.java:125)
09-17 10:10:57.686: ERROR/AndroidRuntime(365): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
09-17 10:10:57.686: ERROR/AndroidRuntime(365): at android.os.Handler.dispatchMessage(Handler.java:99)
09-17 10:10:57.686: ERROR/AndroidRuntime(365): at android.os.Looper.loop(Looper.java:123)
09-17 10:10:57.686: ERROR/AndroidRuntime(365): at android.app.ActivityThread.main(ActivityThread.java:4627)
09-17 10:10:57.686: ERROR/AndroidRuntime(365): at java.lang.reflect.Method.invokeNative(Native Method)
09-17 10:10:57.686: ERROR/AndroidRuntime(365): at java.lang.reflect.Method.invoke(Method.java:521)
09-17 10:10:57.686: ERROR/AndroidRuntime(365): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
09-17 10:10:57.686: ERROR/AndroidRuntime(365): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
09-17 10:10:57.686: ERROR/AndroidRuntime(365): at dalvik.system.NativeStart.main(Native Method)
09-17 10:10:57.686: ERROR/AndroidRuntime(365): Caused by: java.lang.NullPointerException
09-17 10:10:57.686: ERROR/AndroidRuntime(365): at com.abc.act.no1.onCreate(no1.java:31)
09-17 10:10:57.686: ERROR/AndroidRuntime(365): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
09-17 10:10:57.686: ERROR/AndroidRuntime(365): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627)
09-17 10:10:57.686: ERROR/AndroidRuntime(365): ... 11 more
You're not effectively using this API, you should switch to SimpleAdapter because handles more complex List Item layouts and data bindings. Instead of creating intractable branch statements you need to use the underlying data of the list effectively.

Categories

Resources