Volley:java.lang.OutOfMemoryError:分配失败

时间:2017-01-25 01:57:11

标签: java android json listview android-volley

我想从服务器收集信息使用凌空然后显示在listview.before列表视图上的这个diplay信息,想先在arraylist中添加。但问题是,我收到此错误如下。希望你们帮我解决这个问题。

错误

I/art: Alloc sticky concurrent mark sweep GC freed 52(1664B) AllocSpace objects, 0(0B) LOS objects, 0% free, 176MB/177MB, paused 99.553ms total 643.892ms
I/art: WaitForGcToComplete blocked for 323.775ms for cause HeapTrim
W/art: Suspending all threads took: 1.769s
W/art: Suspending all threads took: 98.745ms
W/art: Suspending all threads took: 6.468ms
I/art: Clamp target GC heap from 192MB to 192MB
I/art: Alloc partial concurrent mark sweep GC freed 18(576B) AllocSpace objects, 0(0B) LOS objects, 7% free, 176MB/192MB, paused 101.770ms total 2.222s
W/art: Suspending all threads took: 2.108s
W/art: Suspending all threads took: 98.256ms
W/art: Suspending all threads took: 5.957ms
I/art: Clamp target GC heap from 192MB to 192MB
I/art: Alloc concurrent mark sweep GC freed 18(12KB) AllocSpace objects, 0(0B) LOS objects, 7% free, 176MB/192MB, paused 100.852ms total 2.235s
I/art: Forcing collection of SoftReferences for 29MB allocation
W/art: Suspending all threads took: 2.106s
W/art: Suspending all threads took: 98.003ms
W/art: Suspending all threads took: 5.912ms
I/art: Clamp target GC heap from 192MB to 192MB
I/art: Alloc concurrent mark sweep GC freed 36(1216B) AllocSpace objects, 0(0B) LOS objects, 7% free, 176MB/192MB, paused 100.742ms total 2.231s
W/art: Suspending all threads took: 100.382ms
I/art: Clamp target GC heap from 192MB to 192MB
E/art: Throwing OutOfMemoryError "Failed to allocate a 30536292 byte allocation with 15988544 free bytes and 15MB until OOM"
I/art: WaitForGcToComplete blocked for 1.703s for cause HeapTrim
W/art: Suspending all threads took: 6.631ms
D/AndroidRuntime: Shutting down VM
W/art: Suspending all threads took: 6.846ms
E/AndroidRuntime: FATAL EXCEPTION: main
                  Process: net.simplifiedcoding.androidtablayout, PID: 12350
                  java.lang.OutOfMemoryError: Failed to allocate a 30536292 byte allocation with 15988544 free bytes and 15MB until OOM
                      at java.util.ArrayList.add(ArrayList.java:118)
                      at net.simplifiedcoding.androidtablayout.volley.NotisBackgroundTask$1.onResponse(NotisBackgroundTask.java:50)
                      at net.simplifiedcoding.androidtablayout.volley.NotisBackgroundTask$1.onResponse(NotisBackgroundTask.java:39)
                      at com.android.volley.toolbox.JsonRequest.deliverResponse(JsonRequest.java:72)
                      at com.android.volley.ExecutorDelivery$ResponseDeliveryRunnable.run(ExecutorDelivery.java:99)
                      at android.os.Handler.handleCallback(Handler.java:739)
                      at android.os.Handler.dispatchMessage(Handler.java:95)
                      at android.os.Looper.loop(Looper.java:135)
                      at android.app.ActivityThread.main(ActivityThread.java:5268)
                      at java.lang.reflect.Method.invoke(Native Method)
                      at java.lang.reflect.Method.invoke(Method.java:372)
                      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:902)
                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:697)

MainActivity.java

package net.simplifiedcoding.androidtablayout;

import android.os.Bundle;
import android.os.StrictMode;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;

public class MainActivity extends AppCompatActivity implements TabLayout.OnTabSelectedListener{

    private TabLayout tabLayout;
    private ViewPager viewPager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //initialize toolbar
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        toolbar.setNavigationIcon(R.mipmap.ic_launcher_round);
        setSupportActionBar(toolbar);

        //initialize tablayout
        tabLayout = (TabLayout) findViewById(R.id.tabLayout);

