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

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.

Related

java android Choreographer: Skipped 271 frames

My application when I click a buttons is freezing and in anroid monit I see :
03-22 13:01:33.490 25636-26150/com.smok.maps D/dalvikvm: GC_FOR_ALLOC freed 2468K, 11% free 29508K/32996K, paused 65ms, total 65ms
03-22 13:01:36.914 25636-26150/com.smok.maps D/dalvikvm: GC_FOR_ALLOC freed 3957K, 17% free 28675K/34324K, paused 54ms, total 54ms
03-22 13:01:37.744 25636-25636/com.smok.maps I/Choreographer: Skipped 271 frames! The application may be doing too much work on its main thread.
03-22 13:01:39.907 25636-26150/com.smok.maps D/dalvikvm: GC_FOR_ALLOC freed 3903K, 19% free 27910K/34324K, paused 42ms, total 42ms
This is an action what I do :
btUnselectAll.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
// for (RowBean aRowBean_data : rowBeen) {
// aRowBean_data.setSelected(false);
// }
for (RowBean rowBean : Adapter.data) {
rowBean.setSelected(false);
}
adapter.notifyDataSetChanged();
for (ObjectDefExtends objectDefExtends : Singleton.getInstance().getListaODE()) {
objectDefExtends.visible = false;
editor.putInt(objectDefExtends.id.toString(), 0);
editor.apply();
}
}
});

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.

Update and remove GridView items at runtime

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);

Android Unable to instantiate Activity(Using File Inputs)

