OnResume not showing desired result on 1sr attempt - java

I am new to android coding and need help with my project :
I have a function which I call from the OnResume of the mainActivity . The function reloads the data from the database and shows it on the list view .
Now when I go to second Activity and enter new data , the data is saved when onPause of secondActivity is called . On returning to mainActivity I don't see the changes made to list view but when I click on the same item of list view and go to second Activity again on returning for the 2nd time the changes start showing and the code works properly . What could be the possible reason for function not working in the 1st attempt ?
Note : I also call the function from onCreate of main Activity
EDIT 1:
the function to call
public void fill_list() {
cursor = db.rawQuery("SELECT * FROM " + GameEntry.TABLE + " WHERE " + GameEntry.G_DIFF + " = " + diff, null);
yesitis = cursor.moveToFirst();
if (yesitis)
count = cursor.getCount();
//int count=cursor.getCount();
listv = (ListView) findViewById(R.id.listview1);
listv.setAdapter(null);
arr.clear();
for (int j = 0; j < 15; j++) {
String data;
int j2 = j + 1;
data = String.valueOf(j2);
cursor3 = db.rawQuery("SELECT * FROM " + GameEntry.TABLE + " WHERE " + GameEntry.G_DIFF + " = " + diff+" AND "+GameEntry.G_LEVEL+" = "+j, null);
if (cursor3.moveToFirst()) {
cursor3.moveToPosition(0);
int showstate = cursor3.getColumnIndex(AppContract.GameEntry.G_STATE);
String temp1 = cursor3.getString(showstate);
if (temp1.equals("notStarted")) {
} else {
int showtime = cursor3.getColumnIndex(AppContract.GameEntry.time);
String temp2 = cursor3.getString(showtime);
data = data + " " + temp1 + " " + temp2;
}
}
arr.add(data);
}
ArrayAdapter<String> arradapt = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, arr) {
#Override
public View getView(int position, View convertView, ViewGroup parent) {
TextView textView = (TextView) super.getView(position, convertView, parent);
switch (diff) {
case 1:
textView.setBackgroundColor(Color.parseColor("#83EEA4"));
break;
case 2:
textView.setBackgroundColor(Color.parseColor("#00C5F6"));
break;
case 3:
textView.setBackgroundColor(Color.parseColor("#FF416A"));
break;
}
textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, 25);
return textView;
}
};
listv.setAdapter(arradapt);
listv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> av, View view, int ii, long id) {
level_select=ii;
cursor2 = db.rawQuery("SELECT * FROM " + GameEntry.TABLE + " WHERE " + GameEntry.G_DIFF + " = " + diff + " AND " + GameEntry.G_LEVEL + " = " + ii, null);
if (cursor2.moveToFirst()) {
cursor2.moveToPosition(0);
g_exist = "yes";
} else {
g_exist = "no";
}
Intent send = new Intent(ListActivity.this, GameActivity.class);
send.putExtra("level", ii);
send.putExtra("difficulty", diff);
send.putExtra("exist", g_exist);
startActivity(send);
}
});
}
onResume :
#Override
protected void onResume() {
super.onResume();
Toast.makeText(getApplicationContext(), "onResumed called", Toast.LENGTH_LONG).show();
fill_list();
}
mainActivity onCreate :
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list);
MobileAds.initialize(this,
"ca-app-pub-6165188418561315~3404004371");
mAdView = (AdView) findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder().build();
mAdView.loadAd(adRequest);
diff = getIntent().getExtras().getInt("difficulty");
mhelper = new appdbhelper(this);
db = mhelper.getReadableDatabase();
fill_list();
Toast.makeText(getApplicationContext(), "sqlsize =" + String.valueOf(yesitis), Toast.LENGTH_SHORT).show();
}
onPause of second activity (enterdata function updates the specified row of database ):
#Override
protected void onPause() {
super.onPause();
//Toast.makeText(getApplicationContext(), "onPause called", Toast.LENGTH_LONG).show();
timer.stop();
enterdata();
}
Thanks in advance

Related

int android.database.Cursor.getColumnIndex(java.lang.String)' on a null object reference

public class MainActivity extends AppCompatActivity {
TextView dataTextView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dataTextView = findViewById(R.id.dataTextView);
FloatingActionButton floatingActionButton = findViewById(R.id.floatingActionButton);
floatingActionButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MainActivity.this, add_member.class);
startActivity(intent);
}
});
}
#Override
protected void onStart() {
super.onStart();
displayData();
}
private void displayData () {
String [] projection = {
MemberEntry._ID,
MemberEntry.COLUMN_FIRST_NAME,
MemberEntry.COLUMN_LAST_NAME,
MemberEntry.COLUMN_GENDER,
MemberEntry.COLUMN_SPORT
};
Cursor cursor = getContentResolver().query(
MemberEntry.CONTENT_URI,
projection,
null,
null,
null
);
dataTextView.setText("All members\n\n");
dataTextView.append(MemberEntry._ID + " " +
MemberEntry.COLUMN_FIRST_NAME + " " +
MemberEntry.COLUMN_LAST_NAME + " " +
MemberEntry.COLUMN_GENDER + " " +
MemberEntry.COLUMN_SPORT);
int idIndex = cursor.getColumnIndex(MemberEntry._ID);
int idFirstName = cursor.getColumnIndex(MemberEntry.COLUMN_LAST_NAME);
int idLastName = cursor.getColumnIndex(MemberEntry.COLUMN_LAST_NAME);
int idGender = cursor.getColumnIndex(MemberEntry.COLUMN_GENDER);
int idSport = cursor.getColumnIndex(MemberEntry.COLUMN_SPORT);
while (cursor.moveToNext()) {
int currentID = cursor.getInt(idIndex);
String currentFirstName = cursor.getString(idFirstName);
String currentLastName = cursor.getString(idLastName);
int currentGender = cursor.getInt(idGender);
String currentSport = cursor.getString(idSport);
dataTextView.append("\n" +
currentID + " " +
currentFirstName + " " +
currentLastName + " " +
currentGender + " " +
currentSport);
}
cursor.close();
}
}
This throws an exception:
java.lang.NullPointerException: Attempt to invoke interface method 'int android.database.Cursor.getColumnIndex(java.lang.String)' on a null object reference
at com.example.sportclub.MainActivity.displayData(MainActivity.java:66)
at com.example.sportclub.MainActivity.onStart(MainActivity.java:40)
can you help me ?)
It looks like the line cursor.getColumnIndex(MemberEntry._ID); is the problem. In all likelihood given the error message cursor is null and that your call to getContentResolver().query failed.
private void insertMember () {
String firstName = firstNameEditText.getText().toString().trim();
String lastName = lastNameEditText.getText().toString().trim();
String sport = sportEditText.getText().toString().trim();
ContentValues contentValues = new ContentValues();
contentValues.put(MemberEntry.COLUMN_FIRST_NAME, firstName);
contentValues.put(MemberEntry.COLUMN_LAST_NAME, lastName);
contentValues.put(MemberEntry.COLUMN_SPORT, sport);
contentValues.put(MemberEntry.COLUMN_GENDER, gender);
ContentResolver contentResolver = getContentResolver();
Uri uri = contentResolver.insert(MemberEntry.CONTENT_URI, contentValues);
if (uri == null ) {
Toast.makeText(this, "Insertion of data in the table failed for ", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(this, "Data save ", Toast.LENGTH_LONG).show();
}
}
}
this is correct code ? or not ?

