Android Outofmemoryerror? - java

I have these codes for my android activity. But it gave me java.lang.outofmemoryerror: java.lang.string[] of length 2131492864 ecxeeds the VM limit. I want to know if there is something wrong with my codes or is it my String.xml contains too much items? Or there's too many pictures? I have around 120 150x150 image that is around 20kb each. If possible I would like to know how can i solve this issue. Thanks in advance.
public class ChampionInfo extends FragmentActivity {
GridView gridtable;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_champion_info);
gridtable = (GridView) findViewById(R.id.gridtable);
gridtable.setAdapter(new GridAdapter(this));
}
public class GridAdapter extends BaseAdapter {
private Context mContext;
String[] list = new String[R.array.championlist];
int[] champImage = getImage();
public int[] getImage() {
int[] tempImage = new int[list.length];
for (int i = 0; i > list.length; i++) {
tempImage[i] = getResources().getIdentifier(list[i],
"drawable", getPackageName());
}
return tempImage;
}
// Constructor
public GridAdapter(Context c) {
mContext = c;
}
public int getCount() {
return champImage.length;
}
public Object getItem(int position) {
return null;
}
public long getItemId(int position) {
return 0;
}
// create a new ImageView for each item referenced by the Adapter
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView;
if (convertView == null) {
imageView = new ImageView(mContext);
imageView.setLayoutParams(new GridView.LayoutParams(85, 85));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setPadding(8, 8, 8, 8);
} else {
imageView = (ImageView) convertView;
}
imageView.setImageResource(champImage[position]);
return imageView;
}
// Keep all Images in array
}
}
These are the error that shows on the catlog:
09-26 06:09:38.869: E/AndroidRuntime(2653): FATAL EXCEPTION: main
09-26 06:09:38.869: E/AndroidRuntime(2653): Process: com.example.loldb, PID: 2653
09-26 06:09:38.869: E/AndroidRuntime(2653): java.lang.OutOfMemoryError: java.lang.String[] of length 2131492864 exceeds the VM limit
09-26 06:09:38.869: E/AndroidRuntime(2653): at com.example.loldb.ChampionInfo$GridAdapter.(ChampionInfo.java:50)
09-26 06:09:38.869: E/AndroidRuntime(2653): at com.example.loldb.ChampionInfo.onCreate(ChampionInfo.java:44)
09-26 06:09:38.869: E/AndroidRuntime(2653): at android.app.Activity.performCreate(Activity.java:5231)
09-26 06:09:38.869: E/AndroidRuntime(2653): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
09-26 06:09:38.869: E/AndroidRuntime(2653): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2159)
09-26 06:09:38.869: E/AndroidRuntime(2653): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2245)
09-26 06:09:38.869: E/AndroidRuntime(2653): at android.app.ActivityThread.access$800(ActivityThread.java:135)
09-26 06:09:38.869: E/AndroidRuntime(2653): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
09-26 06:09:38.869: E/AndroidRuntime(2653): at android.os.Handler.dispatchMessage(Handler.java:102)
09-26 06:09:38.869: E/AndroidRuntime(2653): at android.os.Looper.loop(Looper.java:136)
09-26 06:09:38.869: E/AndroidRuntime(2653): at android.app.ActivityThread.main(ActivityThread.java:5017)
09-26 06:09:38.869: E/AndroidRuntime(2653): at java.lang.reflect.Method.invokeNative(Native Method)
09-26 06:09:38.869: E/AndroidRuntime(2653): at java.lang.reflect.Method.invoke(Method.java:515)
09-26 06:09:38.869: E/AndroidRuntime(2653): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
09-26 06:09:38.869: E/AndroidRuntime(2653): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
09-26 06:09:38.869: E/AndroidRuntime(2653): at dalvik.system.NativeStart.main(Native Method)

This line doesn't make much sense:
String[] list = new String[R.array.championlist];
R.array.championlist is an integer that points to the what I assume is a string array resource. You can load that string array with Resources.getStringArray(int).
String[] list = resources.getStringArray(R.array.championlist);

