I recently added a splash screen to my Android application to mask the loading of a JSON file, but my app crashes after finishing parsing. I've commented out and uncommented out code until I found the problematic segment, but I'm not sure why it isn't working.
The code works if I comment out the for loop from this code segment.
From MagazinePagesActivity.java:
public void loadItems() {
for (Item item : SplashActivity.downloadedItems) {
Post post = (Post) item;
for (String tag : post.tags) {
if (tag.equals(this.tag)) {
// loader.loadImage(magazine.imageURL, new
// SimpleImageLoadingListener());
Bundle bundle = new Bundle();
bundle.putString("title", post.title);
bundle.putString("article", post.article);
bundle.putString("imageURL", post.imageURL);
MagazineFragment cover = new MagazineFragment();
cover.setArguments(bundle);
coverAdapter.addNewItem(cover);
}
}
}
setContentView(vp);
}
At first, I thought it was because SplashActivity.downloadedItems wasn't properly defined, but it looks fine to me:
From SplashActivity.java:
public static ArrayList<Item> downloadedItems = new ArrayList<Item>();
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash);
new RetreiveJSONTask() {
protected void onPostExecute(String JSON)
{
Log.d("SplashActivity", "Beginning parsingJSON" );
downloadedItems = parseJSON ( JSON );
Log.d("SplashActivity", "Finished parsingJSON" );
Log.d("SplashActivity", "" + SplashActivity.downloadedItems.isEmpty());
Intent i = new Intent(SplashActivity.this, MagazinePagesActivity.class);
startActivity(i);
// Closes the splash screen
finish();
}
}.execute(sourceURL());
}
From LogCat:
10-16 19:23:12.602: D/AndroidRuntime(828): Shutting down VM
10-16 19:23:12.602: W/dalvikvm(828): threadid=1: thread exiting with uncaught exception (group=0x41465700)
10-16 19:23:12.632: E/AndroidRuntime(828): FATAL EXCEPTION: main
10-16 19:23:12.632: E/AndroidRuntime(828): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.bruinfootball/com.dailybruin.bruinframework.channels.StoryListActivity}: java.lang.NullPointerException
10-16 19:23:12.632: E/AndroidRuntime(828): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2211)
10-16 19:23:12.632: E/AndroidRuntime(828): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
10-16 19:23:12.632: E/AndroidRuntime(828): at android.app.ActivityThread.access$600(ActivityThread.java:141)
10-16 19:23:12.632: E/AndroidRuntime(828): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
10-16 19:23:12.632: E/AndroidRuntime(828): at android.os.Handler.dispatchMessage(Handler.java:99)
10-16 19:23:12.632: E/AndroidRuntime(828): at android.os.Looper.loop(Looper.java:137)
10-16 19:23:12.632: E/AndroidRuntime(828): at android.app.ActivityThread.main(ActivityThread.java:5103)
10-16 19:23:12.632: E/AndroidRuntime(828): at java.lang.reflect.Method.invokeNative(Native Method)
10-16 19:23:12.632: E/AndroidRuntime(828): at java.lang.reflect.Method.invoke(Method.java:525)
10-16 19:23:12.632: E/AndroidRuntime(828): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
10-16 19:23:12.632: E/AndroidRuntime(828): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
10-16 19:23:12.632: E/AndroidRuntime(828): at dalvik.system.NativeStart.main(Native Method)
10-16 19:23:12.632: E/AndroidRuntime(828): Caused by: java.lang.NullPointerException
10-16 19:23:12.632: E/AndroidRuntime(828): at com.dailybruin.bruinframework.channels.StoryListActivity.loadItems(StoryListActivity.java:27)
10-16 19:23:12.632: E/AndroidRuntime(828): at com.dailybruin.bruinframework.channels.JSONItemsActivity.onCreate(JSONItemsActivity.java:20)
10-16 19:23:12.632: E/AndroidRuntime(828): at com.dailybruin.bruinframework.channels.StoryItemsActivity.onCreate(StoryItemsActivity.java:18)
10-16 19:23:12.632: E/AndroidRuntime(828): at com.dailybruin.bruinframework.channels.StoryListActivity.onCreate(StoryListActivity.java:18)
10-16 19:23:12.632: E/AndroidRuntime(828): at android.app.Activity.performCreate(Activity.java:5133)
10-16 19:23:12.632: E/AndroidRuntime(828): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
10-16 19:23:12.632: E/AndroidRuntime(828): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2175)
10-16 19:23:12.632: E/AndroidRuntime(828): ... 11 more
Not sure if it helps, but both SplashActivity and MagazinePagesActivity extend JSONItemsActivity, separately.
Thanks in advance for any help! I'm fairly new to Android, so please bear with me.
Edit: That's odd, the debug statement I put to check if the ArrayList is empty returns true, but another debug statement within parseJSON shows that things are being added. My parseJSON method:
public ArrayList<Item> parseJSON(String jsonString) {
ArrayList<Item> magazines = new ArrayList<Item>();
JSONArray jArray;
try {
jArray = new JSONArray(jsonString);
JSONObject jObject;
JSONObject image;
String img;
String title;
String subtitle;
int commentCount;
String content;
String date;
String ID;
String slug;
JSONArray array;
String[] tags;
for (int i = 0; i < jArray.length(); i++) {
jObject = jArray.getJSONObject(i);
img = jObject.getString("tall_image_url");
if (img.equals(""))
img = jObject.getString("image_url");
if (img.equals("") && !jObject.isNull("poster_image")) {
image = jObject.getJSONObject("poster_image");
img = image.getString("name");
}
title = jObject.getString("title");
subtitle = jObject.getString("subtitle");
commentCount = jObject.getInt("comment_count");
content = jObject.getString("content_html");
date = jObject.getString("creation_date");
ID = jObject.getString("id");
slug = jObject.getString("slug");
array = jObject.getJSONArray("tags_list");
tags = new String[array.length()];
for (int j = 0; j < array.length(); j++) {
tags[j] = array.getString(j);
}
for (String tag : tags) {
if (tag.equals(this.tag))
{
Post additive = new Post(img, title, subtitle,
commentCount, content, date, ID, slug, tags);
magazines.add(additive);
Log.d("SplashActivity", additive.toString());
}
}
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return magazines;
}
StoryListActivity line 27:
public void loadItems() {
(findViewById(R.id.progress_bar)).setVisibility(View.GONE);
getSupportFragmentManager().beginTransaction()
.replace(R.id.loading, new StoryListFragment()).commit();
}
StoryItemsActivity (MagazinePagesActivity and StoryListActivity extend this class; this class extends JSONItemsActivity, which SplashActivity also extends):
package com.dailybruin.bruinframework.channels;
import java.util.ArrayList;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.dailybruin.bruinframework.R;
import com.dailybruin.bruinframework.base.BaseActivity;
import com.dailybruin.bruinframework.base.URLBuilder;
import android.os.Bundle;
public abstract class StoryItemsActivity extends JSONItemsActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
public String sourceURL()
{
return URLBuilder.getPostsURL(getString(R.string.slug));
}
public ArrayList<Item> parseJSON(String jsonString) {
// Using pre-downloaded and parsed JSON
return SplashActivity.downloadedItems;
}
}
Check this part of the code. Line number 27. That is null and hence causing NPE.
Caused by: java.lang.NullPointerException
10-16 19:23:12.632: E/AndroidRuntime(828): at com.dailybruin.bruinframework.channels.StoryListActivity.loadItems(StoryListActivity.java:27)
Related
When i am trying to display the contacts in card view when i click on Button it shows fatal exception error it doesnot display cardview anyone can solve this programming with brillliance and another error is it show only one cardview when i click on again the app will be strucked?
Showcontacts.java
public class ShowContacts extends Activity
{
private SQLiteDatabase db;
DbOperations doo;
private List<Contacts> contactsList;
private RecyclerView rv;
private Cursor c;
String names,email,address;
int phone;
String read_query = "select * from"+ ContactsTask.ContactsEntry.TABLE_NAME;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.recycle_layout);
doo = new DbOperations(this);
openDatabase();
rv = (RecyclerView)findViewById(R.id.recyclerview);
initializeData();
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
rv.setLayoutManager(linearLayoutManager);
rv.setHasFixedSize(true);
ContactAdapter cc = new ContactAdapter(contactsList);
rv.setAdapter(cc);
}
public void initializeData() {
contactsList = new ArrayList<>();
c = db.rawQuery(read_query,null);
c.moveToFirst();
while (!c.isLast())
{
names = c.getString(0);
phone = c.getInt(1);
email = c.getString(2);
address = c.getString(3);
contactsList.add(new Contacts(names,phone,email,address));
}
c.isLast();
names = c.getString(0);
phone = c.getInt(1);
email = c.getString(2);
address = c.getString(3);
contactsList.add(new Contacts(names,phone,email,address));
}
private void openDatabase() {
db = openOrCreateDatabase("contactDB", Context.MODE_PRIVATE,null);
}
}
Logacat error
06-28 08:57:43.107 568-568/com.example.anilkumar.contactstask E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.anilkumar.contactstask/com.example.anilkumar.contactstask.ShowContacts}: android.database.sqlite.SQLiteException: near "fromcontacts": syntax error: , while compiling: select * fromcontacts
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1956)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1981)
at android.app.ActivityThread.access$600(ActivityThread.java:123)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1147)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4424)
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:784)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
at dalvik.system.NativeStart.main(Native Method)
Caused by: android.database.sqlite.SQLiteException: near "fromcontacts": syntax error: , while compiling: select * fromcontacts
at android.database.sqlite.SQLiteCompiledSql.native_compile(Native Method)
at android.database.sqlite.SQLiteCompiledSql.<init>(SQLiteCompiledSql.java:68)
at android.database.sqlite.SQLiteProgram.compileSql(SQLiteProgram.java:143)
at android.database.sqlite.SQLiteProgram.compileAndbindAllArgs(SQLiteProgram.java:361)
at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:127)
at android.database.sqlite.SQLiteProgram.<init>(SQLiteProgram.java:94)
at android.database.sqlite.SQLiteQuery.<init>(SQLiteQuery.java:53)
at android.database.sqlite.SQLiteDirectCursorDriver.query(SQLiteDirectCursorDriver.java:47)
at android.database.sqlite.SQLiteDatabase.rawQueryWithFactory(SQLiteDatabase.java:1564)
at android.database.sqlite.SQLiteDatabase.rawQuery(SQLiteDatabase.java:1538)
at com.example.anilkumar.contactstask.ShowContacts.initializeData(ShowContacts.java:44)
at com.example.anilkumar.contactstask.ShowContacts.onCreate(ShowContacts.java:34)
at android.app.Activity.performCreate(Activity.java:4466)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1920)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1981)
at android.app.ActivityThread.access$600(ActivityThread.java:123)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1147)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4424)
at java.lang.reflect.Method.invokeNative(Native Method)
Another logact error
06-28 13:14:40.552 11252-11261/com.example.anilkumar.contactstask E/SQLiteDatabase: close() was never explicitly called on database '/data/data/com.example.anilkumar.contactstask/databases/contactDB'
android.database.sqlite.DatabaseObjectNotClosedException: Application did not close the cursor or database object that was opened here
at android.database.sqlite.SQLiteDatabase.<init>(SQLiteDatabase.java:1943)
at android.database.sqlite.SQLiteDatabase.openDatabase(SQLiteDatabase.java:1007)
at android.database.sqlite.SQLiteDatabase.openDatabase(SQLiteDatabase.java:986)
at android.database.sqlite.SQLiteDatabase.openDatabase(SQLiteDatabase.java:962)
at android.database.sqlite.SQLiteDatabase.openOrCreateDatabase(SQLiteDatabase.java:1043)
at android.database.sqlite.SQLiteDatabase.openOrCreateDatabase(SQLiteDatabase.java:1036)
at android.app.ContextImpl.openOrCreateDatabase(ContextImpl.java:761)
at android.content.ContextWrapper.openOrCreateDatabase(ContextWrapper.java:215)
at com.example.anilkumar.contactstask.ShowContacts.openDatabase(ShowContacts.java:66)
at com.example.anilkumar.contactstask.ShowContacts.onCreate(ShowContacts.java:33)
at android.app.Activity.performCreate(Activity.java:4466)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1920)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1981)
at android.app.ActivityThread.access$600(ActivityThread.java:123)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1147)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4424)
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:784)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
Just update
String read_query = "select * from"+ ContactsTask.ContactsEntry.TABLE_NAME;
to
String read_query = "select * from "+ ContactsTask.ContactsEntry.TABLE_NAME;
Always close cursor. update your initializeData method
public void initializeData() {
try {
contactsList = new ArrayList<>();
try{
c = db.rawQuery(read_query,null);
c.moveToFirst();
while (!c.isLast())
{
names = c.getString(0);
phone = c.getInt(1);
email = c.getString(2);
address = c.getString(3);
contactsList.add(new Contacts(names,phone,email,address));
}
c.isLast();
names = c.getString(0);
phone = c.getInt(1);
email = c.getString(2);
address = c.getString(3);
contactsList.add(new Contacts(names,phone,email,address));
} catch (Exception e) {
// exception handling
} finally {
if(c != null){
c.close();
}
}
}
So here my problem i'm setting the onitemclicklistener on listview1 and making it that if an item already exist on the order list, then the quantity will increment, but my problem is my program keep crashing
Here's my code
MainActivity.java
public class MainActivity extends Activity {
Database helper;
ListView lv,lv2;
ArrayAdapter<PostItemList> adapter;
ArrayAdapter<PostInventory> adapterInventory;
ArrayAdapter<PostOrder> adapterOrder;
ArrayList<PostItemList> list;
ArrayList<PostInventory> listInventory;
ArrayList<PostOrder> listorder;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
helper = new Database(MainActivity.this);
lv = (ListView)findViewById(R.id.itemList);
lv2 = (ListView)findViewById(R.id.orderList);
list = helper.getAllData();
adapter = new PostAdapterItemList(MainActivity.this,list);
lv.setAdapter(adapter);
listorder = new ArrayList<PostOrder>();
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1,final int pos,
long arg3) {
// TODO Auto-generated method stub
PostItemList getData = list.get(pos);
String parseData = getData.toStringOrder();
String name[] = parseData.split(",");
int itemQuantity = Integer.parseInt(name[1]);
double itemPrice = Double.parseDouble(name[2]);
if (itemQuantity == 0){
String output = name[0] + " is out of stock.";
Toast.makeText(getBaseContext(), output, Toast.LENGTH_LONG).show();
} else {
itemQuantity = itemQuantity - 1;
String newQuantity = String.valueOf(itemQuantity);
helper.updateQuantity(name[0], newQuantity);
list.clear();
list = helper.getAllData();
adapter = new PostAdapterItemList(MainActivity.this, list);
lv.setAdapter(adapter);
int checker = 0;
if (listorder.isEmpty()){
listorder.add(new PostOrder(name[0], "1", name[2]));
adapterOrder = new PostAdapterOrder(MainActivity.this,listorder);
lv2.setAdapter(adapterOrder);
} else if (listorder.size()>0){
for(PostOrder order : listorder){
if (name[0].contentEquals(order.getItemName())){
String quantity = order.getItemQuantity();
order.setItemQuantity(String.valueOf((Integer.parseInt(quantity))+1));
adapterOrder.notifyDataSetChanged();
} else {
checker = 1;
}
}
}
if (checker==1){
listorder.add(new PostOrder(name[0], "1", name[1]));
adapterOrder = new PostAdapterOrder(MainActivity.this, listorder);
lv2.setAdapter(adapterOrder);
}
}
}
});
}
Logcat
10-11 00:05:13.190: D/dalvikvm(854): GC_FOR_ALLOC freed 57K, 5% free 3034K/3176K, paused 32ms, total 33ms
10-11 00:05:13.190: I/dalvikvm-heap(854): Grow heap (frag case) to 3.646MB for 635812-byte allocation
10-11 00:05:13.290: D/dalvikvm(854): GC_FOR_ALLOC freed 0K, 4% free 3655K/3800K, paused 22ms, total 22ms
10-11 00:05:13.870: I/Choreographer(854): Skipped 73 frames! The application may be doing too much work on its main thread.
10-11 00:05:13.950: D/gralloc_goldfish(854): Emulator without GPU emulation detected.
10-11 00:05:14.230: I/Choreographer(854): Skipped 37 frames! The application may be doing too much work on its main thread.
10-11 00:05:20.070: D/AndroidRuntime(854): Shutting down VM
10-11 00:05:20.070: W/dalvikvm(854): threadid=1: thread exiting with uncaught exception (group=0xb3a67ba8)
10-11 00:05:20.080: E/AndroidRuntime(854): FATAL EXCEPTION: main
10-11 00:05:20.080: E/AndroidRuntime(854): Process: com.example.posv3, PID: 854
10-11 00:05:20.080: E/AndroidRuntime(854): java.util.ConcurrentModificationException
10-11 00:05:20.080: E/AndroidRuntime(854): at java.util.ArrayList$ArrayListIterator.next(ArrayList.java:573)
10-11 00:05:20.080: E/AndroidRuntime(854): at com.example.posv3.MainActivity$1.onItemClick(MainActivity.java:71)
10-11 00:05:20.080: E/AndroidRuntime(854): at android.widget.AdapterView.performItemClick(AdapterView.java:299)
10-11 00:05:20.080: E/AndroidRuntime(854): at android.widget.AbsListView.performItemClick(AbsListView.java:1113)
10-11 00:05:20.080: E/AndroidRuntime(854): at android.widget.AbsListView$PerformClick.run(AbsListView.java:2904)
10-11 00:05:20.080: E/AndroidRuntime(854): at android.widget.AbsListView$3.run(AbsListView.java:3638)
10-11 00:05:20.080: E/AndroidRuntime(854): at android.os.Handler.handleCallback(Handler.java:733)
10-11 00:05:20.080: E/AndroidRuntime(854): at android.os.Handler.dispatchMessage(Handler.java:95)
10-11 00:05:20.080: E/AndroidRuntime(854): at android.os.Looper.loop(Looper.java:136)
10-11 00:05:20.080: E/AndroidRuntime(854): at android.app.ActivityThread.main(ActivityThread.java:5017)
10-11 00:05:20.080: E/AndroidRuntime(854): at java.lang.reflect.Method.invokeNative(Native Method)
10-11 00:05:20.080: E/AndroidRuntime(854): at java.lang.reflect.Method.invoke(Method.java:515)
10-11 00:05:20.080: E/AndroidRuntime(854): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
10-11 00:05:20.080: E/AndroidRuntime(854): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
10-11 00:05:20.080: E/AndroidRuntime(854): at dalvik.system.NativeStart.main(Native Method)
If you want to remove item from your iteration
for(Iterator<MyAdapter> it = result.iterator(); it.hasNext();) {
MyAdapter s = it.next();
if(s.getClientPoints().getPointsSpent() == 0) {
it.remove();
}
}
Sir Himanshu Agarwal, thanks for helping me. i solve the problem and heres my solution for the items thats is listed when it is already present on the list
for(PostOrder order : listorder){
if (name[0].contentEquals(order.getItemName())){
String quantity = order.getItemQuantity();
order.setItemQuantity(String.valueOf((Integer.parseInt(quantity))+1));
adapterOrder.notifyDataSetChanged();
break;
} else {
counter++;
}
}
}
if (counter == listorder.size()){
listorder.add(new PostOrder(name[0], "1", name[1]));
adapterOrder = new PostAdapterOrder(MainActivity.this, listorder);
lv2.setAdapter(adapterOrder);
}
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);
I have the following code which is designed for the user to click on a button and when they click on the button, the particular string they are viewing is Favorited and stored somewhere else.
I have two questions.
One what's wrong with what I have right now? as it crashes when you click the button.
How would you go about finishing up on the load array method for the string to be loaded and saved to an array so the user could see that array later?
Thanks for your time!!
fav.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
loadArray("favorites");
favorites = Arrays.copyOf(favorites, favorites.length+1);
favorites[favorites.length]=display.getText().toString();
saveArray(favorites, "favorites");
}
});
home.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent openStartingPoint = new Intent("starting.rt.Menu2");
startActivity(openStartingPoint);
}
});
search.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent openStartingPoint = new Intent("starting.rt.Search");
startActivity(openStartingPoint);
}
});
moreapps.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent goToMarket;
goToMarket = new Intent(Intent.ACTION_VIEW, Uri
.parse("market://search?q=pub:\"Wompa\""));
startActivity(goToMarket);
}
});
}
public String[] loadArray(String arrayName) {
SharedPreferences prefs = getSharedPreferences("preferencename", 0);
int size = prefs.getInt(arrayName + "_size", 0);
String array[] = new String[size];
for(int i=0;i<size;i++)
array[i] = prefs.getString(arrayName + "_" + i, null);
return array;
}
public boolean saveArray(String[] array, String arrayName) {
SharedPreferences prefs = getSharedPreferences("preferencename", 0);
SharedPreferences.Editor editor = prefs.edit();
editor.putInt(arrayName +"_size", array.length);
for(int i=0;i<array.length;i++)
editor.putString(arrayName + "_" + i, array[i]);
return editor.commit();
}
Log Cat
05-08 23:10:51.329: I/Process(495): Sending signal. PID: 495 SIG: 9
05-08 23:11:02.360: D/dalvikvm(504): GC_EXTERNAL_ALLOC freed 44K, 53% free 2553K/5379K, external 1625K/2137K, paused 221ms
05-08 23:11:08.599: D/dalvikvm(504): GC_EXTERNAL_ALLOC freed 16K, 51% free 2644K/5379K, external 2707K/3308K, paused 174ms
05-08 23:11:12.570: D/AndroidRuntime(504): Shutting down VM
05-08 23:11:12.570: W/dalvikvm(504): threadid=1: thread exiting with uncaught exception (group=0x40015560)
05-08 23:11:12.599: E/AndroidRuntime(504): FATAL EXCEPTION: main
05-08 23:11:12.599: E/AndroidRuntime(504): java.lang.NullPointerException
05-08 23:11:12.599: E/AndroidRuntime(504): at starting.rt.Base$1.onClick(Base.java:52)
05-08 23:11:12.599: E/AndroidRuntime(504): at android.view.View.performClick(View.java:2485)
05-08 23:11:12.599: E/AndroidRuntime(504): at android.view.View$PerformClick.run(View.java:9080)
05-08 23:11:12.599: E/AndroidRuntime(504): at android.os.Handler.handleCallback(Handler.java:587)
05-08 23:11:12.599: E/AndroidRuntime(504): at android.os.Handler.dispatchMessage(Handler.java:92)
05-08 23:11:12.599: E/AndroidRuntime(504): at android.os.Looper.loop(Looper.java:123)
05-08 23:11:12.599: E/AndroidRuntime(504): at android.app.ActivityThread.main(ActivityThread.java:3683)
05-08 23:11:12.599: E/AndroidRuntime(504): at java.lang.reflect.Method.invokeNative(Native Method)
05-08 23:11:12.599: E/AndroidRuntime(504): at java.lang.reflect.Method.invoke(Method.java:507)
05-08 23:11:12.599: E/AndroidRuntime(504): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
05-08 23:11:12.599: E/AndroidRuntime(504): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
05-08 23:11:12.599: E/AndroidRuntime(504): at dalvik.system.NativeStart.main(Native Method)
05-08 23:11:17.869: I/Process(504): Sending signal. PID: 504 SIG: 9
loadArray function returns String[]. You might want to use it like:
String [] arr = loadArray("favorites");
This array can be used later as you asked in 2nd part. Hope this helps.
Update [Based on your comment]
So, if you want to grab text in TextView and wish to add it in a List/String array:
1) Try to get the String from TextView
TextView display = (TextView)findViewById(R.id.display);
String toSave = display.getText().toString();
2) Get the existing list from SharedPreferences using `loadArray':
String [] arr = loadArray("favorites");
3) Add the new String to it:
ArrayList<String> arrList = new ArrayList<String>();
for (int i=0; i<arr.length(); i++) {
arrList.add(arr[i]); //add old values to arraylist
}
// add new string to it:
arrList.add(toSave);
//Get back your array
String [] array = arrList.toArray(new String[arrList.size()]);
4) Save it Again.
saveArray(array, "favorites");
I'm developing an app for Android to download the pic from all the friends. I successfully made my app logging in. Now, I need to parse a JSON and download some of the pics. Here the sources:
FacebookPicDownloader (asynctask to download all the pics):
public class FacebookPicDownloader extends AsyncTask <String, Integer, Integer>{
Context context;
private final int MAX_BUFFER_SIZE = 2048;
String id;
int length;
public FacebookPicDownloader (Context context){
this.context = context;
}
//http://graph.facebook.com/ + userid + /picture?type=large to download the photos
#Override
protected Integer doInBackground(String... params) {
for (int i=0; i<params.length; i++){
try {
URL mUrl = new URL("http://graph.facebook.com/" + params[i] + "/picture?type=large");
HttpURLConnection connection = (HttpURLConnection) mUrl.openConnection();
connection.connect();
length = connection.getContentLength();
int downloaded = 0;
File file = new File ("/sdcard/syncro/");
if (!file.exists() || !file.isDirectory()){
file.mkdir();
}
id = params[0];
file = new File ("/sdcard/syncro/" + id);
FileOutputStream fos = new FileOutputStream (file);
//Start downloading
InputStream stream = connection.getInputStream();
byte [] buffer = new byte [(length < MAX_BUFFER_SIZE) ? length : MAX_BUFFER_SIZE];
int read;
while ((read=stream.read(buffer)) != -1){
fos.write(buffer, 0, read);
downloaded += read;
}
fos.close();
} catch (Exception e){
return 2;
}
}
return 1;
}
Manager.java, another AsyncTask that calls FacebookPicDownloader
import java.util.ArrayList;
import org.json.*;
import com.gnufabio.syncro.util.Util;
import android.app.ProgressDialog;
import android.content.Context;
import android.database.Cursor;
import android.os.AsyncTask;
import android.provider.ContactsContract;
import android.util.Log;
import com.facebook.android.*;
import com.gnufabio.syncro.util.*;
public class Manager extends AsyncTask<String, Integer, Integer>{
Context context;
Facebook facebook;
ProgressDialog dialog;
public void doStuff(Facebook facebook, Context context, String ... params){
this.context = context;
this.facebook = facebook;
this.execute(params);
}
#Override
protected void onPreExecute(){
dialog = ProgressDialog.show(context, "Wait" , " Loading. Please wait ... ", true);
dialog.setCancelable(false);
}
#Override
protected Integer doInBackground(String... params) {
String friendlist;
try {
friendlist = facebook.request("me/friends");
FileWriterThread filewriter = new FileWriterThread();
filewriter.writeFile(friendlist, "/sdcard/syncro/friends");
} catch (Exception e) {
friendlist = "";
}
String previous = "[NONE]";
ArrayList validContacts = new ArrayList<String>();
Cursor nameCur = context.getContentResolver().query(ContactsContract.Data.CONTENT_URI, null, ContactsContract.Data.MIMETYPE + " = ?", new String[] { ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE }, ContactsContract.CommonDataKinds.StructuredName.GIVEN_NAME);
while (nameCur.moveToNext()) {
String display = nameCur.getString(nameCur.getColumnIndex(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME));
if (display != null && !(display.contains(previous) || display.equalsIgnoreCase(previous)) && display.contains(" ")){
Log.d("SYNCRO", "Valid contact found: " + display);
validContacts.add(display);
previous = display;
}
}
nameCur.close();
try {
ArrayList idToDownload = new ArrayList <String>();
JSONArray jFriendList = new JSONArray(new JSONObject(friendlist).getString("data"));
for (int i = 0; i < jFriendList.length(); i++){
JSONObject jFriend = jFriendList.getJSONObject(i);
for (int y = 0; y < validContacts.toArray().length; y++){
if (jFriend.getString("name").equals((String)(validContacts.get(y)))){
String id = jFriend.getString("id");
Log.d("SYNCRO", "Adding pic for id \"" + id + "\"");
idToDowload.add(id);
}
}
}
FacebookPicDownloader downloader = new FacebookPicDownloader(context);
downloader.execute((String[]) idToDownload.toArray());
} catch (JSONException e) {
Log.d("SYNCRO", e.getMessage());
}
return null;
}
#Override
protected void onPostExecute(Integer result){
dialog.dismiss();
}
}
The problem is that it downloads just the first pic, and then the app crashes...here the logcat:
D/szipinf ( 7785): Initializing inflate state
E/AndroidRuntime( 7735): FATAL EXCEPTION: AsyncTask #1
E/AndroidRuntime( 7735): java.lang.RuntimeException: An error occured while executing doInBackground()
E/AndroidRuntime( 7735): at android.os.AsyncTask$3.done(AsyncTask.java:200)
E/AndroidRuntime( 7735): at java.util.concurrent.FutureTask$Sync.innerSetException(FutureTask.java:274)
E/AndroidRuntime( 7735): at java.util.concurrent.FutureTask.setException(FutureTask.java:125)
E/AndroidRuntime( 7735): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:308)
E/AndroidRuntime( 7735): at java.util.concurrent.FutureTask.run(FutureTask.java:138)
E/AndroidRuntime( 7735): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1088)
E/AndroidRuntime( 7735): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:581)
E/AndroidRuntime( 7735): at java.lang.Thread.run(Thread.java:1019)
E/AndroidRuntime( 7735): Caused by: java.lang.ClassCastException: [Ljava.lang.Object;
E/AndroidRuntime( 7735): at com.gnufabio.syncro.Manager.doInBackground(Manager.java:78)
E/AndroidRuntime( 7735): at com.gnufabio.syncro.Manager.doInBackground(Manager.java:1)
E/AndroidRuntime( 7735): at android.os.AsyncTask$2.call(AsyncTask.java:185)
E/AndroidRuntime( 7735): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:306)
E/AndroidRuntime( 7735): ... 4 more W/ActivityManager( 541): Force finishing activity com.gnufabio.syncro/.SuperSyncronizerActivity D/szipinf ( 7797): Initializing inflate state D/szipinf ( 7797): Initializing zlib to inflate D/dalvikvm( 7797): GC_CONCURRENT freed 224K, 44% free 3519K/6215K, external 0K/0K, paused 3ms+3ms
E/WindowManager( 7735): Activity com.gnufabio.syncro.SuperSyncronizerActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView#4051c538 that was originally added here
E/WindowManager( 7735): android.view.WindowLeaked: Activity com.gnufabio.syncro.SuperSyncronizerActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView#4051c538 that was originally added here
E/WindowManager( 7735): at android.view.ViewRoot.<init>(ViewRoot.java:260)
E/WindowManager( 7735): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:148)
E/WindowManager( 7735): at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:91)
E/WindowManager( 7735): at android.view.Window$LocalWindowManager.addView(Window.java:424)
E/WindowManager( 7735): at android.app.Dialog.show(Dialog.java:241)
E/WindowManager( 7735): at android.app.ProgressDialog.show(ProgressDialog.java:110)
E/WindowManager( 7735): at android.app.ProgressDialog.show(ProgressDialog.java:93)
E/WindowManager( 7735): at com.gnufabio.syncro.Manager.onPreExecute(Manager.java:36)
E/WindowManager( 7735): at android.os.AsyncTask.execute(AsyncTask.java:391)
E/WindowManager( 7735): at com.gnufabio.syncro.Manager.doStuff(Manager.java:31)
E/WindowManager( 7735): at com.gnufabio.syncro.SuperSyncronizerActivity$2.onClick(SuperSyncronizerActivity.java:73)
E/WindowManager( 7735): at android.view.View.performClick(View.java:2486)
E/WindowManager( 7735): at android.view.View$PerformClick.run(View.java:9130)
E/WindowManager( 7735): at android.os.Handler.handleCallback(Handler.java:587)
E/WindowManager( 7735): at android.os.Handler.dispatchMessage(Handler.java:92)
E/WindowManager( 7735): at android.os.Looper.loop(Looper.java:130)
E/WindowManager( 7735): at android.app.ActivityThread.main(ActivityThread.java:3694)
E/WindowManager( 7735): at java.lang.reflect.Method.invokeNative(Native Method)
E/WindowManager( 7735): at java.lang.reflect.Method.invoke(Method.java:507)
E/WindowManager( 7735): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:841)
E/WindowManager( 7735): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:599)
E/WindowManager( 7735): at dalvik.system.NativeStart.main(Native Method) D/dalvikvm( 7797): GC_CONCURRENT freed 171K, 41% free 3888K/6535K, external 0K/0K, paused 3ms+4ms
Thanks to anyone will help me.
The crash is caused by this code: (String[]) idToDownload.toArray().
Try creating a new String array instead of using the cast:
Replace the line
downloader.execute((String[]) idToDownload.toArray());
By:
String[] stringArray= new String[idToDownload.size()];
idToDownload.toArray(stringArray);
downloader.execute(stringArray);
KR