RecyclerView inside RecyclerView made wrong getItemCount()

So its to looks like this:
SCREENSHOT
But when I click add or less button its returning the size of the whole list.
In this case its returns 2(because the otitles.size() returns 2) Like under the item that I clicked appears another item from the list.
PARENT RecyclerView Adapter:
public class recyclercart extends RecyclerView.Adapter<recyclercart.myViewHolder> {
Context context;
ArrayList<String> list;
public static View.OnClickListener onclickup;
public static View.OnClickListener onclickdown;
public static ArrayList<String> otitles = new ArrayList<>();
public static ArrayList<String> oimages = new ArrayList<>();
public static ArrayList<String> oingridients = new ArrayList<>();
public static ArrayList<String> odependencies = new ArrayList<>();
public static ArrayList<String> oquantities = new ArrayList<>();
public static ArrayList<String> oprices = new ArrayList<>();
public static ArrayList<String> ostartprices = new ArrayList<>();
public static ArrayList<String> obrand = new ArrayList<>();
public static ArrayList<String> oid = new ArrayList<>();
Cursor gettitle, getimage, getingridients, getdependencies,getquantities, getprices, getstartprice, getbrand, getid;
ArrayList<Integer> postoremove= new ArrayList<>();
ProgressBar progressBar;
SQLiteDatabase database;
public recyclercart(Context c, ProgressBar progressBar){
context=c;
this.progressBar=progressBar;
SQLHelper helper = new SQLHelper(context);
database = helper.getWritableDatabase();
Cursor cursor = database.rawQuery("SELECT * FROM "+SQLHelper.DATABASE_TABLE, null);
list =new ArrayList<>();
cursor.moveToFirst();
do {
String lol = cursor.getString(cursor.getColumnIndex(SQLHelper.BRAND_NAME));
list.add(lol.substring(0,lol.length()-5));
}while (cursor.moveToNext());
if(cursor.moveToLast()) {
postoremove.clear();
Log.d("glavniy", "LIST: " + list.toString());
list = new ArrayList<>(removeDuplicates(list));
}
}
#NonNull
#Override
public myViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(context);
View view = inflater.inflate(R.layout.templatecart, parent, false );
return new myViewHolder(view);
}
#SuppressLint("SetTextI18n")
#Override
public void onBindViewHolder(#NonNull myViewHolder holder, int position) {
otitles.clear();
oimages.clear();
oingridients.clear();
odependencies.clear();
oprices.clear();
oquantities.clear();
ostartprices.clear();
obrand.clear();
oid.clear();
Cursor cur = database.rawQuery("SELECT "+SQLHelper.TITLE_NAME+" FROM "+SQLHelper.DATABASE_TABLE+" WHERE "+SQLHelper.BRAND_NAME+" LIKE '%"+
list.get(position)+"%'", null);
SQLHelper helper = new SQLHelper(context);
SQLiteDatabase database = helper.getWritableDatabase();
gettitle = database.rawQuery("SELECT "+SQLHelper.TITLE_NAME+" FROM "+SQLHelper.DATABASE_TABLE+" WHERE "
+SQLHelper.BRAND_NAME+" LIKE '%"+list.get(position)+"%'", null);
getimage = database.rawQuery("SELECT "+SQLHelper.IMAGESRC_NAME+" FROM "+SQLHelper.DATABASE_TABLE+" WHERE "
+SQLHelper.BRAND_NAME+" LIKE '%"+list.get(position)+"%'", null);
getingridients = database.rawQuery("SELECT "+SQLHelper.INGRIDIENTS_NAME+" FROM "+SQLHelper.DATABASE_TABLE+" WHERE "
+SQLHelper.BRAND_NAME+" LIKE '%"+list.get(position)+"%'", null);
getdependencies = database.rawQuery("SELECT "+SQLHelper.DEPENDENCIES_NAME+" FROM "+SQLHelper.DATABASE_TABLE+" WHERE "
+SQLHelper.BRAND_NAME+" LIKE '%"+list.get(position)+"%'", null);
getprices = database.rawQuery("SELECT "+SQLHelper.PRICE_NAME+" FROM "+SQLHelper.DATABASE_TABLE+" WHERE "
+SQLHelper.BRAND_NAME+" LIKE '%"+list.get(position)+"%'", null);
getquantities = database.rawQuery("SELECT "+SQLHelper.QUANTITY_NAME+" FROM "+SQLHelper.DATABASE_TABLE+" WHERE "
+SQLHelper.BRAND_NAME+" LIKE '%"+list.get(position)+"%'", null);
getstartprice = database.rawQuery("SELECT "+SQLHelper.START_PRICE+" FROM "+SQLHelper.DATABASE_TABLE+" WHERE "
+SQLHelper.BRAND_NAME+" LIKE '%"+list.get(position)+"%'", null);
getbrand = database.rawQuery("SELECT "+SQLHelper.BRAND_NAME+" FROM "+SQLHelper.DATABASE_TABLE+" WHERE "
+SQLHelper.BRAND_NAME+" LIKE '%"+list.get(position)+"%'", null);
getid = database.rawQuery("SELECT "+SQLHelper.KEY_ID+" FROM "+SQLHelper.DATABASE_TABLE+" WHERE "
+SQLHelper.BRAND_NAME+" LIKE '%"+list.get(position)+"%'", null);
if (gettitle.moveToFirst() && getimage.moveToNext() && getingridients.moveToFirst() && getdependencies.moveToFirst()
&& getprices.moveToFirst() && getquantities.moveToFirst() && getstartprice.moveToFirst() && getbrand.moveToFirst() && getid.moveToFirst()) {
do {
otitles.add(gettitle.getString(gettitle.getColumnIndex(SQLHelper.TITLE_NAME)));
oimages.add(getimage.getString(getimage.getColumnIndex(SQLHelper.IMAGESRC_NAME)));
oingridients.add(getingridients.getString(getingridients.getColumnIndex(SQLHelper.INGRIDIENTS_NAME)));
odependencies.add(getdependencies.getString(getdependencies.getColumnIndex(SQLHelper.DEPENDENCIES_NAME)));
oprices.add(getprices.getString(getprices.getColumnIndex(SQLHelper.PRICE_NAME)));
oquantities.add(getquantities.getString(getquantities.getColumnIndex(SQLHelper.QUANTITY_NAME)));
ostartprices.add(getstartprice.getString(getstartprice.getColumnIndex(SQLHelper.START_PRICE)));
obrand.add(getbrand.getString(getbrand.getColumnIndex(SQLHelper.BRAND_NAME)));
oid.add(getid.getString(getid.getColumnIndex(SQLHelper.KEY_ID)));
Log.d("glavniy", String.valueOf(ostartprices));
} while (gettitle.moveToNext() && getimage.moveToNext() && getingridients.moveToNext() && getdependencies.moveToNext()
&& getprices.moveToNext() && getquantities.moveToNext() && getstartprice.moveToNext() && getbrand.moveToNext() && getid.moveToNext());
}
if(gettitle.moveToLast()) {
Log.d("glavniy", "MOVETOLAST");
holder.recyclerView.setLayoutManager(new LinearLayoutManager(context));
holder.recyclerView.setAdapter(new recyclerOrdersAdapter(context, otitles, oimages, oingridients, oquantities, oprices, ostartprices
, obrand, odependencies, oid));
}
DatabaseReference reference = FirebaseDatabase.getInstance().getReference("resources");
reference.child(list.get(position)).addListenerForSingleValueEvent(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
holder.title.setText(snapshot.child("nameBrand").getValue().toString());
Glide.with(context).load(snapshot.child("imageBrand").getValue().toString()).into(holder.imageView);
try {
if(recyclerSearchRecycler.timeCheck(snapshot.child("times").child("startTime").getValue().toString(),
snapshot.child("times").child("closeTime").getValue().toString())){
holder.open.setText("OPEN");
}else {holder.open.setText("CLOSED");}
} catch (ParseException e) {
e.printStackTrace();
}
reference.child(list.get(position)).child("addresses").addListenerForSingleValueEvent(new ValueEventListener() {
#SuppressLint("SetTextI18n")
#Override
public void onDataChange(#NonNull DataSnapshot snapshot) {
for (DataSnapshot dataSnapshot : snapshot.getChildren()){
ArrayList<String> addresses = new ArrayList<>();
addresses.add(dataSnapshot.getValue().toString());
Log.d("glavniy", dataSnapshot.getValue().toString());
if(addresses.size()==snapshot.getChildrenCount()) {
try {
float distance = activityBrandPage.getNearestRest(addresses, context);
Log.d("glavniy", "DIST: " + distance);
if (distance <= 1000) {
progressBar.setVisibility(View.INVISIBLE);
holder.delivery.setText("Delivery: 400 AMD");
} else if (distance > 1000 && distance <= 2000) {
holder.delivery.setText("Delivery: 500 AMD");
progressBar.setVisibility(View.INVISIBLE);
} else if (distance > 2000 && distance <= 3000) {
holder.delivery.setText("Delivery: 600 AMD");
} else if (distance > 3000 && distance <= 4000) {
holder.delivery.setText("Delivery: 700 AMD");
progressBar.setVisibility(View.INVISIBLE);
}
if (search.prog != null) {
search.prog.setVisibility(View.INVISIBLE);
}
} catch (IOException e) {
e.printStackTrace();
progressBar.setVisibility(View.VISIBLE);
Toast.makeText(context, "Failed, please restart", Toast.LENGTH_SHORT).show();
}
}
}
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
#Override
public void onCancelled(#NonNull DatabaseError error) {
}
});
}
#Override
public int getItemCount() {
return list.size();
}
public static class myViewHolder extends RecyclerView.ViewHolder {
TextView title, delivery, open;
ImageView imageView;
public static RecyclerView recyclerView;
public myViewHolder(#NonNull View itemView) {
super(itemView);
imageView=itemView.findViewById(R.id.ivBrandCart);
recyclerView=itemView.findViewById(R.id.recyclerMainCart);
title=itemView.findViewById(R.id.tvBrandCart);
delivery=itemView.findViewById(R.id.tvdelivery);
open=itemView.findViewById(R.id.opentv);
}
}
CHILD RecyclerView Adapter:
public class recyclerOrdersAdapter extends RecyclerView.Adapter<recyclerOrdersAdapter.myViewHolder> {
public static Context context;
SQLiteDatabase database;
public static int pos;
public static ArrayList<String> otitles = new ArrayList<>();
public static ArrayList<String> oimages = new ArrayList<>();
public static ArrayList<String> oingridients = new ArrayList<>();
public static ArrayList<String> odependencies = new ArrayList<>();
public static ArrayList<String> oquantities = new ArrayList<>();
public static ArrayList<String> oprices = new ArrayList<>();
public static ArrayList<String> ostartprices = new ArrayList<>();
public static ArrayList<String> obrand = new ArrayList<>();
public static ArrayList<String> oids = new ArrayList<>();
#SuppressLint("Recycle")
public recyclerOrdersAdapter(Context c, ArrayList<String> titles, ArrayList<String> images, ArrayList<String> ingridients,
ArrayList<String> quantities, ArrayList<String> prices, ArrayList<String> startprices, ArrayList<String> brands,
#Nullable ArrayList<String> dependencies, ArrayList<String> ids){
System.out.println("hi");
otitles=new ArrayList<>(titles);
oimages= new ArrayList<>(images);
oingridients=new ArrayList<>(ingridients);
oquantities=new ArrayList<>(quantities);
oprices=new ArrayList<>(prices);
ostartprices=new ArrayList<>(startprices);
obrand=new ArrayList<>(brands);
oids=new ArrayList<>(ids);
assert dependencies != null;
odependencies=new ArrayList<>(dependencies);
context = c;
}
#NonNull
#Override
public myViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(context);
View view = inflater.inflate(R.layout.templateorders, parent, false );
return new myViewHolder(view);
}
#SuppressLint("SetTextI18n")
#Override
public void onBindViewHolder(#NonNull myViewHolder holder, int position) {
System.out.println("hello n");
if(obrand.size()!=0) {
String title = otitles.get(position);
String image = oimages.get(position);
String ingridient = oingridients.get(position);
String dependencie = odependencies.get(position);
String priceik = oprices.get(position);
String quanik = oquantities.get(position);
ingridient = ingridient.replaceAll("[^a-zA-Z0-9, ]", "");
if (ingridient.contains("null, ")) {
ingridient = ingridient.replaceAll("null, ", "");
} else if (ingridient.contains("null,")) {
ingridient = ingridient.replaceAll("null,", "");
} else {
ingridient = ingridient.replaceAll("null", "");
}
dependencie = dependencie.replaceAll("[^a-zA-Z0-9, ]", "");
System.out.println("ingridients " + ingridient);
holder.title.setText(title);
Glide.with(context).load(image).placeholder(R.drawable.elipsis).into(holder.imageView);
holder.ingridients.setText(ingridient);
if(odependencies.get(position)!=null) {
holder.dependencies.setText(dependencie);
}
if(!priceik.contains("$")) {
holder.price.setText(priceik + "$");
}else {
holder.price.setText(priceik);
}
holder.quantity.setText(quanik);
holder.startprice.setText(ostartprices.get(position));
holder.id.setText(oids.get(position));
SQLHelper helper = new SQLHelper(context);
database = helper.getWritableDatabase();
holder.delete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.d("glavniy", "TITLE: "+holder.title.getText().toString());
Log.d("glavniy", "position is" + String.valueOf(position));
SQLHelper helper = new SQLHelper(context);
SQLiteDatabase database = helper.getWritableDatabase();
database.execSQL("DELETE FROM " + SQLHelper.DATABASE_TABLE + " WHERE (" + SQLHelper.KEY_ID +
"='" + holder.id.getText().toString() + "')");
notifyItemRemoved(position);
Log.d("glavniy", DatabaseUtils.dumpCursorToString(database.rawQuery("SELECT * FROM " + SQLHelper.DATABASE_TABLE, null)));
}
});
holder.up.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.d("glavniy", "TITLE: "+holder.title.getText().toString());
int o = Integer.parseInt(holder.quantity.getText().toString())+1;
holder.quantity.setText(String.valueOf(o));
int o1 = Integer.parseInt(holder.startprice.getText().toString()) * Integer.parseInt(holder.quantity.getText().toString());
holder.price.setText(o1 + "$");
Log.d("glavniy", "UPDATED");
database.execSQL("UPDATE " + SQLHelper.DATABASE_TABLE + " SET " + SQLHelper.QUANTITY_NAME + "='" + holder.quantity.getText() + "' WHERE ("
+ SQLHelper.KEY_ID + "='" + holder.id.getText() + "')");
database.execSQL("UPDATE " + SQLHelper.DATABASE_TABLE + " SET " + SQLHelper.PRICE_NAME + "='" + holder.price.getText() + "' WHERE ("
+ SQLHelper.KEY_ID + "='" + holder.id.getText() + "')");
Log.d("glavniy", DatabaseUtils.dumpCursorToString(database.rawQuery("SELECT * FROM " + SQLHelper.DATABASE_TABLE, null)));
}
});
holder.down.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (Integer.parseInt(holder.quantity.getText().toString()) != 1) {
holder.quantity.setText(String.valueOf(Integer.parseInt(holder.quantity.getText().toString())-1));
int o1 = Integer.parseInt(holder.price.getText().toString().replace("$","")) - Integer.parseInt(holder.startprice.getText().toString());
holder.price.setText(o1 + "$");
database.execSQL("UPDATE " + SQLHelper.DATABASE_TABLE + " SET " + SQLHelper.QUANTITY_NAME + "='" + holder.quantity.getText() + "' WHERE ("
+ SQLHelper.KEY_ID + "='" + holder.id.getText() + "')");
database.execSQL("UPDATE " + SQLHelper.DATABASE_TABLE + " SET " + SQLHelper.PRICE_NAME + "='" + holder.price.getText() + "' WHERE ("
+ SQLHelper.KEY_ID + "='" + holder.id.getText() + "')");
Log.d("glavniy", DatabaseUtils.dumpCursorToString(database.rawQuery("SELECT * FROM " + SQLHelper.DATABASE_TABLE, null)));
}
}
});
}
}
#Override
public int getItemCount() {
return otitles.size();
}
#SuppressLint("StaticFieldLeak")
public class myViewHolder extends RecyclerView.ViewHolder {
public TextView title, price, ingridients, dependencies, up,down, quantity, startprice, id;
public ImageView imageView;
public ImageView delete;
public myViewHolder(#NonNull View itemView) {
super(itemView);
id=itemView.findViewById(R.id.textView7);
startprice=itemView.findViewById(R.id.textView6);
quantity = itemView.findViewById(R.id.ordersQuanity);
up=itemView.findViewById(R.id.upBtn);
down=itemView.findViewById(R.id.downBtn);
delete=itemView.findViewById(R.id.removeButton);
title = itemView.findViewById(R.id.titleOfOrder);
price = itemView.findViewById(R.id.priceOfOrder);
imageView=itemView.findViewById(R.id.imageOfOrde);
ingridients = itemView.findViewById(R.id.ingridientsOfOrder);
dependencies = itemView.findViewById(R.id.dependenciesOfOrder);
}
}
}
How can I make to return exactly size of list that PARENT RecyclerView sends (of that position)?
Oh... This is really hard to read.
I will try to give you some tips for better architecture. I hope you are fine with it.
Why are you using so many lists? Why you don't make one list of custom madr classes with all the data like title, image, ingredient itp.
Why you name the type of class recyclercart instead of RecyclerCard. In Kotlin and in Java programmers have not written rule that classes should be named from big letter and in camelCase stale.
The other thing is that you melted together using database and uploadung data into the view processes. It is not good. It would be better to have other class like DatabaseManager or something like this, which will make the job of taking data from the database etc. If you will do that your RecyclerViewAdapter will get list of ready items in the constructor and the only responsibility of this class will be to show the data in the views. The code will be simplified and maybe the mistake will be more visible. If you want to upload children data dynamically (during scrolling) you cab, but the code for it should be places in the DatabaseManager or Helper, too. If number of data is not big- it could be better to upload it before adapter is created even and just put Map<Item,List instead.
I would also check the way of using SQLiteHelper. I am not sure, but something tells me that you are creating few databases in one program. It can be damgerous. Please, just check it. Remember to create database once and just connect to it few times. About this one I am not sure. I have to less time to investigate yourt code.
About my tips: checkout SOLID; you will have a lot more clear architecture.
Ok finally I found solution. Thats pretty funny but problem was that ArrayLists were static. So I just removed static field and everything works fine now.