Related

Application not working on Android Kitkat

I'm creating my own application. I tested it on Android Lollipop and Marshmallow - everything works great. But whenever I try Android Kitkat, an error occurs. Here's error log:
E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.newproject/com.example.newproject.Progi}: java.lang.ClassCastException: java.lang.Object[] cannot be cast to java.math.BigDecimal[][]
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2059)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
at android.app.ActivityThread.access$600(ActivityThread.java:130)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4745)
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:786)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.ClassCastException: java.lang.Object[] cannot be cast to java.math.BigDecimal[][]
at com.example.newproject.Progi.onCreate(Progi.java:62)
at android.app.Activity.performCreate(Activity.java:5008)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1079)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2023)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084) 
at android.app.ActivityThread.access$600(ActivityThread.java:130) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195) 
at android.os.Handler.dispatchMessage(Handler.java:99) 
at android.os.Looper.loop(Looper.java:137) 
at android.app.ActivityThread.main(ActivityThread.java:4745) 
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:786) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553) 
at dalvik.system.NativeStart.main(Native Method) 
It looks like problem is on line 62 in "progi" class, but - as for me - everything is OK especially that on newer Android versions it works great.
public class Progi extends AppCompatActivity {
Intent intent;
Bundle liczby;
Bundle doble;
BigDecimal tablica [][];
BigDecimal punkty = new BigDecimal(-1);
#Override
public boolean onPrepareOptionsMenu(Menu menu)
{
android.content.SharedPreferences shared = android.preference.PreferenceManager.getDefaultSharedPreferences(this);
boolean warunek = shared.getBoolean("serial", false);
android.view.MenuItem menuitem = menu.getItem(0);
if(warunek)
{
menuitem.setTitle("Oceny pojedynczo");
}
else menuitem.setTitle("Oceny seryjnie");
return true;
}
public boolean onCreateOptionsMenu(Menu menu) {
android.view.MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.firstmenu, menu);
return true;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layoutprogi);
Toolbar myToolbar = (Toolbar) findViewById(R.id.my_toolbar);
setSupportActionBar(myToolbar);
getSupportActionBar().setTitle("Progi punktowe");
intent = getIntent();
liczby = intent.getBundleExtra("liczby");
doble = intent.getBundleExtra("doble");
tablica = (BigDecimal[][]) doble.getSerializable("doble"); //here is line 62
if(intent.hasExtra("max")) {
Bundle a = intent.getBundleExtra("max");
punkty = (BigDecimal) a.getSerializable("max");
}
przejscie(true);
if(punkty.compareTo(new BigDecimal(-3))==0)
{
procenty(findViewById(android.R.id.content));
}
else if(punkty.compareTo(new BigDecimal(-1))!=0)
{
liczymy(findViewById(android.R.id.content));
}}
And in case someone asking "what 'tablica' gets from intent?":
BigDecimal[][] tablica = new BigDecimal[16][3];
//here i get data from file and put in inside "tablica"
Bundle doble = new Bundle();
doble.putSerializable("doble", tablica);
Intent intent = new Intent(Starter.this, MyActivity.class);
intent.putExtra("doble", doble);
startActivity(intent);
Any idea what's wrong?
Try switching your array implementation (BigDecimal[] []) to ArrayList.
If you want to pass an Array through an intent on Android versions
prior to Android 5.0.1 (maybe some older versions work aswell, but up
to Android 4.3 it is NOT working) You'll have to work around it. You
could do this by converting your Array to an ArrayList.
Then you would be casting it something like this:
(ArrayList<ArrayList<BigDecimal>>) doble.getSerializable("doble");
Related SO answer

Recyclerview java.lang.IndexOutOfBoundException

