I know there are a lot of this kind of questions, but here is my problem.
I have a gallery with images and when I click, there is an ImageView to display the selected image in the gallery.
I also have a TextView witch displays a message.
When I click an image in the gallery, my ImageView gets the image and the TextTiew doesnt update its data.
I tried to put the code in a try/catch block and it doesn't throw any exception.
In my Log, the TextView has the exact text I have provided.
I tried using a new thread, but the result is the same: the TextView doesn't update, but my ImageView does.
I tried using runOnUiThread (as far as I know it's the same as a Thread), but still nothing.
I also changed from TextView to EditText, but I have the same problem.
Everyone says: "use a thread" - I did and it didn't work.
I ran out of ideas...
public class VODInterface extends Activity {
public static String[] values;
private static int itemPosition;
public static Activity thisActivity;
public Gallery gallery;
public ListView listView;
public LinearLayout MovieView;
public ImageView imgview;
public boolean submenus=false;
public boolean listviewVisibility = true;
private Handler handler = new Handler() ;
private SharedPreferences ep;
public ArrayList<VODObject> vod;
private ArrayList<Bitmap> tempimg;
private static int MovieSetNumber = 1;
public static int VODIndexPosition = 0;
public VODInterface(){
}
public void onDestroy(){
MainActivity.inChild=false;
super.onDestroy();
}
public void onCreate(Bundle bundle){
super.onCreate(bundle);
this.setContentView(R.layout.listview2);
ep = getSharedPreferences("Settings", 0);
listView = (ListView) this.findViewById(R.id.listView1);
MovieView = (LinearLayout) this.findViewById(R.id.movieView);
imgview = (ImageView)this.findViewById(R.id.imageView2);
// Defined Array values to show in ListView
values = new String[] { "A..Z",
"Category",
"Most Rated",
"Most Watched",
"Recently"
};
//this shows whitch movie should me load images
//we show always only 10 movies
MovieSetNumber = 1;
// Define a new Adapter
// First parameter - Context
// Second parameter - Layout for the row
// Third parameter - ID of the TextView to which the data is written
// Forth - the Array of data
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, android.R.id.text1, values);
// Assign adapter to ListView
listView.setAdapter(adapter);
// ListView Item Click Listener
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// ListView Clicked item index
itemPosition = position;
handler.post(goDeep);
}
});
}
private Runnable goDeep = new Runnable(){
public void run(){
new goDeep().execute("");
}
};
class goDeep extends AsyncTask<String, String, String>{
ProgressDialog mProgressDialog = new ProgressDialog(VODInterface.this);
String result="";
boolean failLoadVOD=false;
protected void onPreExecute(){
mProgressDialog.setMessage(getString(R.string.downloading));
mProgressDialog.setIndeterminate(true);
mProgressDialog.setCancelable(false);
mProgressDialog.show();
}
#Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
//START check if servers are Ok
if(!Server.isOnline()){
Server.getAvailableServer();
Log.i("good", "");
}
if(!Server.isOnline()){
Log.i("WEW", "SERVERS are off");
return null;
}
//END check if servers are Ok
//START synchronize local database with online database
try{
if(ep.contains("downloaded")){
Log.i("localDatabase", "is full");
}
else{
Editor ed = ep.edit();
ed.putString("downloaded", "");
ed.commit();
//load data from database
if(!MainActivity.web.parseVODAndVODCategories()){
failLoadVOD=true;
}
}
}
catch(NullPointerException ee)
{
//lets go get datas from Tibodatabase
Editor ed = ep.edit();
ed.putString("downloaded", "");
ed.commit();
if(!MainActivity.web.parseVODAndVODCategories()){
failLoadVOD=true;
}
}
//END synchronize local database with online database
//START handle menus
if(!submenus) //MainMenu
{
if(itemPosition == 1){
//get all movies ordered by name
List<String> val = MainActivity.voddb.selectAllCategories();
values = new String[val.size()+1];
values[0] ="[...]";
for(int i=0;i<val.size();i++){
values[i+1] = val.get(i);
}
listviewVisibility = true;
}
else{
//show movies
listviewVisibility = false;
}
submenus = true;
}
else{
if(itemPosition == 0){
values = new String[] { "A..Z",
"Category",
"Most Rated",
"Most Watched",
"Recently"
};
submenus = false;
listviewVisibility = true;
}
else{
listviewVisibility = false;
}
}
//END handle menu
if(!listviewVisibility){
getData();
for(int i=0;i<vod.size();i++){
if(!FileExciste(vod.get(i).Icon)){
try{
Bitmap bmp ;
URL newurl = new URL(vod.get(i).Icon);
bmp = BitmapFactory.decodeStream(newurl.openConnection() .getInputStream());
saveImageToSD(bmp,vod.get(i).Icon);
Log.i(i+"", "done");
}
catch(Exception e){
Log.i("exciste", "exciste");
}
}
else{
Log.i(i+"", "exciste");
}
}
}
runOnUiThread(new Runnable() {
#Override
public void run() {
if(!listviewVisibility){
listView.setVisibility(View.GONE);
MovieView.setVisibility(View.VISIBLE);
populateMovieView();
}
else{
ArrayAdapter<String> adapter = new ArrayAdapter<String>(VODInterface.this,
android.R.layout.simple_list_item_1, android.R.id.text1, values);
listView.setAdapter(adapter);
}
}
});
mProgressDialog.dismiss();
return "";
}
protected void onPostExecute(){
//start adding to cache
super.onPostExecute("");
}
}
private void getData(){
vod = new ArrayList<VODObject>();
for(int i=1;i<MainActivity.voddb.getVODCount()+1;i++){
vod.add(MainActivity.voddb.getVOD(i+""));
if(vod.get(i-1).Icon.contains(" ")){
vod.get(i-1).Icon = vod.get(i-1).Icon.replaceAll(" ", "%20");
Log.i("u korrigjua", vod.get(i-1).Icon);
}
}
}
private void populateMovieView(){
gallery = (Gallery) findViewById(R.id.gallery1);
GalleryImageAdapter gia= new GalleryImageAdapter(this,vod);
gallery.setAdapter(gia);
gallery.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, final int position, long id) {
// show the selected Image
/*here is the problem
*
*----------------------------/
*/
try{
LayoutInflater factory = getLayoutInflater();
View view = factory.inflate(R.layout.listview2, null);
EditText title = (EditText) view.findViewById(R.id.editText2);
title.setText(vod.get(position).title);
TextView desc = (TextView) view.findViewById(R.id.editText4);
desc.setText(vod.get(position).description);
Log.i("info", title.getText()+" "+desc.getText());
}
catch(Exception ee){
Log.i("info", ee.getMessage()+" nnn");
}
/*----------------------*/
try{
imgview.setImageBitmap(getImageFromSD(vod.get(position).Icon));
}
catch(Exception ee){
imgview.setImageResource(R.drawable.untitled);
}
}
});
}
public static Bitmap getImageFromSD(String url){
String path = Environment.getExternalStorageDirectory().toString();
File imgFile = new File(path+"/"+WebHelper.getFilenameFromUrl(url));
Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
return myBitmap;
}
private void saveImageToSD(Bitmap bmp,String url) throws IOException {
String path = Environment.getExternalStorageDirectory().toString();
OutputStream fOut = null;
File file = new File(path, "/"+WebHelper.getFilenameFromUrl(url));
fOut = new FileOutputStream(file);
bmp.compress(Bitmap.CompressFormat.JPEG, 100, fOut);
fOut.flush();
fOut.close();
MediaStore.Images.Media.insertImage(getContentResolver(),file.getAbsolutePath(),file.getName (),file.getName());
}
private boolean FileExciste(String url){
String path = Environment.getExternalStorageDirectory().toString();
File file = new File(path, "/"+WebHelper.getFilenameFromUrl(url));
return file.exists();
}
AND this is my XML
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#drawable/vod"
android:orientation="vertical" >
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="top" >
<ListView
android:id="#+id/listView1"
android:layout_width="274dp"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginBottom="20dp"
android:layout_marginLeft="20dp"
android:layout_marginTop="20dp"
android:background="#color/translucent_bblack" >
</ListView>
<LinearLayout
android:id="#+id/movieView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/translucent_black"
android:orientation="vertical"
android:visibility="invisible" >
<Gallery
android:id="#+id/gallery1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="20dp"
android:background="#color/translucent_bblack" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal" >
<ImageButton
android:id="#+id/imageView2"
android:layout_width="400dp"
android:layout_height="fill_parent"
android:layout_marginBottom="20dp"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:background="#drawable/bord" />
<LinearLayout
android:id="#+id/MovieDesc"
android:layout_width="match_parent"
android:layout_height="fill_parent"
android:layout_marginBottom="20dp"
android:layout_marginRight="20dp"
android:background="#color/translucent_bblack"
android:orientation="vertical" >
<TextView
android:id="#+id/editText1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="30dp"
android:layout_marginTop="30dp"
android:inputType="textPersonName"
android:text="Title:"
android:textColor="#FFFFFF"
android:textSize="20sp"
android:textStyle="bold" >
</TextView>
<TextView
android:id="#+id/editText2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="30dp"
android:textColor="#FFFFFF"
android:textSize="20sp"
android:textStyle="bold" />
<TextView
android:id="#+id/editText3"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="30dp"
android:layout_marginTop="30dp"
android:text="Description:"
android:textColor="#FFFFFF"
android:textSize="20sp"
android:textStyle="bold" />
<TextView
android:id="#+id/editText4"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="30dp"
android:textColor="#FFFFFF"
android:textSize="20sp"
android:textStyle="bold" />
<TextView
android:id="#+id/editText5"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="30dp"
android:layout_marginTop="60dp"
android:text="Duration:"
android:textColor="#FFFFFF"
android:textSize="20sp"
android:textStyle="bold" />
</LinearLayout>
</LinearLayout>
</LinearLayout>
</RelativeLayout>
Declare your TextViews as field as like as ImageView---- "imgview" as follows...
public ImageView imgview;
public TextView title;
public TextView desc;
Initialize them in onCreate method as "imgview"
imgview = (ImageView)this.findViewById(R.id.imageView2);
title = (TextView) view.findViewById(R.id.editText2);
desc = (TextView) view.findViewById(R.id.editText4);
And update your gallery.setOnItemClickListener code as follows...
gallery.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View v, final int position, long id) {
title.setText(vod.get(position).title);
desc.setText(vod.get(position).description);
Log.i("info", title.getText()+" "+desc.getText());
imgview.setImageBitmap(getImageFromSD(vod.get(position).Icon));
}
});
Related
I have an activity with CustomAdapter ListView and TabLayout with three tabs TrainerTab1, TrainerTab2, TrainerTab3. While clicking on an item it should move to next page that is to TrainerTab1 Fragment.
I need to pass the id from ListView onClick() to fragment page. I have used Bundle to pass value but the items are not working. When I click on an item it's not responding and not showing any error.
My custom ListView Class is:
public class Trainer extends AppCompatActivity {
String tabUrl = "http://adoxsolutions.in/numuww/services/trainers";
private GridView gridView;
ArrayList<HashMap<String, String>> alist = new ArrayList<>();
private TrainAdapter adapter;
private ProgressDialog mprogress;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_trainer);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setDisplayShowHomeEnabled(true);
new Train().execute();
}
private class Train extends AsyncTask<Void, Void, Void> {
protected void onPreExecute() {
mprogress = new ProgressDialog(Trainer.this);
mprogress.setMessage("Loading...");
mprogress.setIndeterminate(false);
mprogress.show();
}
#Override
protected Void doInBackground(Void... params) {
try {
URL url = new URL(tabUrl);
HttpURLConnection connect = (HttpURLConnection) url.openConnection();
connect.setRequestMethod("POST");
//
System.out.println("Response Code:" + connect.getResponseCode());
InputStream in = new BufferedInputStream(connect.getInputStream());
String response = org.apache.commons.io.IOUtils.toString(in, "UTF-8");
System.out.println(response);
Log.d("VALUE:", response);
JSONObject obj = new JSONObject(response);
JSONArray jsArray = obj.optJSONArray("Trainers");
for (int k = 0; k < jsArray.length(); k++) {
HashMap<String, String> map = new HashMap<String, String>();
obj = jsArray.getJSONObject(k);
map.put("id", obj.getString("id"));
map.put("name", obj.getString("name"));
map.put("logo", obj.getString("img"));
alist.add(map);
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void args) {
gridView = (GridView) findViewById(R.id.trainerGrid);
adapter = new TrainAdapter(getBaseContext(), alist);
gridView.setAdapter(adapter);
adapter.notifyDataSetChanged();
mprogress.dismiss();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.newc, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_search) {
return true;
}
else if(id == android.R.id.home){
onBackPressed();
return true;
}
return super.onOptionsItemSelected(item);
}
}
class TrainAdapter extends BaseAdapter {
private Context context;
private ArrayList<HashMap<String, String>> MyArr = new ArrayList<HashMap<String, String>>();
public TrainAdapter(Context c, ArrayList<HashMap<String, String>> list){
context = c;
MyArr = list;
}
#Override
public int getCount() {
return MyArr.size();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
if(convertView == null) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.trainer_list, null);
}
TextView id= (TextView) convertView.findViewById(R.id.trainerId);
ImageView image = (ImageView) convertView.findViewById(R.id.trainerImage);
TextView text = (TextView) convertView.findViewById(R.id.trainerTexts);
try {
image.setImageBitmap(loadBitmap(MyArr.get(position).get("logo")));
text.setText(MyArr.get(position).get("name"));
id.setText(MyArr.get(position).get("id"));
if (((position - 9) / 3) % 9 == 0) {
ImageView adimg = (ImageView) convertView.findViewById(R.id.trainadBanner);
adimg.setScaleType(ImageView.ScaleType.FIT_XY);
adimg.getLayoutParams().height=150;
adimg.getLayoutParams().width=300;
adimg.setImageResource(R.drawable.mainad);
}
} catch (Exception e) {
e.printStackTrace();
}
convertView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Bundle h=new Bundle();
h.putString("id",MyArr.get(position).get("id"));
Fragment tt1=new TrainerTab1();
tt1.setArguments(h);
}
});
// }else{
// convertView=inflater.inflate(R.layout.trainer_list, parent,false);
// ImageView image= (ImageView) convertView.findViewById(R.id.trainerImage);
// TextView text= (TextView) convertView.findViewById(R.id.trainerTexts);
// try{
// image.setImageResource(R.drawable.ic_action_name);
// text.setText(MyArr.get(position).get("name"));
// if(position % 9 == 0){
// ImageView adimg= (ImageView) convertView.findViewById(R.id.trainadBanner);
// adimg.setImageResource(R.drawable.mainad);
// }
//
// } catch(Exception e){
// e.printStackTrace();
// }
return convertView;
}
private static final String TAG = "ERROR";
private static final int IO_BUFFER_SIZE = 4 * 1024;
private static Bitmap loadBitmap(String tabUrl) {
Bitmap bitmap = null;
InputStream in = null;
BufferedOutputStream out = null;
try {
in = new BufferedInputStream(new URL(tabUrl).openStream(), IO_BUFFER_SIZE);
final ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
out = new BufferedOutputStream(dataStream, IO_BUFFER_SIZE);
copy(in, out);
out.flush();
final byte[] data = dataStream.toByteArray();
BitmapFactory.Options options = new BitmapFactory.Options();
//options.inSampleSize = 1;
bitmap = BitmapFactory.decodeByteArray(data, 0, data.length,options);
} catch (IOException e) {
Log.e(TAG, "Could not load Bitmap from: " + tabUrl);
} finally {
closeStream(in);
closeStream(out);
}
return bitmap;
}
private static void closeStream(Closeable stream) {
if (stream != null) {
try {
stream.close();
} catch (IOException e) {
android.util.Log.e(TAG, "Could not close stream", e);
}
}
}
private static void copy(InputStream in, OutputStream out) throws IOException {
byte[] b = new byte[IO_BUFFER_SIZE];
int read;
while ((read = in.read(b)) != -1) {
out.write(b, 0, read);
}
}
}
My tab fragment:
public class TrainerTab1 extends Fragment {
String turl="http://adoxsolutions.in/numuww/services/trainer";
TextView tname,tplace,tsex;
public TrainerTab1() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView= inflater.inflate(R.layout.fragment_trainer_tab1, container, false);
final String tid=getArguments().getString("id");
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
tname= (TextView) rootView.findViewById(R.id.trainerCourse);
tplace= (TextView) rootView.findViewById(R.id.trainerPlace);
tsex= (TextView) rootView.findViewById(R.id.trainerSex);
ImageView photo= (ImageView) rootView.findViewById(R.id.trainer_photo);
}
}
Inside the onClickListener
after adding the bundle to the fragment.
FragmentManager fragmentManager = Trainer.this.getSupportFragmentManager();
FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction.add(R.id.someIDForYourFrameLayout, tt1).commit();
can you just ellaborate where to use this exactly. I mean I don't understand how to add id of fragment to transaction.add(R.id.someIDForYourFrameLayout, tt1).commit();
I tried like this:
Bundle h=new Bundle();
h.putString("id",MyArr.get(position).get("id"));
Fragment tt1=new TrainerTab1();
tt1.setArguments(h);
FragmentTransaction transact=getSupportFragmentManager().beginTransaction();
transact.add(R.id.trainerFragment,tt1).commit();
This is my fragment_trainer_tab_1 layout:
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:scrollbars="vertical"
android:scrollbarSize="1dp"
android:id="#+id/trainerFragment"
tools:context="com.example.anu.numuww.TrainerTab1">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="12dp"
android:background="#color/blue">
<ImageView
android:id="#+id/trainer_photo"
android:layout_width="120dp"
android:layout_height="120dp"
android:layout_gravity="center"
android:contentDescription="#string/trainers"
android:src="#mipmap/ic_launcher"
android:layout_marginTop="20dp"/>
<TextView
android:id="#+id/trainerCourse"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text=""
android:layout_marginTop="12dp"
android:textColor="#ffffff"
android:textSize="22sp"
android:gravity="center"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:orientation="horizontal">
<TextView
android:id="#+id/trainerSex"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=""
android:layout_marginTop="5dp"
android:textColor="#ffffff"
android:textSize="17sp"
android:layout_gravity="center"/>
<TextView
android:id="#+id/trainerPlace"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=""
android:layout_marginLeft="5dp"
android:layout_marginTop="5dp"
android:textColor="#ffffff"
android:textSize="17sp"
android:gravity="center"/>
</LinearLayout>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#F5F5F5"
android:gravity="center_horizontal"
android:padding="7dp"
android:orientation="horizontal">
<ImageView
android:layout_width="38dp"
android:layout_height="38dp"
android:padding="2dp"
android:src="#drawable/global"/>
<ImageView
android:layout_width="38dp"
android:layout_height="38dp"
android:padding="2dp"
android:src="#drawable/messenger"/>
<ImageView
android:layout_width="38dp"
android:layout_height="38dp"
android:padding="2dp"
android:src="#drawable/google_plus"/>
<ImageView
android:layout_width="38dp"
android:layout_height="38dp"
android:padding="2dp"
android:src="#drawable/inst_detail"/>
<ImageView
android:layout_width="38dp"
android:layout_height="38dp"
android:padding="2dp"
android:src="#drawable/telegram"/>
<ImageView
android:layout_width="38dp"
android:layout_height="38dp"
android:padding="2dp"
android:src="#drawable/facebook"/>
<ImageView
android:layout_width="38dp"
android:layout_height="38dp"
android:padding="2dp"
android:src="#drawable/twitter"/>
<ImageView
android:layout_width="38dp"
android:layout_height="38dp"
android:padding="2dp"
android:src="#drawable/inst_instagram"/>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="14dp"
android:orientation="vertical">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="3dp"
android:text="About Trainer"
android:textColor="#color/blue"
android:textSize="19sp"
android:textStyle="bold"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="#string/para"
android:layout_marginTop="4dp"
android:layout_marginBottom="2dp"
android:textSize="14sp"/>
</LinearLayout>
</LinearLayout>
</ScrollView>
How i can display image into simple listview if this image is a bitmap
this void load a image in bitmap
private Bitmap loadImageFromStorage(String ImageName)
{
ContextWrapper cw = new ContextWrapper(mActivity.getApplicationContext());
// path to /data/data/yourapp/app_data/imageDir
File directory = cw.getDir("imageDir", Context.MODE_PRIVATE);
// Create imageDir
File path=new File(directory,ImageName+".jpg");
try {
Bitmap b = BitmapFactory.decodeStream(new FileInputStream(path));
// ImageView img=(ImageView)findViewById(R.id.imgPicker);
// img.setImageBitmap(b);
return b ;
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
return null;
}
this is layout from my single object into list
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="60dp"
android:padding="5dp"
>
<ImageView
android:layout_width="60dp"
android:layout_height="60dp"
android:background="#color/accent_material_dark"
style="#style/stile"
android:id="#+id/imageViewID" />
<LinearLayout
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_toEndOf="#+id/imageViewID">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Nome Gruppo"
android:id="#+id/NomeGruppo"
android:layout_alignParentTop="false"
android:layout_alignParentStart="true"
android:layout_alignParentBottom="false"
android:layout_centerHorizontal="true"
android:layout_gravity="center_horizontal"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#000000" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#Gruppo"
android:id="#+id/IDgruppo"
android:layout_below="#+id/NomeGruppo"
android:layout_centerInParent="true"
android:layout_gravity="center_horizontal"
android:textColor="#6b6f6e" />
</LinearLayout>
this is my old method for load listview without image
private void visualizzaRisultati(){
final List<Map<String, String>> lista = readDb();
String[] from = {"NomeGruppo", "IDgruppo"}; //dai valori contenuti in queste chiavi
int[] to = {R.id.NomeGruppo, R.id.IDgruppo};//agli id delle view
SimpleAdapter adapter = new SimpleAdapter(
mActivity.getApplicationContext(),
lista,//sorgente dati
R.layout.visualizza_ris_ric_gruppo, //layout contenente gli id di "to"
from,
to);
final ListView mylist = (ListView) getActivity().findViewById(R.id.listaGruppi);
mylist.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, final int position, long arg3) {
Intent nuovaPagina = new Intent(mActivity, gruppo.class);
nuovaPagina.putExtra("nomeGruppo", lista.get(position).get("IDgruppo").toString());
startActivity(nuovaPagina);
}
});
mylist.setAdapter(adapter);
}
protected List<Map<String, String>> readDb(){
SQLiteDatabase db;
db = getActivity().openOrCreateDatabase("utenteDB", Context.MODE_PRIVATE, null);
Cursor resultSet = db.rawQuery("Select * from gruppo",null);
List<Map<String, String>> lista = new ArrayList<Map<String, String>>();
if (resultSet.moveToFirst()) {
do {
final String idgruppo = resultSet.getString(0);
final String nomeGruppo =resultSet.getString(1);
lista.add(new HashMap<String, String>() {
{
put("NomeGruppo", nomeGruppo);
put("IDgruppo", idgruppo);
}
});
} while (resultSet.moveToNext());
}
return(lista);
}
how i can upgrade this method for load an image into layout for listview
Here is an example. NB: this is not a tutorial site
private class MyCustomAdapter extends BaseAdapter {
#Override
public int getCount() {
return yourDataset.size();
}
#Override
public String getItem(int position) {
return yourdata;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
//inflate your layout , bind data
}
}
I want to give a little context: The app I'm currently involved in helping develop is an app a company has already developed for IOS and Android but the Android developer didn't delivered the expected results (mostly performance wise) so the leader gave me the code to see if I could fix it. Given the code I tried to improve it, now, the app is a picture sharing app somewhat like Instagram and it uses and endless scrolling list, the problem with the app is that every time I scroll a little bit, the app lags or freezes for a second and then loads a new row.
The listview only has one row visible at any moment.
What have I tried?:
The adapter wasn't using the ViewHolder pattern so I tried to implement it.
The programmer was defining a lot of click listeners on the getView method so I removed them.
still, every time I scroll ( a new row appears as there's only one visible row at any time) it lags. Are there any other noticeable problems here that could be the cause?
On another note, on this view there's a lot of overdraw so, maybe it's affecting the performance on the ListView? if so, tell me and I'll post the XML part.
Here's the code I adapted:
public class SomeFragment extends Fragment implements SwipeRefreshLayout.OnRefreshListener {
// declaration and constructors.....
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
//initialization......
//setting variables.......
//getting views.....
listview = (ListView)rootView.findViewById(R.id.listview);
listview.setOnScrollListener(new AbsListView.OnScrollListener() {
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
int threshold = 1;
int count = listview.getCount();
if (scrollState == SCROLL_STATE_IDLE) {
if (listview.getLastVisiblePosition() >= count - threshold) {
int position = listview.getLastVisiblePosition();
if (!loading) {
loading = true;
listview.addFooterView(footerView, null, false);
currentVal = position + 1;
LoadMoreStuffAsyncTask loadMoreStuffAsyncTask = new LoadMoreStuffAsyncTask();
loadMoreStuffAsyncTask.execute();
}
}
}
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
int topRowVerticalPosition = (listview == null || listview.getChildCount() == 0) ? 0 : listview.getChildAt(0).getTop();
swipeRefreshLayout.setEnabled(firstVisibleItem == 0 && topRowVerticalPosition >= 0);
}
});
LoadStuffAsyncTask loadStuffAsyncTask=new LoadStuffAsyncTask();
loadStuffAsyncTask.execute();
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.activity, container, false);
swipeRefreshLayout = (SwipeRefreshLayout)rootView.findViewById(R.id.swipe);
swipeRefreshLayout.setOnRefreshListener(SomeFragment.this);
return rootView;
}
private void LoadStuff () {
list=null;
ParseQuery<ParseObject> query = null;
query = ParseQuery.getQuery("Objects");
query.orderByDescending("createdAt");
query.include("User");
query.setLimit(20);
try {
list = query.find();
} catch (ParseException e) {
e.printStackTrace();
}
}
private void LoadMoreStuff () {
List<ParseObject> moreList=null;
ParseQuery<ParseObject> query = null;
query = ParseQuery.getQuery("Objects");
query.orderByDescending("createdAt");
query.include("User");
query.setLimit(20);
query.setSkip(currentVal);
try {
moreList = query.find();
if(moreList!=null|| moreList.size()!=0){
for(int i =0;i<moreList.size();i++){
list.add(moreList.get(i));
}
}else{
loading=false;
}
} catch (ParseException e) {
e.printStackTrace();
loading=false;
}
}
#Override
public void onRefresh() {
swipeRefreshLayout.setRefreshing(true);
listAdapter.notifyDataSetChanged();
LoadStuffAsyncTask loadStuffAsyncTask=new LoadStuffAsyncTask();
loadStuffAsyncTask.execute();
}
class LoadMoreStuffAsyncTask extends AsyncTask<Void, Void, Void>{
private ProgressDialog pDialog;
#Override
protected Void doInBackground(Void... params) {
LoadMoreStuff();
return null;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
listAdapter.updateList(list);
listview.setAdapter(listAdapter);
loading=false;
listview.removeFooterView(footerView);
listview.setSelection(currentVal);
}
}
class LoadStuffAsyncTask extends AsyncTask<Void, Void, Void>{
private ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(activity);
pDialog.setMessage(activity.getString(R.string.loading));
pDialog.setCancelable(false);
pDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
pDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
LoadStuff();
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
pDialog.dismiss();
swipeRefreshLayout.setRefreshing(false);
listAdapter = new CustomAdapter(activity,momentosGeneral);
listview.setAdapter(listAdapter);
}
}
}
This is the adapter:
public class CustomAdapter extends BaseAdapter {
//declaration of variables.....
public CustomAdapter(ActionBarActivity activity, List<ParseObject> list) {
this.activity = activity;
this.list = list;
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
private static class ViewHolder{
//holderfields......
}
#Override
public View getView(final int position, View v, ViewGroup parent) {
ViewHolder holder;
if (v == null) {
v = View.inflate(activity.getApplicationContext(), R.layout.customview, null);
holder = new ViewHolder();
holder.profilepicture = (CircularImageView) v.findViewById(R.id.profilepic);
holder.username = (TextView) v.findViewById(R.id.username);
holder.picture = (ParseImageView) v.findViewById(R.id.picture);
holder.container =(LinearLayout)v.findViewById(R.id.container);
holder.share=(LinearLayout)v.findViewById(R.id.share);
holder.comment= (TextView) v.findViewById(R.id.comment);
holder.likes= (TextView) v.findViewById(R.id.likes);
holder.publishDate =(TextView)v.findViewById(R.id.publisdate);
holder.liked = (ImageView)v.findViewById(R.id.liked);
v.setTag(holder);
}
holder = (ViewHolder)v.getTag();
CustomTypography customTypo = new CustomTypography(activity.getApplicationContext());
holder.username.setTypeface(customTypo.OpenSansSemibold());
if(list.get(position).getParseUser("User")!=null){
holder.username.setText(list.get(position).getParseUser("User").getString("name"));
profilePic = list.get(position).getParseUser("User").getParseFile("profilePic");
if (profilePic != null) {
try {
Drawable drawable = new BitmapDrawable(BitmapFactory.decodeByteArray(profilePic.getData(), 0, profilePic.getData().length));
holder.profilepicture.setImageDrawable(drawable);
holder.profilepicture.setDrawingCacheEnabled(true);
} catch (Exception e) {
e.printStackTrace();
}
}
}
else{
holder.username.setText("");
}
final ParseFile picture = list.get(position).getParseFile("picture");
if (picture != null) {
try {
Drawable drawable = new BitmapDrawable(BitmapFactory.decodeByteArray(picture.getData(), 0, picture.getData().length));
holder.picture.setImageDrawable(drawable);
holder.picture.setDrawingCacheEnabled(true);
} catch (Exception e) {
e.printStackTrace();
}
}
else{
}
holder.container.setLayoutParams(customLayoutParams);
holder.comment.setText(capitalizarPrimeraLetra(list.get(postiion).getString("Comment")));
holder.comment.setTypeface(customTypo.OpenSansRegular());
final int likes= list.get(position).getInt("Likes");
if(likes==0|| likes<0){
holder.likes.setText("");
}else{
holder.likes.setText(String.valueOf(likes));
}
holder.likes.setTypeface(customTypo.OpenSansLight());
holder.publishDate.setText(timeBetween(list.get(position).getCreatedAt()));
ParseQuery<ParseObject> query = ParseQuery.getQuery("LikedPictures");
query.whereEqualTo("picture", list.get(position));
query.whereEqualTo("user", currentUser);
query.findInBackground(new FindCallback<ParseObject>() {
public void done(List<ParseObject> likelist, ParseException e) {
if (e == null) {
if (likelist.size() != 0) {
hasLiked = true;
holder.liked.setBackground(activity.getApplicationContext().getResources().getDrawable(R.drawable.like));
holder.likes.setTextColor(activity.getApplicationContext().getResources().getColor(R.color.red));
} else {
hasLiked = false;
}
} else {
hasLiked = false;
}
}
});
return v;
}
private String timeBetween(Date date){
String result="";
Date parsedPictureDate = null;
Date parsedCurrentDate=null;
Date today = new Date();
SimpleDateFormat dateFormatGmt = new SimpleDateFormat("yyyy-MMM-dd HH:mm:ss");
dateFormatGmt.setTimeZone(TimeZone.getTimeZone("GMT"));
SimpleDateFormat dateFormatLocal = new SimpleDateFormat("yyyy-MMM-dd HH:mm:ss");
try {
parsedPictureDate= dateFormatLocal.parse(dateFormatGmt.format(date));
parsedCurrentDate=dateFormatLocal.parse(dateFormatGmt.format(hoy));
} catch (java.text.ParseException e) {
result="";
}
long milis=parsedCurrentDate.getTime()-parsedPictureDate.getTime();
final long MILISECS_PER_MINUTE=milis/(60 * 1000);
final long MILISECS_PER_HOUR=milis/(60 * 60 * 1000);
final long MILLSECS_PER_DAY=milis/(24 * 60 * 60 * 1000);
if(milis<60000){
result="Now";
}
if(milis>=60000&&milis<3600000){
result=MILISECS_PER_MINUTE+" min";
}
if(milis>=3600000&&milis<86400000){
result=MILISECS_PER_HOUR+" h";
}
if(milis>=86400000){
result=MILLSECS_PER_DAY+" d";
}
return result;
}
This is the item that always gets populated in the listview
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="vertical" android:layout_width="match_parent"
android:background="#android:color/white"
android:paddingBottom="20dp"
android:layout_height="match_parent">
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content">
<LinearLayout
android:id="#+id/somelayout"
android:layout_weight="0.5"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_marginTop="#dimen/margin_16dp_sw600"
android:layout_marginLeft="5dp"
android:paddingRight="#dimen/padding_16dp_sw600"
android:gravity="left"
android:layout_marginBottom="5dp">
<customImageView
android:layout_gravity="center"
android:layout_width="50dp"
android:layout_height="50dp"
android:id="#+id/profilepicture"
app:border_width="0dp"
/>
<TextView
android:layout_marginLeft="#dimen/margin_16dp_sw600"
android:layout_gravity="center"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/username"
android:textSize="14sp"
android:gravity="left"
android:singleLine="true"
android:minLines="1"
android:maxLines="1"
android:lines="1"
/>
</LinearLayout>
<LinearLayout
android:id="#+id/layoutTime"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:gravity="right"
android:layout_weight="0.5"
android:layout_gravity="center" >
<TextView
android:gravity="right"
android:id="#+id/publishdate"
android:layout_marginRight="#dimen/margin_16dp_sw600"
android:textSize="14sp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
</LinearLayout>
</LinearLayout>
<LinearLayout
android:paddingLeft="5dp"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<LinearLayout
android:id="#+id/container"
android:layout_gravity="center"
android:background="#drawable/border"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
>
<com.parse.ParseImageView
android:layout_margin="1dp"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/picture" />
</LinearLayout>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
>
<LinearLayout
android:id="#+id/layoutlikes"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:gravity="left"
android:layout_weight="0.5"
android:layout_gravity="center" >
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:id="#+id/likes"
>
<TextView
android:layout_gravity="center"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/numlikes"
android:text="0"
android:textSize="14sp"
android:layout_margin="#dimen/margin_16dp_sw600"
/>
<ImageView
android:layout_gravity="center"
android:layout_marginRight="#dimen/margin_16dp_sw600"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/likepic"
android:background="#drawable/like_off"
/>
</LinearLayout>
</LinearLayout>
<LinearLayout
android:id="#+id/sharelayout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:gravity="right"
android:padding="10dp"
android:layout_weight="0.5"
android:layout_marginTop="#dimen/margin_16dp_sw600"
android:layout_gravity="center" >
<ImageView
android:layout_gravity="center"
android:layout_marginRight="#dimen/margin_16dp_sw600"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/sharepic"
android:background="#drawable/ellipsis"
/>
</LinearLayout>
</LinearLayout>
<View
android:layout_width="match_parent"
android:layout_height="#dimen/division_2dp_sw_600"
android:layout_margin="#dimen/margin_16dp_sw600"
android:background="#color/loading" />
<TextView
android:layout_gravity="left"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/comment"
android:textSize= "14sp"
android:layout_marginLeft="#dimen/margin_16dp_sw600"
android:layout_marginRight="#dimen/margin_16dp_sw600"
/>
</LinearLayout>
Your biggest performance hit is probably the code below. You should use some sort of caching rather than decoding the Bitmap each time.
if (profilePic != null) {
try {
Drawable drawable = new BitmapDrawable(BitmapFactory.decodeByteArray(profilePic.getData(), 0, profilePic.getData().length));
holder.profilepicture.setImageDrawable(drawable);
holder.profilepicture.setDrawingCacheEnabled(true);
} catch (Exception e) {
e.printStackTrace();
}
Also, you are creating a new CustomTypography instance everytime getView() is called. I assume this class extends Typeface, in which case you could just use a single instance that gets initialised in the adapter's constructor.
Here are a couple of things:
1. in your adapter.getView() method, move the
holder = (ViewHolder)v.getTag();
to if/else scope:
if(view ==null){
//creation of viewHolder
}else{
holder = (ViewHolder)v.getTag();
}
2. There is too much code in the adapter.getView(), specially the parse query. You better call it once per item, by caching the result of query for each item in adapter. It is currently being called on every item get visible on scroll.
3. Try to reduce the count of views in your item's xml. Too many views in ListView items cause in memory leak and low performance.
4. Adding the hardwareAccelerated="true" to your activity in manifest might help.
5. Try to comment out the scroll listener, to find out if it is reducing the performance.
I have retrieved data from a remote db using json and i have created a custom listView with this data. I have three TextView and one CheckBox and it works perfectly. So, i have added a button that would control selected items in list and eventually transfer selected item in another activity. Problem was solved as suggested,but if i scroll list, selected items losts status.I think it depends from horder or adapter. Can someone help me? Here is my code
public class Activity2 extends ActionBarActivity implements OnItemClickListener {
TextView txtLavorante;
TextView txtCodice;
Intent currIntent;
ListView list;
String myJSON;
ArrayList <String> checkedValue;
private ProgressDialog pDialog;
private static final String TAG_RESULTS="result";
private static final String TAG_ID = "ID";
private static final String TAG_NAME = "Descrizione";
private static final String TAG_PRICE ="Costo";
private static final String TAG_TIME ="Durata_m";
JSONArray serv_man = null;
ArrayList<HashMap<String, String>> list_serv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_activity2);
list = (ListView) findViewById(R.id.listView);
currIntent = getIntent();
txtLavorante = (TextView) findViewById (R.id.Lavorante);
txtCodice = (TextView) findViewById(R.id.CodiceLavorante);
stampaValori();
list_serv = new ArrayList<HashMap<String,String>>();
getData();
}
#Override
public void onItemClick(AdapterView arg0, View v, int position, long arg3) {
CheckBox cb = (CheckBox) v.findViewById(R.id.checkBox);
TextView tv = (TextView) v.findViewById(R.id.textView);
cb.performClick();
if (cb.isChecked()) {
checkedValue.add(tv.getText().toString());
Log.i("Btn Test",""+checkedValue);
} else if (!cb.isChecked()) {
checkedValue.remove(tv.getText().toString());
}
}
private void stampaValori() {
String pkg = getApplicationContext().getPackageName();
String tCode = "ID: " + currIntent.getStringExtra(pkg + "ID") + "\n";
String tNome = "Collaboratore scelto: " + currIntent.getStringExtra(pkg + "LAV") + "\n";
txtLavorante.setText(tNome);
txtCodice.setText(tCode);
}
protected void showList(){
try {
JSONObject jsonObj = new JSONObject(myJSON);
serv_man = jsonObj.getJSONArray(TAG_RESULTS);
for(int i=0;i<serv_man.length();i++){
JSONObject c = serv_man.getJSONObject(i);
String id = c.getString(TAG_ID);
String name = c.getString(TAG_NAME);
String price = c.getString(TAG_PRICE);
String time = c.getString(TAG_TIME);
HashMap<String,String> persons = new HashMap<String,String>();
persons.put(TAG_ID,id);
persons.put(TAG_NAME,name);
persons.put(TAG_PRICE,price);
persons.put(TAG_TIME,time);
list_serv.add(persons);
}
list = (ListView) findViewById(R.id.listView);
list.setAdapter(new ListatoAdapter(Activity2.this, list_serv));
list.setOnItemClickListener(Activity2.this);
Button b= (Button) findViewById(R.id.button);
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
// Toast.makeText(Activity2.this, "TEST" + checkedValue, Toast.LENGTH_LONG).show();
Log.i ("Test ",""+checkedValue);
}
});
} catch (JSONException e) {
e.printStackTrace();
}
}
public void getData(){
class GetDataJSON extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams());
HttpPost httppost = new HttpPost("http://www.example.com/.php");
// Depends on your web service
httppost.setHeader("Content-type", "application/json");
InputStream inputStream = null;
String result = null;
try {
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
inputStream = entity.getContent();
// json is UTF-8 by default
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
result = sb.toString();
Log.i ("Servizi","serv:"+result);
} catch (Exception e) {
// Oops
Log.e("log_tag", "Error converting result " + e.toString());
}
finally {
try{if(inputStream != null)inputStream.close();}catch(Exception squish){}
}
return result;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Activity2.this);
pDialog.setMessage("Obtaining list...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected void onPostExecute(String result){
pDialog.dismiss();
myJSON=result;
showList();
}
}
GetDataJSON g = new GetDataJSON();
g.execute();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_activity2, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
ListatoAdapter
public class ListatoAdapter extends BaseAdapter {
private LayoutInflater layoutinflater;
private Context context;
ArrayList<HashMap<String, String>> dataList;
boolean [] itemChecked;
public ListatoAdapter(Context context, ArrayList<HashMap<String, String>> list_serv) {
super();
this.context = context;
this.dataList = list_serv;
itemChecked = new boolean [dataList.size()];
}
#Override
public int getCount() {
return dataList.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = inflater.inflate(R.layout.prenota_serv, null);
holder = new ViewHolder();
holder.service = (TextView)convertView.findViewById(R.id.et_serv);
holder.id = (TextView)convertView.findViewById(R.id.et_id);
holder.costo = (TextView)convertView.findViewById(R.id.et_costo);
holder.durata = (TextView)convertView.findViewById(R.id.et_dur);
holder.Ceck = (CheckBox)convertView.findViewById(R.id.checkBox);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.service.setText(dataList.get(position).get("Descrizione"));
holder.id.setText(dataList.get(position).get("ID"));
holder.costo.setText(dataList.get(position).get("Costo"));
holder.durata.setText(dataList.get(position).get("Durata_m"));
holder.Ceck.setChecked(false);
if (itemChecked[position])
holder.Ceck.setChecked(true);
else
holder.Ceck.setChecked(false);
holder.Ceck.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (holder.Ceck.isChecked())
itemChecked[position] = true;
else
itemChecked[position] = false;
Log.i("Adapter Test",""+itemChecked[position]);
}
});
return convertView;
}
class ViewHolder {
TextView service;
TextView id;
TextView costo;
TextView durata;
CheckBox Ceck;
}
}
Activity2.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context="net.puntosys.www.customadaptertest.Activity2"
android:orientation="vertical">
<TextView android:text="hello_word" android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/Lavorante"
android:textStyle="bold"
android:textSize="22dp" />
<Button
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="New Button"
android:id="#+id/button"
android:layout_gravity="right" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="Small Text"
android:id="#+id/CodiceLavorante"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:visibility="invisible" />
<ListView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:id="#+id/listView" />
prenota_serv.xml
<?xml version="1.0" encoding="utf-8"?>
<TextView
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="Servizio:"
android:textSize="7pt"
android:id="#+id/tv_serv"
android:layout_alignBottom="#+id/tv_id"
android:layout_alignLeft="#+id/tv_id"
android:layout_alignStart="#+id/tv_id" />
<EditText
android:background="#android:drawable/editbox_background"
android:layout_height="wrap_content"
android:layout_width="190dip"
android:id="#+id/et_serv"
android:layout_gravity="center_horizontal"
android:textSize="7pt"
android:layout_alignBottom="#+id/et_id"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
<TextView
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="Costo Euro:"
android:textSize="7pt"
android:id="#+id/tv_cost"
android:layout_below="#+id/et_serv"
android:layout_alignLeft="#+id/tv_serv"
android:layout_alignStart="#+id/tv_serv" />
<EditText
android:background="#android:drawable/editbox_background"
android:layout_height="wrap_content"
android:layout_width="120dip"
android:id="#+id/et_costo"
android:layout_gravity="center_horizontal"
android:layout_below="#+id/et_serv"
android:layout_alignLeft="#+id/et_serv"
android:layout_alignStart="#+id/et_serv"
android:textSize="7pt" />
<TextView
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="Durata min:"
android:textSize="7pt"
android:id="#+id/tv_dur"
android:layout_below="#+id/et_costo"
android:layout_alignLeft="#+id/tv_cost"
android:layout_alignStart="#+id/tv_cost" />
<EditText
android:background="#android:drawable/editbox_background"
android:layout_height="wrap_content"
android:layout_width="70dip"
android:id="#+id/et_dur"
android:layout_gravity="center_horizontal"
android:textSize="7pt"
android:layout_alignTop="#+id/tv_dur"
android:layout_alignLeft="#+id/et_costo"
android:layout_alignStart="#+id/et_costo" />
<TextView
android:layout_marginTop="5dip"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="Nr:"
android:layout_marginLeft="5dip"
android:layout_marginRight="9dip"
android:layout_alignParentLeft="true"
android:textSize="10pt"
android:id="#+id/tv_id"
android:visibility="invisible" />
<EditText
android:background="#android:drawable/editbox_background"
android:layout_height="wrap_content"
android:layout_width="70dip"
android:id="#+id/et_id"
android:layout_gravity="center_horizontal"
android:layout_alignTop="#+id/tv_id"
android:layout_alignLeft="#+id/et_serv"
android:layout_alignStart="#+id/et_serv"
android:enabled="false"
android:elegantTextHeight="false"
android:visibility="invisible" />
<CheckBox
android:id="#+id/checkBox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:focusable="false"
android:focusableInTouchMode="false"
android:text="CheckBox"
android:layout_below="#+id/tv_dur"
android:layout_alignRight="#+id/et_serv"
android:layout_alignEnd="#+id/et_serv" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="Small Text"
android:id="#+id/textView"
android:layout_alignParentBottom="true"
android:layout_alignLeft="#+id/tv_dur"
android:layout_alignStart="#+id/tv_dur" />
when user select a check box, put its corresponding data to a list.and send the list in bundle on button click.and receive it on another activity with the key.
you need to create a list like.
ArrayList<HashMap<String, String>> list_selected;
public ListatoAdapter(Context context, ArrayList<HashMap<String, String>> list_serv) {
super();
this.context = context;
this.dataList = list_serv;
list_selected = new ArrayList<HashMap<String, String>>();
}
change the listener as.
holder.Ceck.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
HashMap<String,String> data = dataList.get(position);
if(isChecked){
addToSelected(data);
}else{
removeSelected(data);
}
}
});
private void addToSelected(HashMap contact){
if(!list_selected.contains(contact))list_selected.add(contact);
}
private boolean removeSelected(HashMap contact){
return list_selected.remove(contact);
}
public ArrayList<HashMap<String, String>> getSelectedItems(){
return list_selected;
}
access the list from activity as adapter.getSelectedItems();.
declare it in your activity as global
ListatoAdapter adapter;
set adapter in this way.
adapter = new ListatoAdapter(Activity2.this, list_serv);
list.setAdapter(adapter);
and get the list in button Click as.
ArrayList<HashMap<String,String> list = adapter.getSelectedItems();
From what I can gather it appears that this might be because my ListView is not being displayed, I've verified that getCount is returning a value not zero, but I can't see what I'm doing wrong.
Everything loads and acts like it's working but the ListView never appears, I put a background color on the fragment reference in mixed.xml and it is there and taking up the full screen, but when I set a background color on my ListView it does not appear, it's like it's not being rendered at all.
More odd, getView is not being called in my adapter, and this is all working code from regular activities that I ported to fragments.
I've tried calling notifyDataSetChanged which didn't changed anything, debugging shows the adapter is filled with data and getCount is indeed returning an accurate count greater than 0.
Thanks for any help, I'm stuck.
Project is open and can be viewed here http://code.google.com/p/shack-droid/source/browse/#svn%2FTrunk but I'm also including the pertinent code here.
This is the ListFragment:
public class FragmentTopicView extends ListFragment implements ShackGestureEvent {
private ArrayList<ShackPost> posts;
private String storyID = null;
private String errorText = "";
private Integer currentPage = 1;
private Integer storyPages = 1;
private String loadStoryID = null;
private Boolean threadLoaded = true;
private Hashtable<String, String> postCounts = null;
private AdapterLimerifficTopic tva;
public FragmentTopicView() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
this.setRetainInstance(true);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.topics, null);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
final ShackGestureListener listener = Helper.setGestureEnabledContentView(R.layout.topics, getActivity());
if (listener != null) {
listener.addListener(this);
}
if (savedInstanceState == null) {
// get the list of topics
GetChattyAsyncTask chatty = new GetChattyAsyncTask(getActivity());
chatty.execute();
}
ListView lv = getListView();
lv.setOnScrollListener(new OnScrollListener() {
#Override
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
// start loading the next page
if (threadLoaded && firstVisibleItem + visibleItemCount >= totalItemCount && currentPage + 1 <= storyPages) {
// get the list of topics
currentPage++;
GetChattyAsyncTask chatty = new GetChattyAsyncTask(getActivity());
chatty.execute();
}
}
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
}
});
}
class GetChattyAsyncTask extends AsyncTask<String, Void, Void> {
protected ProgressDialog dialog;
protected Context c;
public GetChattyAsyncTask(Context context) {
this.c = context;
}
#Override
protected Void doInBackground(String... params) {
threadLoaded = false;
try {
final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(c);
final String feedURL = prefs.getString("shackFeedURL", getString(R.string.default_api));
final URL url;
if (loadStoryID != null) {
if (currentPage > 1)
url = new URL(feedURL + "/" + loadStoryID + "." + currentPage.toString() + ".xml");
else
url = new URL(feedURL + "/" + loadStoryID + ".xml");
}
else {
if (currentPage > 1)
url = new URL(feedURL + "/" + storyID + "." + currentPage.toString() + ".xml");
else
url = new URL(feedURL + "/index.xml");
}
// Get a SAXParser from the SAXPArserFactory.
final SAXParserFactory spf = SAXParserFactory.newInstance();
final SAXParser sp = spf.newSAXParser();
// Get the XMLReader of the SAXParser we created.
final XMLReader xr = sp.getXMLReader();
// Create a new ContentHandler and apply it to the XML-Reader
SaxHandlerTopicView saxHandler = new SaxHandlerTopicView(c, "topic");
xr.setContentHandler(saxHandler);
// Parse the xml-data from our URL.
xr.parse(new InputSource(HttpHelper.HttpRequestWithGzip(url.toString(), c)));
// Our ExampleHandler now provides the parsed data to us.
if (posts == null) {
posts = saxHandler.GetParsedPosts();
}
else {
ArrayList<ShackPost> newPosts = saxHandler.GetParsedPosts();
newPosts.removeAll(posts);
posts.addAll(posts.size(), newPosts);
}
storyID = saxHandler.getStoryID();
storyPages = saxHandler.getStoryPageCount();
if (storyPages == 0) // XML returns a 0 for stories with only
// one page
storyPages = 1;
}
catch (Exception ex) {
// TODO: implement error handling
}
return null;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
if (currentPage == 1)
dialog = ProgressDialog.show(getActivity(), null, "Loading Chatty", true, true);
else
SetLoaderVisibility(View.VISIBLE);
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
ShowData();
SetLoaderVisibility(View.GONE);
try {
dialog.dismiss();
}
catch (Exception e) {
}
}
}
private void ShowData() {
if (posts != null) {
Hashtable<String, String> tempHash = null;
final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
final String login = prefs.getString("shackLogin", "");
final int fontSize = Integer.parseInt(prefs.getString("fontSize", "12"));
try {
postCounts = GetPostCache();
}
catch (Exception ex) {
}
if (postCounts != null)
tempHash = new Hashtable<String, String>(postCounts);
if (tva == null) {
tva = new AdapterLimerifficTopic(getActivity(), R.layout.lime_topic_row, posts, login, fontSize, tempHash);
setListAdapter(tva);
}
else {
tva.SetPosts(posts);
tva.notifyDataSetChanged();
}
final ListView lv = getListView();
lv.setOnCreateContextMenuListener(new OnCreateContextMenuListener() {
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
menu.setHeaderTitle("Options");
menu.add(0, 1, 0, "Copy Post Url to Clipboard");
menu.add(0, 2, 0, "Watch Thread");
menu.add(0, 3, 0, "Thread Expires In?");
menu.add(0, 4, 0, "Shacker's Chatty Profile");
}
});
// update the reply counts for the listing of topics
try {
UpdatePostCache();
}
catch (Exception e) {
}
}
else {
if (errorText.length() > 0) {
try {
new AlertDialog.Builder(getActivity()).setTitle("Error").setPositiveButton("OK", null).setMessage(errorText).show();
}
catch (Exception ex) {
// could not create a alert for the error for one reason
// or another
Log.e("ShackDroid", "Unable to create error alert ActivityTopicView:468");
}
}
}
threadLoaded = true;
}
}
Here's my FragmentActivity:
public class FragmentActivityTopic extends FragmentActivity {
#Override
protected void onCreate(Bundle arg) {
// TODO Auto-generated method stub
super.onCreate(arg);
setContentView(R.layout.mixed);
}
}
This is the Adapter I'm using, and as mentioned above getView is not being called:
public class AdapterLimerifficTopic extends BaseAdapter {
// private Context context;
private List<ShackPost> topicList;
private final int rowResouceID;
private final String shackLogin;
private final Typeface face;
private final int fontSize;
private final Hashtable<String, String> postCache;
private final String showAuthor;
private final Resources r;
private int totalNewPosts = 0;
LayoutInflater inflate;// = LayoutInflater.from(context);
public AdapterLimerifficTopic(Context context, int rowResouceID, List<ShackPost> topicList, String shackLogin, int fontSize, Hashtable<String, String> postCache) {
this.topicList = topicList;
this.rowResouceID = rowResouceID;
this.shackLogin = shackLogin;
this.fontSize = fontSize;
this.postCache = postCache;
this.r = context.getResources();
face = Typeface.createFromAsset(context.getAssets(), "fonts/arial.ttf");
final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
showAuthor = prefs.getString("showAuthor", "count");
inflate = LayoutInflater.from(context);
}
public void SetPosts(List<ShackPost> posts)
{
topicList = posts;
}
#Override
public int getCount() {
return topicList.size();
}
#Override
public Object getItem(int position) {
return topicList.get(position);
}
#Override
public long getItemId(int position) {
// return position;
final ShackPost post = topicList.get(position);
return Long.parseLong(post.getPostID());
}
static class ViewHolder {
TextView posterName;
TextView datePosted;
TextView replyCount;
TextView newPosts;
TextView postText;
TextView viewCat;
RelativeLayout topicRow;
ImageView postTimer;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TextView tmp;
// final View v;
ViewHolder holder;
final ShackPost post = topicList.get(position);
if (convertView == null) {
convertView = inflate.inflate(rowResouceID, parent, false);
holder = new ViewHolder();
holder.posterName = (TextView) convertView.findViewById(R.id.TextViewLimeAuthor);
holder.datePosted = (TextView) convertView.findViewById(R.id.TextViewLimePostDate);
holder.replyCount = (TextView) convertView.findViewById(R.id.TextViewLimePosts);
holder.newPosts = (TextView) convertView.findViewById(R.id.TextViewLimeNewPosts);
holder.postText = (TextView) convertView.findViewById(R.id.TextViewLimePostText);
holder.viewCat = (TextView) convertView.findViewById(R.id.TextViewLimeModTag);
// holder.topicRow = (RelativeLayout) convertView.findViewById(R.id.TopicRow);
// holder.postTimer = (ImageView) convertView.findViewById(R.id.ImageViewTopicTimer);
// holder.posterName.setTypeface(face);
// holder.datePosted.setTypeface(face);
// holder.replyCount.setTypeface(face);
// holder.newPosts.setTypeface(face);
holder.postText.setTextSize(TypedValue.COMPLEX_UNIT_SP, fontSize);
// holder.postText.setTypeface(face);
convertView.setTag(holder);
}
else {
holder = (ViewHolder) convertView.getTag();
}
// holder.postTimer.setImageResource(Helper.GetTimeLeftDrawable(post.getPostDate()));
//
holder.posterName.setText(post.getPosterName());
//
// if (shackLogin.equalsIgnoreCase(post.getPosterName()))
// holder.posterName.setTextColor(Color.parseColor("#00BFF3"));
// else
// holder.posterName.setTextColor(Color.parseColor("#ffba00"));
//
holder.datePosted.setText(Helper.FormatShackDateToTimePassed(post.getPostDate()));
holder.replyCount.setText(post.getReplyCount());
//
// if (showAuthor.equalsIgnoreCase("count") && post.getIsAuthorInThread())
// holder.replyCount.setTextColor(Color.parseColor("#0099CC"));
// else
// holder.replyCount.setTextColor(Color.parseColor("#FFFFFF"));
// clipped code
holder.postText.setText(preview);
// if (showAuthor.equalsIgnoreCase("topic") && post.getIsAuthorInThread()) {
// final Drawable d = r.getDrawable(R.drawable.background_gradient_blue);
// holder.topicRow.setBackgroundDrawable(d);
// }
// else
// holder.topicRow.setBackgroundDrawable(null);
// TODO: clean this up a little / also replicated in ShackDroidThread ick
final String postCat = post.getPostCategory();
holder.viewCat.setVisibility(View.VISIBLE);
if (postCat.equals("offtopic")) {
holder.viewCat.setText("offtopic");
holder.viewCat.setBackgroundColor(Color.parseColor("#444444"));
}
else if (postCat.equals("nws")) {
holder.viewCat.setText("nws");
holder.viewCat.setBackgroundColor(Color.parseColor("#CC0000"));
}
else if (postCat.equals("political")) {
holder.viewCat.setText("political");
holder.viewCat.setBackgroundColor(Color.parseColor("#FF8800"));
}
else if (postCat.equals("stupid")) {
holder.viewCat.setText("stupid");
holder.viewCat.setBackgroundColor(Color.parseColor("#669900"));
}
else if (postCat.equals("informative")) {
holder.viewCat.setText("interesting");
holder.viewCat.setBackgroundColor(Color.parseColor("#0099CC"));
}
else
holder.viewCat.setVisibility(View.GONE);
return convertView;
}
public int getTotalNewPosts() {
return totalNewPosts;
}
}
And related XML:
mixed.xml (this is the layout for the fragments, only the one for now)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal"
android:id="#+id/LinearLayoutMixed">
<fragment
android:id="#+id/MixedThreads"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
class="com.stonedonkey.shackdroid.FragmentTopicView"
>
</fragment>
</LinearLayout>
Topics.xml (this contains the ListView as well as a sliding tray and some other stuff.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<ListView
android:id="#android:id/list"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_above="#+id/TopicLoader"
android:divider="#333333"
android:dividerHeight="1dip"
android:textColor="#FFFFFF"
/>
<RelativeLayout
android:id="#+id/TopicLoader"
android:layout_width="fill_parent"
android:layout_height="35dip"
android:layout_alignParentBottom="true"
android:gravity="center_horizontal"
android:visibility="gone"
android:layout_marginTop="5dip" >
<TextView
android:id="#+id/TextViewTopicLoaderText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:focusable="false"
android:focusableInTouchMode="false"
android:text="Loading"
>
</TextView>
<ImageView
android:id="#+id/ImageViewTopicLoader"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="#+id/TextViewTopicLoaderText"
android:src="#drawable/ic_action_refresh"
android:layout_alignBottom="#+id/TextViewTopicLoaderText"
/>
</RelativeLayout>
<SlidingDrawer
android:id="#+id/SlidingDrawer01"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_below="#+id/TopicLoader"
android:animateOnClick="true"
android:content="#+id/bookMarkParent"
android:handle="#+id/TextViewTrayHandle"
android:orientation="vertical"
android:paddingTop="200dip"
android:visibility="gone" >
<TextView
android:id="#+id/TextViewTrayHandle"
android:layout_width="fill_parent"
android:layout_height="35dip"
android:background="#drawable/darkgrey_gradient"
android:focusable="false"
android:focusableInTouchMode="false"
android:gravity="center_vertical" >
</TextView>
<RelativeLayout
android:id="#id/bookMarkParent"
android:layout_width="wrap_content"
android:layout_height="wrap_content" >
<ListView
android:id="#+id/ListViewWatchedThreads"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:divider="#333333"
android:dividerHeight="1dip"
android:textColor="#FFFFFF" >
</ListView>
</RelativeLayout>
</SlidingDrawer>
</RelativeLayout>
and finally lime_topic_row which is my custom row layout for the ListView in the above layout:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#FF0000" >
<TextView
android:id="#+id/TextViewLimeModTag"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#FF0000"
android:layout_alignParentLeft="true"
android:layout_marginLeft="10dip"
android:textColor="#000000"
android:padding="2dip"
android:textSize="10dip"
/>
<TextView
android:id="#+id/TextViewLimePostText"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:minHeight="20dip"
android:padding="10dip"
android:layout_below="#+id/TextViewLimeModTag"
android:textColor="#FFFFFF" />
<TextView
android:id="#+id/TextViewLimeAuthor"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/TextViewLimePostText"
android:paddingBottom="10dip"
android:paddingLeft="10dip"
android:textColor="#0099CC" />
<TextView
android:id="#+id/TextViewPosted"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/TextViewLimePostText"
android:layout_toRightOf="#+id/TextViewLimeAuthor"
android:paddingBottom="10dip"
android:text=" posted " />
<TextView
android:id="#+id/TextViewLimePostDate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/TextViewLimePostText"
android:layout_toRightOf="#+id/TextViewPosted"
android:paddingBottom="10dip"
android:paddingRight="10dip"
android:textColor="#FF8800" />
<TextView
android:id="#+id/TextViewLimePosts"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/TextViewLimePostDate"
android:layout_marginRight="3dip"
android:layout_below="#+id/TextViewLimePostText"
android:layout_marginBottom="15dip"
android:layout_toLeftOf="#+id/TextViewLimeNewPosts"
android:background="#BBBBBB"
android:padding="3dip"
android:minWidth="25dip"
android:gravity="center"
android:textColor="#000000" />
<TextView
android:id="#+id/TextViewLimeNewPosts"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/TextViewLimePostDate"
android:layout_below="#+id/TextViewLimePostText"
android:layout_marginBottom="15dip"
android:layout_marginRight="10dip"
android:background="#669900"
android:padding="3dip"
android:minWidth="25dip"
android:gravity="center"
android:layout_alignParentRight="true"
android:textColor="#000000" />
</RelativeLayout>
I think I found the problem. The issue appears because of the ShackGestureListener that you setup at the start of the onActivityCreated method in the FragmentTopicView:
final ShackGestureListener listener = Helper.setGestureEnabledContentView(R.layout.topics, getActivity());
if (listener != null) {
listener.addListener(this);
}
In the setGestureEnabledContentView() method you check to see if the user enabled the gestures in the preferences or if the android version is bigger then 3. Either way, true or false you set the content view for the FragmentActivityTopic again(with the layout of the FragmentTopicView). Setting the content view again will, unfortunately, cover the current layout which holds the ListView with data(ListView that populates with no problems). When you run those AsyncTasks to get the data, at the end you set the data on the correct ListView(returned by getListView) because the getListView will hold a reference to the old correct ListView which was set in the onCreateView method, but you don't see anything because in the setGestureEnabledContentView you cover this ListView.
This behavior is easy to see if you simple comment out(or remove) the lines that set the content view for the activity in the Helper and HelperAPI4 classes. Another way to see that your ListView is covered is, for example to set the adapter for the ListView(tva) using getListView and using the getActivity().findViewById(android.R.id.list)(I've done this on selecting one of your menus items, so I can control when I replace the adapter):
#Override
public boolean onOptionsItemSelected(MenuItem item) {
Intent intent;
switch (item.getItemId())
{
case R.id.topic_menu_newpost: // Launch post form
//this doesn't work as the getListView will return a reference to the old ListView
ListView lv = getListView();
lv.setAdapter(tva);
// this will work as you get a reference to the new ListView on top
ListView lv = (ListView) getActivity().findViewById(android.R.id.list);
lv.setAdapter(tva);
I don't know what to recommend as a solution as I don't quite understand what you're doing, but I doubt that it requires to set the content view for the activity again(and you should work from this).