Update/Edit Sqlite Database using SimpleCursorAdapter via onClick ImageView

Illustration
Please see image first..
How can i get value "Test 1" and after that i want update column (favorite) in sqlite database to "Yes"?
I was searching to find answer for my case but there is no match with my problem, or maybe I am the one who doesn't understand.. :D
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.act_channel_list);
channelList = this.findViewById(R.id.channelList);
mDB = openDB();
if (mDB != null) {
mCsr = mDB.query(CHANNELTABLE,
new String[]{KEY_NO + " AS _id",
KEY_NAME, KEY_CATEGORY, KEY_LOGO, KEY_SERVER1, KEY_SERVER2, KEY_SERVER3, KEY_SERVER4, KEY_SERVER5, KEY_LIKE
},
null,null,null,null,null);
mSCA = new SimpleCursorAdapter(this,R.layout.custom_listview,mCsr,
new String[]{KEY_NAME, KEY_CATEGORY, KEY_LOGO, KEY_LIKE},
new int[]{R.id.channel_name, R.id.category, R.id.logo, R.id.like},0);
mSCA.setViewBinder(new SimpleCursorAdapter.ViewBinder(){
public boolean setViewValue(final View view, Cursor cursor, int columnIndex){
if(view.getId() == R.id.logo){
channelName = cursor.getString(3);
int resID = getResources().getIdentifier(channelName, "drawable", getPackageName());
//Toast.makeText(Channel_List_Act.this, cursor.getString(9), Toast.LENGTH_LONG).show();
((ImageView)view.findViewById(R.id.logo)).setImageDrawable(getResources().getDrawable(resID, getApplicationContext().getTheme()));
return true;
}
if(view.getId() == R.id.like){
liked = cursor.getString(9);
final int resID = getResources().getIdentifier(liked, "drawable", getPackageName());
((ImageView)view.findViewById(R.id.like)).setImageDrawable(getResources().getDrawable(resID, getApplicationContext().getTheme()));
((ImageView)view.findViewById(R.id.like)).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
I AM STUCK IN HERE, OR MAYBE NOT HERE?
}
});
return true;
}
return false;
}
});
channelList.setAdapter(mSCA);
} else {
Toast.makeText(this,"Unable to open Database.",Toast.LENGTH_LONG).show();
}
}
this is weird to answer my own question.. :D
//This is for getting Textview and Imageview from custom_listview.xml
RelativeLayout vwParentRow = (RelativeLayout)v.getParent();
TextView child = (TextView)vwParentRow.getChildAt(1);
ImageView btnChild = (ImageView)vwParentRow.getChildAt(3);
//This is for changing image to favorited or no
assert (R.id.like == btnChild.getId());
Integer integer = (Integer) btnChild.getTag();
integer = integer == null ? 0 : integer;
switch(integer) {
case R.drawable.yes:
btnChild.setImageResource(R.drawable.no);
btnChild.setTag(R.drawable.no);
//This is to update database
mDB.execSQL("UPDATE Channel_Info SET Favourite='no' WHERE name='" + child.getText() + "'");
break;
case R.drawable.no:
default:
btnChild.setImageResource(R.drawable.yes);
btnChild.setTag(R.drawable.yes);
mDB.execSQL("UPDATE Channel_Info SET Favourite='yes' WHERE name='" + child.getText() + "'");
break;
}
Get the ID of a drawable in ImageView
I am forgot.
Forgot