        //create create two tab and add those tab inside tablayout object (content not included,just tab)
        tabLayout.addTab(tabLayout.newTab().setText("Aduan"));
        tabLayout.addTab(tabLayout.newTab().setText("Semakan"));
        tabLayout.addTab(tabLayout.newTab().setText("Notis"));
        tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);

        //initialize viewpager
        viewPager = (ViewPager) findViewById(R.id.pager);


        //initialize fragment pager adapter
        Pager adapter = new Pager(getSupportFragmentManager(), tabLayout.getTabCount(),MainActivity.this);
        viewPager.setAdapter(adapter);
        tabLayout.setOnTabSelectedListener(this);

    }

    @Override
    public void onTabSelected(TabLayout.Tab tab) {
        viewPager.setCurrentItem(tab.getPosition());
    }

    @Override
    public void onTabUnselected(TabLayout.Tab tab) {

    }

    @Override
    public void onTabReselected(TabLayout.Tab tab) {

    }
}

Pager.java

package net.simplifiedcoding.androidtablayout;

import android.content.Context;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;

import net.simplifiedcoding.androidtablayout.volley.NotisBackgroundTask;

public class Pager extends FragmentStatePagerAdapter {

    Context context;
    int tabCount;


    public Pager(FragmentManager fm, int tabCount,Context context) {
        super(fm);
        //set context
        this.context = context;
        //get count of the tab layout
        this.tabCount= tabCount;
    }

    //if user either tab,the tab position will send to this method and open new tab content inside fragment.
    @Override
    public Fragment getItem(int position) {
        switch (position) {
            case 0:
                Tab1 tab1 = new Tab1();

                return tab1;
            case 1:
                Tab2 tab2 = new Tab2();
                return tab2;
            case 2:
                NotisBackgroundTask notisBackgroundTask = new NotisBackgroundTask(context);
                Tab3 tab3 = new Tab3();
                return tab3;
            default:
                return null;
        }
    }
    //get total number of tab
    @Override
    public int getCount() {
        return tabCount;
    }
}

NotisBackgroundTask.java

package net.simplifiedcoding.androidtablayout.volley;

import android.content.Context;
import android.util.Log;
import android.widget.EditText;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;

import net.simplifiedcoding.androidtablayout.MainActivity;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;

/**
 * Created by User on 1/24/2017.
 */

public class NotisBackgroundTask {
    Context context;
    ArrayList<Notis> arrayList = new ArrayList<>();


    public NotisBackgroundTask(Context context){
        this.context = context;
        callNotisFromServer();

    }

    public void callNotisFromServer(){

        // make json request (volley)

        JsonArrayRequest jsonArrayRequest = new JsonArrayRequest(Request.Method.POST, "http://192.168.1.106/android/notis_android.php", (String) null, new Response.Listener<JSONArray>() {
            @Override
            public void onResponse(JSONArray response) {
                //get all information from json
                int count = 0;
                while(count <response.length()){
                    try{
                        JSONObject jsonObject = response.getJSONObject(count);
                        Notis notis = new Notis(jsonObject.getString("time_mula"),
                                jsonObject.getString("time_tamat"),jsonObject.getString("dt_mula"),jsonObject.getString("dt_tamat"),
                                jsonObject.getString("notis_sebab"),jsonObject.getString("notis_lokasi"));
                        arrayList.add(notis);
                    }catch (JSONException e){
                        Log.d("message:",e.getMessage());
                    }
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Log.d("Volley ERROR:",error.getMessage());
            }
        });
        MySingleton.getmInstances(context).addRequestQueue(jsonArrayRequest);


    }

}

Tab3.java

package net.simplifiedcoding.androidtablayout;

import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import net.simplifiedcoding.androidtablayout.volley.Notis;
import net.simplifiedcoding.androidtablayout.volley.NotisBackgroundTask;

/**
 * Created by User on 1/24/2017.
 */

public class Tab3 extends Fragment{


    @Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    // return super.onCreateView(inflater, container, savedInstanceState);

        View view = inflater.inflate(R.layout.tab3,null);



        return view;
}
}

1 个答案:

答案 0 :(得分:0)

看起来你有一个无限循环,你永远不会在下面的块中增加计数:

int count = 0;
while(count <response.length()){
    try{
        JSONObject jsonObject = response.getJSONObject(count);
        Notis notis = new Notis(jsonObject.getString("time_mula"),
                jsonObject.getString("time_tamat"),jsonObject.getString("dt_mula"),jsonObject.getString("dt_tamat"),
                jsonObject.getString("notis_sebab"),jsonObject.getString("notis_lokasi"));
        arrayList.add(notis);
    }catch (JSONException e){
        Log.d("message:",e.getMessage());
    }
}

要解决此问题,请尝试在添加项目后添加count++;