Info: I am a decent java developer, I know my way around it pretty well I think, so I decided to give android a chance, and it hasn't been the smoothest road for me. I mess up very often. Anyway to my question if anyone would be so kind to help me out with this error I would very much appreciate it! Thank you.
Main Class
package dev.shaw.MyShoppingPlanner;
import java.io.File;
import android.support.v7.app.ActionBarActivity;
import android.support.v4.app.Fragment;
import android.text.InputType;
import android.app.ActionBar;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.FragmentTransaction;
import android.app.ActionBar.Tab;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
public class MainActivity extends ActionBarActivity {
private String m_Text = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final ActionBar actionbar = getActionBar();
actionbar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
if(firstTime()){
GenerateNeededFiles();
}
else{
//do nothing
}
ActionBar.TabListener tablistener = new ActionBar.TabListener() {
#Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) {
// TODO Auto-generated method stub
}
#Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
switch(tab.getText().toString()){
case "Lists":
openLists();
break;
case "Store":
openStore();
case "Home":
openTab();
}
}
private void openTab() {
}
private void openStore() {
View v = new View(MainActivity.this);
v.setVisibility(1);
v.clearFocus();
v.bringToFront();
}
private void openLists() {
Intent intent = new Intent(MainActivity.this,List_Activity.class);
startActivity(intent);
}
#Override
public void onTabReselected(Tab tab, FragmentTransaction ft) {
// do nothing
}
};
actionbar.addTab(actionbar.newTab().setText("Home").setTabListener(tablistener));
actionbar.addTab(actionbar.newTab().setText("Store").setTabListener(tablistener));
actionbar.addTab(actionbar.newTab().setText("Lists").setTabListener(tablistener));
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}
}
private boolean firstTime() {
File storelist = new File(this.getFilesDir() + "\\StoreList.txt");
File listnames = new File(this.getFilesDir() + "\\ListNames.txt");
if(storelist.exists() && listnames.exists()){
return false;
}
else{
return true;
}
}
private void GenerateNeededFiles() {
Intent intent = new Intent(MainActivity.this,Install_Activity.class);
startActivity(intent);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()){
case R.id.action_search:
openSearch();
return true;
case R.id.action_settings:
openSettings();
default:
return super.onOptionsItemSelected(item);
}
}
private void openSettings() {
}
private void openSearch() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Search");
// Set up the input
final EditText input = new EditText(this);
// Specify the type of input expected; this, for example, sets the input as a password, and will mask the text
input.setInputType(InputType.TYPE_CLASS_TEXT);
builder.setView(input);
// Set up the buttons
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
m_Text = input.getText().toString();
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
builder.show();
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container,
false);
return rootView;
}
}
}
The Class that gets an error when called
package dev.shaw.MyShoppingPlanner;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import android.app.ListActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
public class List_Activity extends ListActivity {
String ListNames[] = getListNames();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setListAdapter(new ArrayAdapter<String>(this, R.layout.singleitem , ListNames));
}
protected void onListItemClick(ListView lv, View v, int pos,long id){
this.onListItemClick(lv, v, pos, id);
ShoppingList list = new ShoppingList(ListNames[pos]);
try {
setListAdapter(new ArrayAdapter<String>(this, R.layout.singleitem, list.toArray(list.getFile())));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private String[] getListNames() {
File file = new File(this.getFilesDir() + "\\listnames.txt");
FileInputStream fis = null;
try {
fis = new FileInputStream(file);
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
InputStreamReader is = new InputStreamReader(fis);
BufferedReader br = new BufferedReader(is);
String line;
String names[] = new String[100];
int i = 0;
try {
while(true){
line = br.readLine();
if(line == null){
break;
}
else{
try{
names[i] = line;
}
catch(NullPointerException e){
e.printStackTrace();
}
i++;
}
}
} catch (IOException e) {
e.printStackTrace();
}
try {
br.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return names;
}
}
and here is the printStack
03-23 04:58:16.523: D/dalvikvm(3710): GC_FOR_ALLOC freed 151K, 18% free 2770K/3356K, paused 2ms, total 7ms
03-23 04:58:16.531: D/dalvikvm(3710): GC_FOR_ALLOC freed 100K, 19% free 2988K/3680K, paused 1ms, total 4ms
03-23 04:58:16.535: I/dalvikvm-heap(3710): Grow heap (frag case) to 4.414MB for 1127532-byte allocation
03-23 04:58:16.539: D/dalvikvm(3710): GC_FOR_ALLOC freed <1K, 15% free 4089K/4784K, paused 3ms, total 3ms
03-23 04:58:16.555: D/dalvikvm(3710): GC_FOR_ALLOC freed <1K, 15% free 4089K/4784K, paused 1ms, total 1ms
03-23 04:58:16.587: I/dalvikvm-heap(3710): Grow heap (frag case) to 6.833MB for 2536932-byte allocation
03-23 04:58:16.599: D/dalvikvm(3710): GC_FOR_ALLOC freed 0K, 10% free 6567K/7264K, paused 2ms, total 2ms
03-23 04:58:16.615: D/HardwareRenderer(3710): Profiling hardware renderer
03-23 04:58:16.647: D/libEGL(3710): loaded /system/lib/egl/libEGL_genymotion.so
03-23 04:58:16.651: D/(3710): HostConnection::get() New Host Connection established 0xb85b3b40, tid 3710
03-23 04:58:16.655: D/libEGL(3710): loaded /system/lib/egl/libGLESv1_CM_genymotion.so
03-23 04:58:16.655: D/libEGL(3710): loaded /system/lib/egl/libGLESv2_genymotion.so
03-23 04:58:16.711: W/EGL_genymotion(3710): eglSurfaceAttrib not implemented
03-23 04:58:16.711: E/OpenGLRenderer(3710): Getting MAX_TEXTURE_SIZE from GradienCache
03-23 04:58:16.723: E/OpenGLRenderer(3710): Getting MAX_TEXTURE_SIZE from Caches::initConstraints()
03-23 04:58:16.723: D/OpenGLRenderer(3710): Enabling debug mode 0
03-23 04:58:18.015: D/AndroidRuntime(3710): Shutting down VM
03-23 04:58:18.015: W/dalvikvm(3710): threadid=1: thread exiting with uncaught exception (group=0xa4bae648)
03-23 04:58:18.015: E/AndroidRuntime(3710): FATAL EXCEPTION: main
03-23 04:58:18.015: E/AndroidRuntime(3710): java.lang.RuntimeException: Unable to instantiate activity ComponentInfo{dev.shaw.MyShoppingPlanner/dev.shaw.MyShoppingPlanner.List_Activity}: java.lang.NullPointerException
03-23 04:58:18.015: E/AndroidRuntime(3710): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2137)
03-23 04:58:18.015: E/AndroidRuntime(3710): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
03-23 04:58:18.015: E/AndroidRuntime(3710): at android.app.ActivityThread.access$600(ActivityThread.java:141)
03-23 04:58:18.015: E/AndroidRuntime(3710): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
03-23 04:58:18.015: E/AndroidRuntime(3710): at android.os.Handler.dispatchMessage(Handler.java:99)
03-23 04:58:18.015: E/AndroidRuntime(3710): at android.os.Looper.loop(Looper.java:137)
03-23 04:58:18.015: E/AndroidRuntime(3710): at android.app.ActivityThread.main(ActivityThread.java:5103)
03-23 04:58:18.015: E/AndroidRuntime(3710): at java.lang.reflect.Method.invokeNative(Native Method)
03-23 04:58:18.015: E/AndroidRuntime(3710): at java.lang.reflect.Method.invoke(Method.java:525)
03-23 04:58:18.015: E/AndroidRuntime(3710): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
03-23 04:58:18.015: E/AndroidRuntime(3710): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
03-23 04:58:18.015: E/AndroidRuntime(3710): at dalvik.system.NativeStart.main(Native Method)
03-23 04:58:18.015: E/AndroidRuntime(3710): Caused by: java.lang.NullPointerException
03-23 04:58:18.015: E/AndroidRuntime(3710): at android.content.ContextWrapper.getFilesDir(ContextWrapper.java:199)
03-23 04:58:18.015: E/AndroidRuntime(3710): at dev.shaw.MyShoppingPlanner.List_Activity.getListNames(List_Activity.java:38)
03-23 04:58:18.015: E/AndroidRuntime(3710): at dev.shaw.MyShoppingPlanner.List_Activity.<init>(List_Activity.java:16)
03-23 04:58:18.015: E/AndroidRuntime(3710): at java.lang.Class.newInstanceImpl(Native Method)
03-23 04:58:18.015: E/AndroidRuntime(3710): at java.lang.Class.newInstance(Class.java:1130)
03-23 04:58:18.015: E/AndroidRuntime(3710): at android.app.Instrumentation.newActivity(Instrumentation.java:1061)
03-23 04:58:18.015: E/AndroidRuntime(3710): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2128)
03-23 04:58:18.015: E/AndroidRuntime(3710): ... 11 more

Thread OutOfMemoryError, Force Close

everytime I run this code I get a force close, which i don't understand. Im new to Android development, can anybody help? I'm really thankful for any tips from you guys. So far i just understood, that the memory space is running out, but how can I prevent the memory from running low?
My code:
Boolean start = true;
HttpPost httppost;
StringBuffer buffer;
HttpResponse response;
HttpClient httpclient;
List<NameValuePair> nameValuePair;
TextView txtEntries;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_screen);
txtEntries = (TextView)findViewById(R.id.txtEntries);
SharedPreferences p = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
String User = p.getString("User", "");
String Password = p.getString("Password", "");
txtEntries.setText("user:" + User + "Passwort:" + Password);
getEntries.start();
start = 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.activity_main_screen, menu);
return true;
}
Thread getEntries = new Thread() {
public void run() {
//while(!login_thread.isInterrupted()) {
while (getEntries.isInterrupted() == false) {
try {
sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (start) {
//Code for login+Action from saved text
SharedPreferences p = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
String User = p.getString("User", "");
String Password = p.getString("Password", "");
login("Entries", User, Password);
}
}
//while (start == true){
//login(box_User.getText().toString(), box_Password.getText().toString());
//}
//}
}
};
//implement Handler
Handler handler = new Handler() {
#Override
public void handleMessage(Message msg) {
getEntries.interrupt();
txtEntries = (TextView)findViewById(R.id.txtEntries);
txtEntries.setText("Handler");
Bundle bundle = msg.getData();
Boolean Connection = bundle.getBoolean("Connection");
String response = bundle.getString("Entries");
if (Connection) {
// Toast.makeText(getBaseContext(), "Connection", 5000).show();
if (response != "") {
//Code which shows all entries
Toast.makeText(getBaseContext(), "Response", 5000).show();
txtEntries.setText(response);
} else {
txtEntries.setText("Empty");
}
}else {
txtEntries.setText("No connection");
getEntries.interrupt();
}
}
};
// getData method
private void login(String Action, String User, String Password) {
// TODO Auto-generated method stub
start = false;
Message msg = handler.obtainMessage();
Bundle bundle = new Bundle();
httppost = new HttpPost("http://10.0.2.2/KHG/api/check-login.php");
HttpParams httpParameters = new BasicHttpParams();
// Set the timeout in milliseconds until a connection is established.
// The default value is zero, that means the timeout is not used.
int timeoutConnection = 15000;
HttpConnectionParams.setConnectionTimeout(httpParameters, timeoutConnection);
// Set the default socket timeout (SO_TIMEOUT)
// in milliseconds which is the timeout for waiting for data.
int timeoutSocket = 15000;
HttpConnectionParams.setSoTimeout(httpParameters, timeoutSocket);
httpclient = new DefaultHttpClient(httpParameters);
nameValuePair = new ArrayList<NameValuePair>(1);
nameValuePair.add(new BasicNameValuePair("User", User));
nameValuePair.add(new BasicNameValuePair("Password", Password));
nameValuePair.add(new BasicNameValuePair("Action", Action));
try {
httppost.setEntity(new UrlEncodedFormEntity(nameValuePair));
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
e.printStackTrace();
bundle.putBoolean("Connection", false);
bundle.putString("Entries", "");
msg.setData(bundle);
handler.sendMessage(msg);
}
try {
response = httpclient.execute(httppost);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
bundle.putBoolean("Connection", false);
bundle.putString("Entries", "");
msg.setData(bundle);
handler.sendMessage(msg);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
bundle.putBoolean("Connection", false);
bundle.putString("Entries", "");
msg.setData(bundle);
handler.sendMessage(msg);
}
ResponseHandler<String> responseHandler = new BasicResponseHandler();
String response;
try {
// Toast.makeText(getBaseContext(), "test", Toast.LENGTH_LONG).show();
response = httpclient.execute(httppost, responseHandler);
SharedPreferences p = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
p.edit().putString("Data", response).commit();
bundle.putBoolean("Connection", true);
bundle.putString("Entries", "ok");
msg.setData(bundle);
handler.sendMessage(msg);
}
catch (Exception e) {
e.printStackTrace();
bundle.putBoolean("Connection", false);
bundle.putString("Entries", "");
msg.setData(bundle);
handler.sendMessage(msg);
// Toast.makeText(getBaseContext(), "exception", Toast.LENGTH_LONG).show();
}
}
}
And my log:
03-23 16:32:22.683: D/dalvikvm(741): GC_FOR_ALLOC freed 135K, 4% free 8821K/9159K, paused 60ms
03-23 16:32:22.822: W/SingleClientConnManager(741): Invalid use of SingleClientConnManager: connection still allocated.
03-23 16:32:22.822: W/SingleClientConnManager(741): Make sure to release the connection before allocating another one.
03-23 16:32:23.012: W/System.err(741): java.lang.InterruptedException
03-23 16:32:23.012: W/System.err(741): at java.lang.VMThread.sleep(Native Method)
03-23 16:32:23.012: W/System.err(741): at java.lang.Thread.sleep(Thread.java:1214)
03-23 16:32:23.022: W/System.err(741): at java.lang.Thread.sleep(Thread.java:1196)
03-23 16:32:23.022: W/System.err(741): at com.shr.khg.MainActivity$2.run(MainActivity.java:109)
03-23 16:32:25.342: D/dalvikvm(741): GC_FOR_ALLOC freed 80K, 3% free 9148K/9415K, paused 60ms
03-23 16:32:25.442: W/SingleClientConnManager(741): Invalid use of SingleClientConnManager: connection still allocated.
03-23 16:32:25.442: W/SingleClientConnManager(741): Make sure to release the connection before allocating another one.
03-23 16:32:25.822: D/dalvikvm(741): GC_CONCURRENT freed 40K, 3% free 9558K/9799K, paused 21ms+9ms
03-23 16:32:25.942: D/dalvikvm(741): GC_FOR_ALLOC freed 123K, 5% free 9629K/10119K, paused 68ms
03-23 16:32:25.952: I/dalvikvm-heap(741): Grow heap (frag case) to 9.770MB for 262160-byte allocation
03-23 16:32:26.092: D/dalvikvm(741): GC_FOR_ALLOC freed 0K, 6% free 9885K/10439K, paused 69ms
03-23 16:32:26.262: D/dalvikvm(741): GC_FOR_ALLOC freed 132K, 7% free 9757K/10439K, paused 55ms
03-23 16:32:26.262: I/dalvikvm-heap(741): Grow heap (frag case) to 10.145MB for 524304-byte allocation
03-23 16:32:26.412: D/dalvikvm(741): GC_FOR_ALLOC freed 0K, 7% free 10269K/11015K, paused 57ms
03-23 16:32:26.682: D/dalvikvm(741): GC_CONCURRENT freed 262K, 10% free 10014K/11015K, paused 13ms+3ms
03-23 16:32:26.852: D/dalvikvm(741): GC_FOR_ALLOC freed 1K, 10% free 10013K/11015K, paused 71ms
03-23 16:32:26.872: I/dalvikvm-heap(741): Grow heap (frag case) to 10.895MB for 1048592-byte allocation
03-23 16:32:27.042: D/dalvikvm(741): GC_FOR_ALLOC freed 0K, 9% free 11037K/12103K, paused 63ms
03-23 16:32:27.302: D/dalvikvm(741): GC_CONCURRENT freed 518K, 14% free 10526K/12103K, paused 26ms+5ms
03-23 16:32:28.212: D/dalvikvm(741): GC_FOR_ALLOC freed 9K, 14% free 10525K/12103K, paused 102ms
03-23 16:32:28.242: I/dalvikvm-heap(741): Grow heap (frag case) to 12.395MB for 2097168-byte allocation
03-23 16:32:28.562: D/dalvikvm(741): GC_FOR_ALLOC freed 0K, 12% free 12573K/14215K, paused 89ms
03-23 16:32:28.912: D/dalvikvm(741): GC_CONCURRENT freed 1030K, 19% free 11550K/14215K, paused 18ms+23ms
03-23 16:32:31.352: D/dalvikvm(741): GC_FOR_ALLOC freed 26K, 19% free 11549K/14215K, paused 79ms
03-23 16:32:31.412: I/dalvikvm-heap(741): Grow heap (frag case) to 15.395MB for 4194320-byte allocation
03-23 16:32:31.723: D/dalvikvm(741): GC_FOR_ALLOC freed 0K, 15% free 15645K/18375K, paused 87ms
03-23 16:32:31.932: D/dalvikvm(741): GC_CONCURRENT freed 2054K, 27% free 13598K/18375K, paused 19ms+4ms
03-23 16:32:38.491: D/dalvikvm(741): GC_FOR_ALLOC freed 59K, 27% free 13597K/18375K, paused 67ms
03-23 16:32:38.621: I/dalvikvm-heap(741): Grow heap (frag case) to 21.395MB for 8388624-byte allocation
03-23 16:32:39.031: D/dalvikvm(741): GC_FOR_ALLOC freed 0K, 19% free 21789K/26631K, paused 98ms
03-23 16:32:39.341: D/dalvikvm(741): GC_CONCURRENT freed 4101K, 34% free 17694K/26631K, paused 17ms+11ms
03-23 16:32:52.093: D/dalvikvm(741): GC_FOR_ALLOC freed 124K, 34% free 17693K/26631K, paused 79ms
03-23 16:32:52.093: I/dalvikvm-heap(741): Forcing collection of SoftReferences for 16777232-byte allocation
03-23 16:32:52.242: D/dalvikvm(741): GC_BEFORE_OOM freed 8K, 34% free 17685K/26631K, paused 142ms
03-23 16:32:52.242: E/dalvikvm-heap(741): Out of memory on a 16777232-byte allocation.
03-23 16:32:52.242: I/dalvikvm(741): "Thread-12" prio=5 tid=10 RUNNABLE
03-23 16:32:52.251: I/dalvikvm(741): | group="main" sCount=0 dsCount=0 obj=0x408b9158 self=0x16f860
03-23 16:32:52.251: I/dalvikvm(741): | sysTid=752 nice=0 sched=0/0 cgrp=default handle=1669016
03-23 16:32:52.251: I/dalvikvm(741): | schedstat=( 5912317448 1115812658 845 ) utm=511 stm=80 core=0
03-23 16:32:52.251: I/dalvikvm(741): at org.apache.http.util.CharArrayBuffer.expand(CharArrayBuffer.java:~59)
03-23 16:32:52.251: I/dalvikvm(741): at org.apache.http.util.CharArrayBuffer.append(CharArrayBuffer.java:77)
03-23 16:32:52.251: I/dalvikvm(741): at org.apache.http.util.EntityUtils.toString(EntityUtils.java:136)
03-23 16:32:52.251: I/dalvikvm(741): at org.apache.http.util.EntityUtils.toString(EntityUtils.java:146)
03-23 16:32:52.251: I/dalvikvm(741): at org.apache.http.impl.client.BasicResponseHandler.handleResponse(BasicResponseHandler.java:76)
03-23 16:32:52.251: I/dalvikvm(741): at org.apache.http.impl.client.BasicResponseHandler.handleResponse(BasicResponseHandler.java:59)
03-23 16:32:52.251: I/dalvikvm(741): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:657)
03-23 16:32:52.262: I/dalvikvm(741): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:627)
03-23 16:32:52.262: I/dalvikvm(741): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:616)
03-23 16:32:52.262: I/dalvikvm(741): at com.shr.khg.MainScreen.login(MainScreen.java:170)
03-23 16:32:52.262: I/dalvikvm(741): at com.shr.khg.MainScreen.access$0(MainScreen.java:118)
03-23 16:32:52.262: I/dalvikvm(741): at com.shr.khg.MainScreen$1.run(MainScreen.java:79)
03-23 16:32:55.752: W/dalvikvm(741): threadid=10: thread exiting with uncaught exception (group=0x40014760)
03-23 16:32:55.772: E/AndroidRuntime(741): FATAL EXCEPTION: Thread-12
03-23 16:32:55.772: E/AndroidRuntime(741): java.lang.OutOfMemoryError
03-23 16:32:55.772: E/AndroidRuntime(741): at org.apache.http.util.CharArrayBuffer.expand(CharArrayBuffer.java:59)
03-23 16:32:55.772: E/AndroidRuntime(741): at org.apache.http.util.CharArrayBuffer.append(CharArrayBuffer.java:77)
03-23 16:32:55.772: E/AndroidRuntime(741): at org.apache.http.util.EntityUtils.toString(EntityUtils.java:136)
03-23 16:32:55.772: E/AndroidRuntime(741): at org.apache.http.util.EntityUtils.toString(EntityUtils.java:146)
03-23 16:32:55.772: E/AndroidRuntime(741): at org.apache.http.impl.client.BasicResponseHandler.handleResponse(BasicResponseHandler.java:76)
03-23 16:32:55.772: E/AndroidRuntime(741): at org.apache.http.impl.client.BasicResponseHandler.handleResponse(BasicResponseHandler.java:59)
03-23 16:32:55.772: E/AndroidRuntime(741): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:657)
03-23 16:32:55.772: E/AndroidRuntime(741): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:627)
03-23 16:32:55.772: E/AndroidRuntime(741): at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:616)
03-23 16:32:55.772: E/AndroidRuntime(741): at com.shr.khg.MainScreen.login(MainScreen.java:170)
03-23 16:32:55.772: E/AndroidRuntime(741): at com.shr.khg.MainScreen.access$0(MainScreen.java:118)
03-23 16:32:55.772: E/AndroidRuntime(741): at com.shr.khg.MainScreen$1.run(MainScreen.java:79)
03-23 16:32:59.012: I/Process(741): Sending signal. PID: 741 SIG: 9
Thanks!
It is a very known problem.... First of all you ought to implement your http request in AsyncTask.... Then you won't see this error never Again!!!!!!!!!!!!!

Categories

Resources