Unexplained bug at Android Firebase RecyclerView with Button pressed

I have a RecyclerView and a button for 'Binding' each item (Moving to another child at the DB).
Most of the time it works well, but sometimes i'm receiving indexOutOfBounds Exception.
This is a screen shot:
When I press at 'BIND' at the top recycler view item, i'm receiving this bug.
I made it print this line:
Log.d("dDebug","Almost bug! Size: " + ((MissionAdapter) MissionAdapter.this).mSnapshots.size() + " , index: " + missionPosition);
And it prints this:
D/dDebug: Almost bug! Size: 1 , index: 1
Here you can see the bug - size 1, index 1, so it will have indexOutOfBounds.
This is the code:
public class AvailableFragmentPilot extends Fragment {
private String TAG = "dDEBUG";
private RecyclerView mavailableList;
private DatabaseReference mAvailableMissionsDb, mPendingMissionsDb;
private FirebaseAuth mAuth;
private ProgressDialog mSubmitMsnProgress;
private String mCurrent_pilot_id;
private View mMainView;
// Query queries;
public AvailableFragmentPilot() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
mMainView = inflater.inflate(R.layout.fragment_of_recycler_view_user, container, false);
mavailableList = (RecyclerView)mMainView.findViewById(R.id.mission_recycler_user);
mAuth = FirebaseAuth.getInstance();
mSubmitMsnProgress = new ProgressDialog(getContext());
mCurrent_pilot_id = mAuth.getCurrentUser().getUid();
mAvailableMissionsDb = FirebaseDatabase.getInstance().getReference().child("Missions").child("Available");
mAvailableMissionsDb.keepSynced(true);
mPendingMissionsDb = FirebaseDatabase.getInstance().getReference().child("Missions").child("Pending");
mPendingMissionsDb.keepSynced(true);
// queries = mAvailableMissionsDb.orderByChild("user_uid").equalTo(mCurrent_pilot_id);
mavailableList.setHasFixedSize(true);
mavailableList.setLayoutManager(new LinearLayoutManager(getContext()));
// Inflate the layout for this fragment
return mMainView;
}
#Override
public void onStart() {
super.onStart();
mavailableList.setAdapter(new MissionAdapter(mAvailableMissionsDb));
}
private class MissionAdapter extends FirebaseRecyclerAdapter<Mission, AvailableFragmentPilot.MissionsViewHolder> {
public MissionAdapter(Query queries){
super(Mission.class, R.layout.missions_single_layout, AvailableFragmentPilot.MissionsViewHolder.class, queries);
}
#Override
protected void populateViewHolder(AvailableFragmentPilot.MissionsViewHolder missionViewHolder, final Mission missionModel, final int missionPosition) {
Log.d(TAG, "inside populateViewHolder" + missionModel.getType() + " , " + missionModel.getDescription());
missionViewHolder.setMissionName(missionModel.getType());
missionViewHolder.setMissionDescription(missionModel.getDescription());
missionViewHolder.setMissionStatus(missionModel.getStatus());
missionViewHolder.button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Mission clickedMission = null;
if (((MissionAdapter) MissionAdapter.this).mSnapshots.size()>missionPosition){
clickedMission = AvailableFragmentPilot.MissionAdapter.this.getItem(missionPosition);
Log.d("dDebug","Ein bug. Size: " + ((MissionAdapter) MissionAdapter.this).mSnapshots.size() + " , index: " + missionPosition + " , mission: " + clickedMission.getType() + ": " + clickedMission.getDescription());
}
else{
Log.d("dDebug","Almost bug! Size: " + ((MissionAdapter) MissionAdapter.this).mSnapshots.size() + " , index: " + missionPosition);
}
if (clickedMission != null){ // for the sake of being extra-safe
// String url_str = getRef(missionPosition).toString();
// String uuid_for_mission = url_str.split("/")[5];
Log.d(TAG,"The button was pressed for mission: " + clickedMission.getType() + " , uid: " + missionModel.getMission_uid());
// removeMission(uuid_for_mission);
bindMission(clickedMission);
}
}
});
}
}
public void bindMission(final Mission mission){
AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
builder.setCancelable(false);
builder.setTitle("Mission bind");
builder.setMessage("Are you sure you want to bind this mission?");
builder.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
mAvailableMissionsDb.child(mission.getMission_uid()).setValue(null);
final HashMap<String, String> missionMap = new HashMap<>();
missionMap.put("username", mission.getUsername());
missionMap.put("user_uid", mission.getUser_uid());
missionMap.put("mission_uid", mission.getMission_uid());
missionMap.put("type", mission.getType());
missionMap.put("status", "Pending");
missionMap.put("description", mission.getDescription());
missionMap.put("x", String.valueOf(mission.getX()));
missionMap.put("y", String.valueOf(mission.getY()));
missionMap.put("pilot_uid", mCurrent_pilot_id);
mPendingMissionsDb.child(mission.getMission_uid()).setValue(missionMap).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if (task.isSuccessful()){
// Log.d("dDebug","Before");
mSubmitMsnProgress.dismiss();
Toast.makeText(getContext(), ("Bind to mission " + mission.getType()),
Toast.LENGTH_LONG).show();
Log.d("dDebug","Painting in Red 1");
}
else {
Toast.makeText(getContext(), "Something went wrong",
Toast.LENGTH_SHORT).show();
}
}
});
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Log.d("dDebug","ok, not binding");
}
});
// Create the AlertDialog object and return it
builder.create().show();
}
public static class MissionsViewHolder extends RecyclerView.ViewHolder {
View mView;
Button button ;
public MissionsViewHolder(View itemView) {
super(itemView);
mView = itemView;
button = (Button)mView.findViewById(R.id.mission_single_button);
button.setText("BIND");
}
public void setMissionName(String name){
TextView mMissionNameView = mView.findViewById(R.id.mission_single_name);
mMissionNameView.setText(name);
}
public void setMissionStatus(String status){
TextView mMissionStatusView = mView.findViewById(R.id.mission_single_status);
mMissionStatusView.setText(status);
if (status.equals("Available")){
mMissionStatusView.setTextColor(Color.parseColor("#008000"));;
} else {
mMissionStatusView.setTextColor(Color.parseColor("#FF0000"));;
}
}
public void setMissionDescription(String description){
TextView mMissionDescriptionView = mView.findViewById(R.id.mission_single_description);
mMissionDescriptionView.setText(description);
}
}
}
In addition - sometimes I will have 5 items, I'll press at the most upper one, (Should be index 0!) - and the SECOND item is being moved (at index 1).
So it means that probarely something is wrong with the way i'm getting the item that was clciked.
Rookie recycler view mistake: the view holder can move around and be reused (thus changing its position) while the onClick callback will only store a reference to the original position. To fix that, use viewHolder.getAdapterPosition(). 👍