When I scroll down too fast and click on whatever item I land on I get this following error then the app crashes: java.lang.IndexOutOfBoundsException: Inconsistency detected. Invalid view holder adapter positionViewHolder{440a7260 position=15 id=-1, oldPos=14, pLpos:14 scrap tmpDetached no parent} I have read that it's a (known) bug in the recyclerview. Does someone have a way to bypass it? Maybe restrict scroll to let all the JSON data to load properly in recyclerview
I use the following method to send my JSON request
private void sendJsonRequest(){
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, urlUpcoming, (String) null, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
//Toast.makeText(getActivity(), response.toString(), Toast.LENGTH_LONG).show();
gamesList.addAll(parseJsonResponse(response));
adapterUpcoming.notifyDataSetChanged();
adapterUpcoming.setData(gamesList);
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//error getting data
}
});
//add the request
mRequestQueue.add(request);
}
The parseJsonResponse returns an array list, this is where the magic happens(fetching the data from the api)
private ArrayList<Game> parseJsonResponse(JSONObject response) {
final ArrayList<Game> games = new ArrayList<>();
//{fetching data with volley} code omitted
return games;
}
OnCreateView
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_upcoming, container, false);
mRecyclerView = (RecyclerView) view.findViewById(R.id.upcomingGamesList);
mLayoutManager = new LinearLayoutManager(getActivity());
mRecyclerView.setLayoutManager(mLayoutManager);
adapterUpcoming = new AdapterUpcoming(getActivity());
mRecyclerView.setAdapter(adapterUpcoming);
urlUpcoming = MyApplication.getUrl(); //the url from which I'm fetching my data
sendJsonRequest();
return view;
Error (The error is the same but values different):
E/AndroidRuntime? FATAL EXCEPTION: main
java.lang.IndexOutOfBoundsException: Inconsistency detected. Invalid view holder adapter positionViewHolder{52ea27c0 position=5 id=-1, oldPos=4, pLpos:4 scrap tmpDetached no parent}
at android.support.v7.widget.RecyclerView$Recycler.validateViewHolderForOffsetPosition(RecyclerView.java:3229)
at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:3359)
at android.support.v7.widget.RecyclerView$Recycler.getViewForPosition(RecyclerView.java:3340)
at android.support.v7.widget.LinearLayoutManager$LayoutState.next(LinearLayoutManager.java:1810)
at android.support.v7.widget.LinearLayoutManager.layoutChunk(LinearLayoutManager.java:1306)
at android.support.v7.widget.LinearLayoutManager.fill(LinearLayoutManager.java:1269)
at android.support.v7.widget.LinearLayoutManager.onLayoutChildren(LinearLayoutManager.java:523)
at android.support.v7.widget.RecyclerView.dispatchLayout(RecyclerView.java:1942)
at android.support.v7.widget.RecyclerView.onLayout(RecyclerView.java:2237)
at android.view.View.layout(View.java:14289)
at android.view.ViewGroup.layout(ViewGroup.java:4562)
at android.widget.FrameLayout.onLayout(FrameLayout.java:448)
at android.view.View.layout(View.java:14289)
at android.view.ViewGroup.layout(ViewGroup.java:4562)
at android.widget.FrameLayout.onLayout(FrameLayout.java:448)
at android.view.View.layout(View.java:14289)
at android.view.ViewGroup.layout(ViewGroup.java:4562)
at android.support.v4.view.ViewPager.onLayout(ViewPager.java:1594)
at android.view.View.layout(View.java:14289)
at android.view.ViewGroup.layout(ViewGroup.java:4562)
at android.widget.FrameLayout.onLayout(FrameLayout.java:448)
at android.view.View.layout(View.java:14289)
at android.view.ViewGroup.layout(ViewGroup.java:4562)
at android.support.v7.internal.widget.ActionBarOverlayLayout.onLayout(ActionBarOverlayLayout.java:502)
at android.view.View.layout(View.java:14289)
at android.view.ViewGroup.layout(ViewGroup.java:4562)
at android.widget.FrameLayout.onLayout(FrameLayout.java:448)
at android.view.View.layout(View.java:14289)
at android.view.ViewGroup.layout(ViewGroup.java:4562)
at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1671)
at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1525)
at android.widget.LinearLayout.onLayout(LinearLayout.java:1434)
at android.view.View.layout(View.java:14289)
at android.view.ViewGroup.layout(ViewGroup.java:4562)
at android.widget.FrameLayout.onLayout(FrameLayout.java:448)
at android.view.View.layout(View.java:14289)
at android.view.ViewGroup.layout(ViewGroup.java:4562)
at android.view.ViewRootImpl.performLayout(ViewRootImpl.java:1976)
at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1730)
at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1004)
at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:5481)
at android.view.Choreographer$CallbackRecord.run(Choreographer.java:749)
at android.view.Choreographer.doCallbacks(Choreographer.java:562)
at android.view.Choreographer.doFrame(Choreographer.java:532)
at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:735)
at android.os.Handler.handleCallback(Handler.java:730)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5103)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
Thanks!!
Please always post the code that you need help with. Also make sure that this code is concise and well commented. However an IndexOutOfBounds exception means that somewhere you are trying to look at a string or an array. And looking at A negative number or a number too high. But it says position 15 so it is going past the end of the array. Trying adding a check statement if(oldPosition+1

Fetch data from database SQLite with fragment

This is my fragment activity i am getting error while accessing database my code is :-
public class Test extends Fragment {
View view;
private Cursor c;
private final String DB = "Canary";
private SQLiteDatabase db2;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
view = inflater.inflate(R.layout.test, container, false);
Button b = (Button) view.findViewById(R.id.test_button);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getActivity(),"Listning",Toast.LENGTH_LONG).show();
}
});
db2 = SQLiteDatabase.openOrCreateDatabase(DB, null);
Log.d("Lee", "working her1");
c=db2.rawQuery("SELECT * FROM business_master", null);
Log.d("Lee", "working here2");
c.moveToFirst();
String id=c.getString(c.getColumnIndex("id"));
Log.d("id", "" + id);
String email=c.getString(c.getColumnIndex("email"));
Log.d("email", email);
String password=c.getString(c.getColumnIndex("password"));
db2.close();
return view;
} }
The error i am getting :-
01-20 11:35:57.168 17081-17081/com.purplefront.canary E/AndroidRuntime﹕ FATAL EXCEPTION: main
Process: com.purplefront.canary, PID: 17081
android.database.sqlite.SQLiteCantOpenDatabaseException: unknown error (code 14): Could not open database
at android.database.sqlite.SQLiteConnection.nativeOpen(Native Method)
at android.database.sqlite.SQLiteConnection.open(SQLiteConnection.java:209)
at android.database.sqlite.SQLiteConnection.open(SQLiteConnection.java:193)
at android.database.sqlite.SQLiteConnectionPool.openConnectionLocked(SQLiteConnectionPool.java:463)
at android.database.sqlite.SQLiteConnectionPool.open(SQLiteConnectionPool.java:185)
at android.database.sqlite.SQLiteConnectionPool.open(SQLiteConnectionPool.java:177)
at android.database.sqlite.SQLiteDatabase.openInner(SQLiteDatabase.java:804)
at android.database.sqlite.SQLiteDatabase.open(SQLiteDatabase.java:789)
at android.database.sqlite.SQLiteDatabase.openDatabase(SQLiteDatabase.java:694)
at android.database.sqlite.SQLiteDatabase.openOrCreateDatabase(SQLiteDatabase.java:709)
at com.purplefront.canary.Test.onCreateView(Test.java:36)
at android.app.Fragment.performCreateView(Fragment.java:1700)
at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:890)
at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1062)
at android.app.BackStackRecord.run(BackStackRecord.java:684)
at android.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1447)
at android.app.FragmentManagerImpl$1.run(FragmentManager.java:443)
at android.os.Handler.handleCallback(Handler.java:733)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:136)
at android.app.ActivityThread.main(ActivityThread.java:5086)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:515)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:785)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:601)
at dalvik.system.NativeStart.main(Native Method)
If i remove the database access it will work fine as expected but i need database access in fragment only.
Any help would be appreciated.

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

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.

Categories

Resources