Get height of listview cells to ease scrolling upwards

An activity with a listview has a problem that is, the listview will have different amount of content in each cell. When the user scrolls down, the listview is smooth and things work as expected. But, when the user scrolls up, the cached data of the listview is reloaded. This redraw is making the listview scrolling up jumpy. What I figured out is that, if I calculate the height of each cell while scrolling down and save it in an ArrayList and apply the same height when the user scrolls up against the visible listitem then the jumpy scroll can be fixed. I have tested the same by setting a static height for every post, the scrollbar was not jumpy. But, I have to make it dynamic according to each cell height. The listview code might look to be a little complex!
The activity:
public class PostListActivity extends Activity implements OnScrollListener {
TableLayout html_output_table;
int id = 0;
List<String> dataFromParse = new ArrayList<String>();
LazyObjectDrawingAdapter adapter;
ListView listView;
List<RichPost> richPostArrayList = new ArrayList<RichPost>();
private int currentScrollState;
private int currentVisibleItemCount;
private int skipParam = 0;
private boolean flag_loading = false;
int mLastFirstVisibleItem = 0;
HashMap<integer, String> hashMap = new HashMap<integer, String>();
int initialHeight = 0;
ArrayList<Integer> heightList = new ArrayList<Integer>();
int position;
boolean scrolling = false;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_post_list_list);
listView = (ListView) findViewById(R.id.listView);
// Need to create the adapter constructor
listView.setOnScrollListener(this);
adapter = new LazyObjectDrawingAdapter(PostListActivity.this, dataFromParse, richPostArrayList);
listView.setAdapter(adapter);
setContent();
// cityListBody("Hello");
}
public void setContent(){
// Pull data from Parse
HashMap<String, Object> params = new HashMap<String, Object>();
params.put("userid", ParseUser.getCurrentUser().getObjectId());
params.put("skip", skipParam);
ParseCloud.callFunctionInBackground("studentsPosts", params, new FunctionCallback<List<List<ParseObject>>>() {
#Override
public void done(List<List<ParseObject>> data, com.parse.ParseException arg1){
if (data == null) {
} else {
Log.e("size ", "RUNNING Size : " + data.size());
if (data.size() > 0) {
flag_loading = false;
for (int i = 0; i < data.size(); i++) {
RichPost rc = new RichPost();
//if (heightList.size()>i){
Log.e("heightList.size()", ""+heightList.size());
//}
if (data.get(0).get(0).get("htmlContent") != null) {
// Switch i to 1 to force just 1 additon.
dataFromParse.add(data.get(i).get(0).getString("htmlContent"));
rc.setHtmlCode(data.get(i).get(0).getString("htmlContent"));
Log.i("Calling notifiyDataSetchanged", "now");
}
if (data.get(i).get(0).get("photos") != null) {
List<ParseFile> pFileList;
pFileList = (List<ParseFile>) data.get(i).get(0).get("photos");
rc.setPhotosArray(pFileList);
}
if (data.get(i).get(0).getParseFile("photo") != null) {
// Time to retrieve the photo
ParseFile getParseFile;
getParseFile = (ParseFile) data.get(i).get(0).get("photo");
rc.setPhoto(getParseFile);
}
richPostArrayList.add(rc);
adapter.notifyDataSetChanged();
}
}
}
}
});
}
#Override
public void onScrollStateChanged(AbsListView view, int scrollState){
this.currentScrollState = scrollState;
this.isScrollCompleted();
}
private void isScrollCompleted(){
if (this.currentVisibleItemCount >= 5 && this.currentScrollState == SCROLL_STATE_IDLE) {
}
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount){
this.currentVisibleItemCount = visibleItemCount;
if (firstVisibleItem + visibleItemCount == totalItemCount && totalItemCount != 0) {
if (flag_loading == false) {
flag_loading = true;
Log.d("IN ON SCROLL", "NOW: " + skipParam);
skipParam = skipParam + 10;
setContent();
}
}
// to determine scroll up or down
if (mLastFirstVisibleItem < firstVisibleItem) {
Log.i("SCROLLING DOWN", "TRUE");
// View c = listView.getChildAt(0);
// int scrolly = -c.getTop() + listView.getFirstVisiblePosition() * c.getHeight();
// Log.e("scrolly", "" + scrolly);
int scrolly = getItemHeightofListView(listView, firstVisibleItem);
Log.e("scrolly down", "" + scrolly);
//setting the cell height from total height - initial height
heightList.add(scrolly-initialHeight);
ArrayListGetterSetter test = new ArrayListGetterSetter();
test.setList(scrolly-initialHeight);
initialHeight = scrolly;
//hashMap.put(firstVisibleItem, "" + scrolly);
//Log.e("Item show",""+heightList.get(firstVisibleItem));
scrolling = true;
}
if (mLastFirstVisibleItem > firstVisibleItem) {
Log.i("SCROLLING UP", "TRUE");
// View c = listView.getChildAt(0);
// int scrolly = -c.getTop() + listView.getFirstVisiblePosition() * c.getHeight();
// Log.e("scrolly", "" + scrolly);
// int scrolly = getItemHeightofListView(listView, firstVisibleItem);
// Log.e("scrolly up", "" + scrolly);
if (firstVisibleItem <= heightList.size()) {
//getting the heights from the arraylist while scrolling up
//Log.e("Item show",""+heightList.get(firstVisibleItem));
position = firstVisibleItem;
}
}
mLastFirstVisibleItem = firstVisibleItem;
}
public static int getItemHeightofListView(ListView listView, int items) {
ListAdapter mAdapter = listView.getAdapter();
int listviewElementsheight = 0;
// for listview total item height
// items = mAdapter.getCount();
for (int i = 0; i < items; i++) {
View childView = mAdapter.getView(i, null, listView);
childView.measure(MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED), MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
listviewElementsheight+= childView.getMeasuredHeight();
}
return listviewElementsheight;
}
}
The adapter:
public class LazyObjectDrawingAdapter extends BaseAdapter {
PostListActivity postList = new PostListActivity();
RichPost rc = new RichPost();
Context mContext;
List<String> randomItems = new ArrayList<String>();
List<RichPost> richPostArrayList = new ArrayList<RichPost>();
private LayoutInflater inflater = null;
ArrayList<Integer> heightList = new ArrayList<Integer>();
public LazyObjectDrawingAdapter(Context context, List<String> contentComingIn, List<RichPost> richPostArrayList) {
this.mContext = context;
this.inflater = LayoutInflater.from(mContext);
this.randomItems = contentComingIn;
this.richPostArrayList = richPostArrayList;
}
// public LazyObjectDrawingAdapter(Context context, List<String> contentComingIn, List<RichPost> richPostArrayList, ArrayList<Integer> heightList) {
// this.mContext = context;
// this.inflater = LayoutInflater.from(mContext);
// this.randomItems = contentComingIn;
// this.richPostArrayList = richPostArrayList;
// this.heightList = heightList;
//
// }
#Override
public int getCount() {
//return 1;
//Log.i("GetCount size : ", " " + randomItems.size());
//return 1;
return randomItems.size();
}
#Override
public Object getItem(int position) {
return randomItems.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
View vi = convertView;
if (convertView == null) {
vi = inflater.inflate(R.layout.lazy_adapter, null);
holder = new ViewHolder();
setIds(vi, holder);
vi.setTag(holder);
} else {
holder = (ViewHolder) vi.getTag();
}
ArrayListGetterSetter test = new ArrayListGetterSetter();
Log.e("test.getSize()", ""+test.getSize());
//test.getListValues(position);
tryingNewClass(holder, vi, mContext, (String) randomItems.get(position), richPostArrayList.get(position));
return vi;
}
private void step1(String fromActivity) {
Log.d("Html output", "" + fromActivity);
}
private void step2(String html){
Document doc = Jsoup.parse(html);
Element element = doc.body();
Elements elements = element.select("img");
Log.w("Size of the elements ", " " + elements.size());
for(Element e : elements){
Log.d("step 2: ", "img: " + e.toString());
}
}
private void step2PicksUpWorks(String html){
Document doc = Jsoup.parse(html);
Elements imgs = doc.body().select("p");
for (Element e : imgs){
if(!e.toString().contentEquals("")){
Log.i("Img sources ", ": " + e.ownText());
}
}
}
private void tryingNewClass(ViewHolder holder, View view, Context context, String source, RichPost richPost){
//setting static height for testing, feel free to remove it anytime
int heightValue = 500;
holder.textToDraw.setMinHeight(heightValue + 200);
TestDrawableClass tdc = new TestDrawableClass(source, holder.textToDraw, context, holder.imageToDraw, richPost);
}
private void URLCombinedTest(int position, ViewHolder holder, View view, Context context, String source){
ImageView iv = new ImageView(context);
TextView tv = new TextView(context);
URLCombined uip = new URLCombined(position, iv, context, tv);
Spanned spanned = Html.fromHtml(source, uip, null);
tv.setText(spanned);
//holder.linearLayoutForImages.addView(iv);
holder.linearLayoutForImages.addView(tv);
}
/*
* Time to do the on draw
*/
private void lineByLine(int position, ViewHolder holder, View view, Context context, String source){
//Need to get line by line and then run it via the test parsers and add it to the layout dynmically via the ViewGrou parpent
Document doc = Jsoup.parse(source);
Element element = doc.body();
Elements ele = element.select("img");
for (int i = 0; i < ele.size(); i++) {
/* Log.w("For loop ", " " + i + " "+ ele.get(i).html());
Log.d("For loop ", " " + i + " "+ ele.get(i).text());
Log.i("For loop ", " " + i + " "+ ele.get(i));*/
addURLImageParser(position, holder, view, context, ""+ele.get(i));
}
Elements all = doc.select("b");
for (int i = 0; i < all.size(); i++) {
Log.i("For loop ", " " + i + " "+ all.get(i));
addURLTextParser(position, holder, view, context, ""+all.get(i));
}
Log.w("About to start a loop to check everything ", "now");
int imgValue = 0;
for (Element el:doc.select("body").select("*")) {
imgValue++;
// loop over all textnodes of these children
Log.i("Element siblings ", " " + el.nextElementSibling() + " " +imgValue);
Element tempElement = el.nextElementSibling();
if(el.nextElementSibling() == null){
Log.w("Element is null", "value is : " + el + " " + imgValue);
}
if(el.nextElementSibling() != null){
//Loop through the siblings.
if(el.nextElementSibling().hasText()){
//Log.d("Can we check any text after the fact ? ", " " + el);
//Log.e("Element has text: ", " " + el.nextElementSibling());
}
if(el.nextElementSibling().hasText() == false){
Elements elements = tempElement.select("img");
if(elements.isEmpty() == false){
//Log.e("Element text is false ", " " + elements);
}
}
}
imgValue = 0;
}
}
private void addURLTextParser(int position, ViewHolder holder, View view, Context context, String source){
Log.w("in add text url", "now");
TextView tv = new TextView(context);
URLTextParser utp = new URLTextParser(tv, context, 0);
Spanned spanned = Html.fromHtml(source, utp, null);
tv.setText(spanned);
holder.linearLayoutForImages.addView(tv);
//Now attach it the layout
}
private void addURLImageParser(int position, ViewHolder holder, View view, Context context, String source){
//Log.w("in add image url", "now");
ImageView iv = new ImageView(context);
URLImageParser uip = new URLImageParser(position, iv, context);
Spanned spanned = Html.fromHtml(source, uip, null);
holder.linearLayoutForImages.setId(position);
holder.linearLayoutForImages.addView(iv);
}
private void testURLTextParser(int position, ViewHolder holder, View view, Context context, String source){
//Lets just get text only
Document doc = Jsoup.parse(source);
Elements img = doc.body().select("p");
for (int i = 0; i < img.size(); i++) {
//Log.w("Checking null ", " " + img.get(i).text().contentEquals(""));
if( img.get(i).text().contentEquals("") == false){
Log.i("output : ", " " + img.get(i).text());
Log.d("Output2 ", " " + img.get(i).html());
URLTextParser utp = new URLTextParser(holder.textToDraw, context, 0);
Spanned spanned = Html.fromHtml(img.get(i).html(), utp, null);
holder.textToDraw.setText(spanned);
}
}
}
private void testURLImageParser(int position, ViewHolder holder, View view, Context context, String source){
//Log.d("In step 3 ", " Position : " + position);
//Lets do some crazy work right now. So lets start with just images. Make them 3 seperate ImageViews to draw
//Pos 0 has three images, but lets cycle throgh the mfirst
Document doc = Jsoup.parse(source);
Elements img = doc.body().select("img");
//Now we have all possible image 'source links'
for (int i = 0; i < img.size(); i++) {
//Lets loop through them one by one
Log.w("checking the output of the img ", "" + img.get(i).toString());
ImageView iv = new ImageView(context); //Create a holder for the images
URLImageParser uip = new URLImageParser(position, iv, context);
Spanned spanned = Html.fromHtml(img.get(i).toString(), uip, null);
holder.linearLayoutForImages.addView(iv);
}
}
private void setIds(View vi, ViewHolder holder) {
holder.textToDraw = (TextView) vi.findViewById(R.id.textOnly);
holder.imageToDraw = (ImageView) vi.findViewById(R.id.imageOnly);
holder.linearLayoutForImages = (LinearLayout) vi.findViewById(R.id.linearForImages);
}
static class ViewHolder {
TextView textToDraw;
ImageView imageToDraw;
Object objectCouldBeAnything;
Canvas toTry;
LinearLayout linearLayoutForImages;
}
}
Class ArrayListGetterSetter:
public class ArrayListGetterSetter {
ArrayList<Integer> heightList = new ArrayList<Integer>();
int valueFromList;
int size;
public int getListValues(int itemIndex) {
valueFromList = heightList.get(itemIndex);
return valueFromList;
}
public void setList(int value) {
heightList.add(value);
}
public int getSize(){
size = heightList.size();
return size;
}
}
Class TestDrawableClass:
Click to see the code
The
ArrayListGetterSetter test = new ArrayListGetterSetter();
Log.e("test.getSize()", ""+test.getSize());
in the LazyObjectDrawingAdapter is always returning 0. Thus querying the elements are causing null pointer exception. How can I get the height values?
in getItemId you should have returned position instead of zero.
#Override
public long getItemId(int position) {
return 0;
}
it should be :
#Override
public long getItemId(int position) {
return position;
}
i think this might help.

Categories