I have a ListView in an activity. The list elements are generated from a BaseAdapter. The list is continously growing as the user scrolls down on the screen. Actually an AsyncTask is responsibe to download data from the internet and generate the View elements for the ListView.
Each View element has a set onClickListener. The OnClickListener class starts a new activity...
The problem is that sometimes the GUI does not react on the click action.
e.g.
1. start the app
2. tap on the first element -> nothing happens
3. tap on the 2nd element -> nothing happens
4. scroll down a but -> both corresponding activities appear (on each other)
ListAdapter:
private class HirdetesListaAdapter extends BaseAdapter {
private GSResult hirdetesek;
private final Context context;
private LayoutInflater inflater = null;
private SparseArray<ImageDownloaderThread> imageDownloadThreads;
private ListViewWorker worker;
private int thresHold = 45;
private ArrayList<View> views;
private boolean isWorkerThreadRunning = false;
public HirdetesListaAdapter(final Context context, GSResult result) throws IOException {
this.context = context;
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
initAdapter(result);
}
public void initAdapter(GSResult result) {
if (views == null) {
views = new ArrayList<View>();
} else {
views.clear();
}
hirdetesek = result;
imageDownloadThreads = new SparseArray<ImageDownloaderThread>();
worker = new ListViewWorker();
worker.execute(null, null, null);
}
#Override
public int getCount() {
// Log.v("bar2", "HirdetesListaAdapter.getCount()=" + views.size());
return views.size();
}
#Override
public GSHirdetes getItem(int arg0) {
Log.v("bar", "HirdetesListaAdapter.getItem(" + arg0 + ")");
// Toast.makeText(getBaseContext(), "Találatok: " + gsr.size(),
// 100000).show();
return hirdetesek.get(arg0);
}
public void destroy() {
synchronized (worker) {
worker.notify();
Log.v("thread", "Working thread notified");
worker.cancel(true);
Log.v("thread", "Working thread cancelled");
for (int i = 0; i < this.imageDownloadThreads.size(); i++) {
imageDownloadThreads.get(i).cancel(false);
Log.v("thread", "ImageDownloadThread " + i + " cancelled");
}
}
}
#Override
public long getItemId(int arg0) {
Log.v("bar", "HirdetesListaAdapter.getItemId(" + arg0 + ")");
return arg0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if ((lv.getLastVisiblePosition() + thresHold) > views.size()) {
synchronized (worker) {
if (!this.isWorkerThreadRunning) {
Log.v("wthread", "Resuming worker thread");
worker.notify();
isWorkerThreadRunning = true;
}
}
}
synchronized (imageDownloadThreads) {
if (imageDownloadThreads.get(position) == null) {
Log.v("ithread", "Storing download thread: " + position);
ImageDownloaderThread thread = new ImageDownloaderThread();
imageDownloadThreads.put(position, thread);
thread.execute(position);
}
}
Log.v("thread", "getview finished for " + position);
return views.get(position);
}
private class ListViewWorker extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... arg0) {
Log.v("thread", "ListViewWorker started");
int buffer = 20;
int i = 0;
try {
while ((views.size() != gsr.size()) && !this.isCancelled()) {
Log.v("thread", views.size() + "/" + gsr.size());
if (buffer != 0) {
views.add(i, makeView(i));
ResultActivity.this.runOnUiThread(new Runnable() {
public void run() {
lv.addFooterView(views.get(views.size() - 1));
}
});
i++;
buffer--;
} else {
synchronized (this) {
try {
Log.v("wthread", "Pausing worker thread");
buffer = 20;
this.wait();
HirdetesListaAdapter.this.isWorkerThreadRunning = false;
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
private View makeView(int position) {
Log.v("thread", "ListViewWorker.makeView(" + position + ")");
GSHirdetes hirdetes = hirdetesek.get(position);
View hirdetesView = inflater.inflate(R.layout.hirdetes_listaelem, null);
TextView hirdetesName = (TextView) hirdetesView.findViewById(R.id.hirdetesListaElemView_TextView_Name);
TextView hirdetesAr = (TextView) hirdetesView.findViewById(R.id.hirdetesListaElemView_TextView_Ar);
TextView hirdetesKategoria = (TextView) hirdetesView.findViewById(R.id.hirdetesListaElemView_TextView_Kategoria);
hirdetesName.setText(position + ". " + hirdetes.getHirdetesName());
// hirdetesName.setText(Integer.toString(position));
hirdetesAr.setText(hirdetes.getHirdetesPrice());
hirdetesKategoria.setText(hirdetes.getCategory());
ImageView hirdetesImage = (ImageView) hirdetesView.findViewById(R.id.hirdetesListaElemView_ImageView_HirdetesCover);
//hirdetesImage.setOnClickListener(new HirdetesImageListener(context, hirdetes));
//hirdetesView.setOnClickListener(new HirdetesListaListener(context, hirdetes));
//views.add(position, hirdetesView);
Log.v("gui", "ListViewWorker.makeView(" + position + ") finished");
return hirdetesView;
}
}
private class ImageDownloaderThread extends AsyncTask<Integer, Integer, Bitmap> {
private ProgressBar progressBar;
private TextView percent;
private URL imageUrl;
private View view;
private int sorszám = -1;
public void onPreExecute() {
super.onPreExecute();
// while (threadCounter >= threadPool) {
// try {
// Log.v("konti","threadCounter:"+threadCounter+" threadPool:"+threadPool);
// Thread.sleep(10);
// } catch (InterruptedException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
//
// }
//
// threadCounter++;
}
public void onProgressUpdate(Integer... values) {
progressBar.setProgress(values[0]);
float percentValue = (float) progressBar.getProgress() / progressBar.getMax();
DecimalFormat df = new DecimalFormat("#");
String percentString = df.format(percentValue * 100) + "%";
percent.setText(percentString);
// Log.v("konti", percentString);
}
#Override
protected Bitmap doInBackground(Integer... params) {
sorszám = params[0];
imageUrl = hirdetesek.get(sorszám).gethirdetesCoverImageUrl();
view = views.get(sorszám);
progressBar = (ProgressBar) view.findViewById(R.id.hirdetesListaElemView_ProgressBar_ImageDLProgressBar);
progressBar.setIndeterminate(false);
progressBar.setProgress(0);
percent = (TextView) view.findViewById(R.id.hirdetesListaElemView_TextView_ImageDLPercent);
if (imageUrl == null) {
return null;
}
Log.v("thread", "Starting ImageDownloaderThread for " + sorszám);
int size;
try {
size = imageUrl.openConnection().getContentLength();
progressBar.setMax(size);
InputStream is = imageUrl.openStream();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer = new byte[2048];
int read = 0;
Log.v("gui", "Downloading image for " + sorszám + ": " + imageUrl.getPath());
while ((read = is.read(buffer, 0, buffer.length)) != -1) {
baos.write(buffer, 0, read);
// Log.v("net", "Image download progress: " +
// baos.size());
publishProgress(progressBar.getProgress() + read);
}
baos.flush();
byte[] data = baos.toByteArray();
return BitmapFactory.decodeByteArray(data, 0, data.length);
} catch (IOException e) {
Log.v("exception", "thread");
return null;
}
}
protected void onPostExecute(Bitmap bitmap) {
ResultActivity.this.runOnUiThread(new Runnable() {
public void run() {
ViewGroup vg = (ViewGroup) (progressBar.getParent());
vg.removeView(progressBar);
vg.removeView(percent);
}
});
ImageView im = (ImageView) view.findViewById(R.id.hirdetesListaElemView_ImageView_HirdetesCover);
if (bitmap == null) {
im.setImageResource(R.drawable.noimage_hu);
} else {
im.setImageBitmap(bitmap);
}
}
}
}
Listener:
public class HirdetesListaListener implements View.OnClickListener {
GSHirdetes hirdetes;
Context context;
public HirdetesListaListener(Context context, GSHirdetes hirdetes){
this.hirdetes = hirdetes;
this.context = context;
Log.v("konti","Listener: "+hirdetes.getHirdetesName());
}
#Override
public void onClick(View v) {
Log.v("konti","HirdetesListaListener.onClick(v) "+hirdetes.getHirdetesName());
Intent intent = new Intent(context, HirdetesActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra("data", hirdetes);
context.startActivity(intent);
}
}
you should use this code:
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
Toast.makeText(MainActivity.this, "item at pos "+arg2+" clicked", Toast.LENGTH_LONG).show();
}
});
Related
Problem with "list" the counter is greater than the number of elements within the
This is filled by the response of a server.
public class ListQuestions extends Activity{
private ListQuestionsAdapter adapter;
ListView listquestion;
List<ResponseQuestionDto> questions = new ArrayList<>();
List<ResponseQuestionDto> questionsSelected;
int positionQuestion;
final Handler mHandler = new Handler();
ProgressDialog dialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
try{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_listquestions);
dialog = ProgressDialog.show(this, "",
getString(R.string.progress), true);
Thread thread = new Thread() {
#Override
public void run() {
try {
questions = BusinessLogic.getQuestions(LiveCookie.getInstance().getToken());
mHandler.post(mUpdate);
} catch (Exception e) {
Util.alert(ListQuestions.this, getString(R.string.Error));
}
}
};
thread.start();
}catch (Exception e)
{
Toast.makeText(ListQuestions.this, getString(R.string.Error), Toast.LENGTH_LONG).show();
}
}
final Runnable mUpdate = new Runnable() {
#Override
public void run() {
try {
dialog.dismiss();
questionsSelected = LiveCookie.getInstance().getQuestionsSelected();
positionQuestion = LiveCookie.getInstance().getPositionQuestion();
try {
if(questionsSelected != null)
{
for (int i=0;i<questionsSelected.size();i++) {
if (questionsSelected != null) {
if (questionsSelected.get(i).pregunta != null) {
if (positionQuestion != i) {
for (int e = 0; e < questions.size(); e++) {
if (questions.get(e) != null) {
if (questions.get(e).pregunta.equals(questionsSelected.get(i).pregunta)) {
questions.remove(questions.get(e));
}
}
}
}
}
}
}
}
}catch (Exception e)
{
//Not Used
}
listquestion = (ListView) findViewById(R.id.listquestion);
adapter = new ListQuestionsAdapter(ListQuestions.this,questions);
listquestion.setAdapter(adapter);
listquestion.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> adapter2, View v, int position, long id) {
questionsSelected = LiveCookie.getInstance().getQuestionsSelected();
ResponseQuestionDto selected = questions.get(position);
positionQuestion = LiveCookie.getInstance().getPositionQuestion();
questionsSelected.set(positionQuestion,selected);
LiveCookie.getInstance().setQuestionsSelected(questionsSelected);
ListQuestions.this.finish();
}});
}catch (Exception e)
{
dialog.dismiss();
Toast.makeText(ListQuestions.this, getString(R.string.Error), Toast.LENGTH_LONG).show();
ListQuestions.this.finish();
}
}
};
}
At first the list is 14 but when I check it in the "setOnItemClickListener" this is 18.
enter image description here
you have to put all code, and where is the code affect the problem?
as well you check before getting data from the list to avoid this problem
if(counter<=list.size-1){
//put your code
}
In a list view i have image, text and image contains default image when list load with download complete , every thing works fine but when keyboard opens the downloaded image change to default image.
public class ChatScreen extends Activity implements OnClickListener
{
private void stopTimer()
{
if (mTimer1 != null)
{
mTimer1.cancel();
mTimer1.purge();
}
}
private void startTimer()
{
mTimer1 = new Timer();
mTt1 = new TimerTask()
{
public void run()
{
mTimerHandler.post(new Runnable()
{
public void run()
{
try
{
Date date1 = getDate(time);
Date date2 = getDate(getCurrentTime());
if (date2.getTime() - date1.getTime() == 5000)
{
stopTimer();
try
{
chat.setCurrentState(ChatState.paused,
chatWithJID, FromChatJID);
} catch (XMPPException e)
{
e.printStackTrace();
}
isTyping = false;
}
else if (date2.getTime() - date1.getTime() > 30000)
{
time = getCurrentTime();
try
{
chat.setCurrentState(ChatState.gone,
chatWithJID, FromChatJID);
} catch (XMPPException e)
{
e.printStackTrace();
}
isTyping = false;
}
}
catch (ParseException e)
{
e.printStackTrace();
}
catch(IllegalStateException e)
{
e.printStackTrace();
}
}
});
}
};
mTimer1.schedule(mTt1, 00, 5000);
}
#Override
protected void onPause()
{
super.onPause();
chat.setChatFragment(null);
System.out.println("onPasue called");
}
}
}
}
}
}
#Override
protected void onResume()
{
super.onResume();
session.saveCurrentName(this.getLocalClassName());
chat.setChatFragment(ctx);
System.out.println("onResume called");
if(checkForCurfew())
showHideView(true, 0);
else
showHideView(false, 0);
}
public void showHideView(final boolean value, final int type)
{
System.out.println("Called");
runOnUiThread(new Runnable()
{
#Override
public void run()
{
if(value)
{
btnSend.setEnabled(value);
btnSend.setAlpha(1.0f);
inputMessage.setEnabled(value);
btnSticker.setEnabled(value);
btnSticker.setAlpha(1.0f);
btnPicture.setEnabled(value);
btnPicture.setAlpha(1.0f);
doodle_btn.setEnabled(value);
doodle_btn.setAlpha(1.0f);
}
else
{
btnSend.setEnabled(value);
btnSend.setAlpha(0.5f);
inputMessage.setEnabled(value);
btnSticker.setEnabled(value);
btnSticker.setAlpha(0.5f);
btnPicture.setEnabled(value);
btnPicture.setAlpha(0.5f);
doodle_btn.setEnabled(value);
doodle_btn.setAlpha(0.5f);
}
if(!value && type == 0)
inputMessage.setHint("You can't chat during a curfew");
else if(!value && type == 1)
inputMessage.setHint("Can’t Access Internet");
else
inputMessage.setHint("Enter message here");
}
});
}
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
System.gc();
setContentView(R.layout.activity_fragment_chat);
System.out.println("Chat screen called.");
mcon = ChatScreen.this;
chat = ((RooChat) getApplication()).chat;
Bundle bundle = getIntent().getBundleExtra("bundle_data");
System.out.println("bundle- " + bundle);
chatWithJID = bundle.getString("chat_with");
chatWithName = bundle.getString("kid_name");
FromChatJID = bundle.getString("chat_from");
ChatRoomName = bundle.getString("chat_room");
indexOfChatRoom = Integer.parseInt(bundle.getString("index"));
CopyindexOfChatRoom = indexOfChatRoom;
typeFaceCurseCasual = AppFonts.getFont(mcon, AppFonts.CurseCasual);
typeFaceARLRDBDHand = AppFonts.getFont(mcon, AppFonts.ARLRDBDHand);
back = (Button) findViewById(R.id.back);
sendBtn=(Button)findViewById(R.id.send);
sendBtn.setOnClickListener(this);
erasebtn=(Button)findViewById(R.id.erase);
erasebtn.setOnClickListener(this);
smallers=(Button)findViewById(R.id.small_ers1);
smallers.setOnClickListener(this);
mediumers=(Button)findViewById(R.id.medium_ers1);
mediumers.setOnClickListener(this);
largeers=(Button)findViewById(R.id.large_ers1);
largeers.setOnClickListener(this);
smallline=(Button)findViewById(R.id.small);
smallline.setOnClickListener(this);
mediumline=(Button)findViewById(R.id.medium);
mediumline.setOnClickListener(this);
largeline=(Button)findViewById(R.id.large);
largeline.setOnClickListener(this);
back1=(Button)findViewById(R.id.back1);
back1.setOnClickListener(this);
drawView=(DrawingView)findViewById(R.id.Drawing);
doodle_btn=(Button)findViewById(R.id.doodle_btn);
doodle_btn.setOnClickListener(this);
doodle=(LinearLayout) findViewById(R.id.doodle);
back.setOnClickListener(this);
init();
String available = convertAvailability(chat.getUserAvailability(chatWithJID));
if (chatWithName.equalsIgnoreCase("echo") || chatWithName.equalsIgnoreCase("puzzle")
|| chatWithName.equalsIgnoreCase("msr"))
{
image.setImageResource(R.drawable.status_active);
}
else if (available.equalsIgnoreCase("offline"))
{
chat.sendIQForLastSeen(chatWithJID);
image.setImageResource(R.drawable.status_offline);
}
else
{
// chatState.setText(available);
image.setImageResource(R.drawable.status_active);
}
inputMessage.addTextChangedListener(new TextWatcher()
{
#Override
public void onTextChanged(CharSequence s, int start, int before, int count)
{
if (chat.isConnected())
{
try
{
time = getCurrentTime();
}
catch (ParseException e1)
{
e1.printStackTrace();
}
if (isTyping == false)
{
try
{
chat.setCurrentState(ChatState.composing, chatWithJID, FromChatJID);
isTyping = true;
startTimer();
}
catch (XMPPException e)
{
e.printStackTrace();
}
}
else if (isTyping == true)
{
stopTimer();
startTimer();
}
}
/*else
Toast.makeText(getApplicationContext(), "Please wait, connecting to server.", 0).show();
*/
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after)
{
}
#Override
public void afterTextChanged(Editable s)
{
}
});
inputMessage.setOnFocusChangeListener(new OnFocusChangeListener()
{
#Override
public void onFocusChange(final View v, final boolean hasFocus)
{
if (hasFocus && inputMessage.isEnabled() && inputMessage.isFocusable())
new Runnable()
{
#Override
public void run()
{
final InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(inputMessage, InputMethodManager.SHOW_IMPLICIT);
}
};
}
});
data = session.getUserDetails();
banned = session.getBannedWord();
System.out.println(banned);
JSONArray jsonArray;
if(!banned.equals(""))
{
try
{
jsonArray = new JSONArray(banned);
strArr = new String[jsonArray.length()];
for (int i = 0; i < jsonArray.length(); i++)
{
strArr[i] = jsonArray.getString(i);
}
//System.out.println(Arrays.toString(strArr));
}
catch (JSONException e)
{
e.printStackTrace();
}
}
}
}
public void reFreshData()
{
indexOfChatRoom = db.getChatRoomIndex(chatWithName);
messages = db.getFriendChat(indexOfChatRoom);
adapter = new ChatMessageAdapter(mcon, messages);
chatList.setAdapter(adapter);
}
private void init()
{
db = new DatabaseHelper(mcon);
ctx = this;
chat.setChatFragment(ctx);
session = new SessionManager(mcon);
chatList = (ListView) findViewById(R.id.chatList);
chatWith = (TextView) findViewById(R.id.chat_with);
doodle_txt = (TextView) findViewById(R.id.doodle_txt);
chatState = (TextView) findViewById(R.id.chat_status);
btnPicture = (TextView) findViewById(R.id.picture);
btnPicture.setOnClickListener(this);
btnSticker = (TextView) findViewById(R.id.sticker);
btnSticker.setOnClickListener(this);
btnExtra = (TextView) findViewById(R.id.extra);
btnExtra.setOnClickListener(this);
btnSend = (TextView) findViewById(R.id.btn_send);
btnSend.setTypeface(typeFaceARLRDBDHand, Typeface.BOLD);
btnSend.setOnClickListener(this);
inputMessage = (EditText) findViewById(R.id.et_message);
inputMessage.setTypeface(typeFaceCurseCasual);
chatWith.setText(chatWithName);
image = (ImageView) findViewById(R.id.img_chat_status);
cross = (ImageView) findViewById(R.id.cross);
cross.setOnClickListener(this);
lay_sticker_main = (LinearLayout) findViewById(R.id.lay_sticker_main);
lay_sticker_child = (FlowLayout) findViewById(R.id.lay_sticker_child);
lay_sticker_group = (FlowLayout) findViewById(R.id.lay_sticker_group);
reFreshData();
chatList.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, final View arg1, final int arg2,
long arg3) {
// TODO Auto-generated method stub
final ChatMessage msg=adapter.getItem(arg2);
final ImageView btn = (ImageView) arg1.findViewById(R.id.textView1);
final ImageView imgone = (ImageView)arg1.findViewById(R.id.imagev);
try{
if(!btn.getTag().toString().equals("")){
Log.v("","msg getting:..."+btn.getTag().toString());
DownloadImage di=new DownloadImage(ChatScreen.this, btn.getTag().toString(), new BitmapAsyncTaskCompleteListener() {
#Override
public void onTaskComplete(Bitmap result) {
// TODO Auto-generated method stub
Log.v("Img :",""+result);
imgone.setImageBitmap(result);
String filePath=saveImage(result,msg.getId(),msg.getFrom());
btn.setVisibility(View.GONE);
btn.setTag(filePath);
final int index = chatList.getFirstVisiblePosition();
View v = chatList.getChildAt(0);
final int top = (v == null) ? 0 : v.getTop();
Log.v("", "top :.."+top);
chatList.post(new Runnable() {
#Override
public void run() {
chatList.setSelectionFromTop(index,top);
}
});
}
});
di.execute();
}
}
catch(Exception ex){
btn.setVisibility(View.GONE);
btn.setTag("");
}
}
});
handler = new Handler(Looper.getMainLooper())
{
#Override
public void handleMessage(Message msg)
{
super.handleMessage(msg);
switch (msg.what)
{
case REFRESH_CHAT_LIST:
adapter.notifyDataSetChanged();
break;
case REFRESH_CHAT_STATUS:
if(text != null)
{
try
{
if (isNumeric(text))
{
chatState.setText(calculateTime(Long.parseLong(text)));
image.setImageResource(R.drawable.status_offline);
}
else
{
chatState.setText(text);
if (chatWithName.equalsIgnoreCase("echo")
|| chatWithName.equalsIgnoreCase("puzzle")
|| chatWithName.equalsIgnoreCase("msr")) {
image.setImageResource(R.drawable.status_active);
} else if (text.equalsIgnoreCase("offline")) {
chat.sendIQForLastSeen(chatWithJID);
image.setImageResource(R.drawable.status_offline);
} else {
image.setImageResource(R.drawable.status_active);
}
}
}
catch(NumberFormatException e)
{
image.setImageResource(R.drawable.status_offline);
e.printStackTrace();
}
}
break;
case REFRESH_MESSAGE_DELIVERY:
adapter.notifyDataSetChanged();
break;
default:
break;
}
}
};
}String filePath ="";
private String saveImage(Bitmap finalBitmap,int chatWith,String from) {
String fileName = chat.getCurrentDateTime();
//msg = "You got a photo. Display of photo will be added in next version of this app.";
final File dir = new File(Environment.getExternalStorageDirectory()
.getAbsolutePath(), "/roo_kids/images/" + from + "/");
if (!dir.exists())
{
dir.mkdirs();
}
final File myFile = new File(dir, fileName + ".png");
if (!myFile.exists())
{
try
{
myFile.createNewFile();
}
catch (IOException e)
{
e.printStackTrace();
}
}
try {
FileOutputStream out = new FileOutputStream(myFile);
finalBitmap.compress(Bitmap.CompressFormat.PNG, 90, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
filePath= myFile.getAbsolutePath()+"::images::";
Log.v("","filePath after decoding:.."+filePath);
Log.v("","chatWith Id after decoding:.."+chatWith);
Log.v("","from after decoding:.."+from);
db.updateFriendChat(chatWith,filePath);
return filePath;
}
public void getAllFiles(String directoryName)
{
}
public boolean isFileExist(String directoryName, String filename)
{
}
#Override
public void onClick(View v)
{
switch (v.getId())
{
case R.id.picture:
openGallery();
break;
case R.id.extra:
break;
case R.id.btn_send:
sendMessageAndValidate();
break;
case R.id.back:
onBackPressed();
break;
default:
break;
}
}
private void openGallery()
{
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
//intent.putExtra(Intent.EXTRA_LOCAL_ONLY, true);
startActivityForResult(intent, SELECT_PICTURE);
}
private String encodeFileToBase64Binary(String path)throws IOException, FileNotFoundException
{
}
String cond="";
public class ExecuteImageSharingProcess extends AsyncTask<String, Integer, String>
{
String base64 = "";
ProgressDialog pd = null;
#Override
protected void onPreExecute()
{
super.onPreExecute();
pd = new ProgressDialog(ChatScreen.this);
pd.setCancelable(false);
pd.setMessage("Please wait..");
pd.show();
}
#Override
protected String doInBackground(String... params)
{
try
{
//base64 = encodeFileToBase64Binary(params[0]);
Log.v("", "params[0].."+params[0]);
byte[] data = params[0].getBytes("UTF-8");
base64= new String(data);
Log.v("", "base64.."+base64);
return "yes";
}
catch (IOException e)
{
e.printStackTrace();
return "no";
}
catch(NullPointerException e)
{
return "no";
}
}
#Override
protected void onPostExecute(String result)
{
super.onPostExecute(result);
if(result.equals("yes"))
{
if(chat.isConnected())
{
String prefix = chat.generateRandomChar()+"imagePrefixEnd";
System.out.println("prefix-> "+prefix);
ctx.moveMessagetoXMPP(prefix + base64 + "::images::", 1);
base64 = "";
bitmap = null;
}
}
else
{
Toast.makeText(ctx, "File not found.", Toast.LENGTH_LONG).show();
}
try
{
if ((this.pd != null) && this.pd.isShowing())
{
this.pd.dismiss();
}
} catch (final IllegalArgumentException e)
{
} catch (final Exception e)
{
} finally
{
this.pd = null;
}
}
}
String imgDecodableString = null;
String imgbase64="";
AlertManager alert_dialog;
#Override
public void onActivityResult(int requestCode, int resultCode, Intent i)
{
super.onActivityResult(requestCode, resultCode, i);
try
{
if (requestCode == SELECT_PICTURE && resultCode == RESULT_OK && null != data)
{
String urlofimage=""; // here i send base64 image to server and it will returns url of image that is send in ExecuteImageSharingProcess method.
new ExecuteImageSharingProcess().execute(urlofimage);
}
});
ucIA.execute();
}
}
else if (resultCode == Activity.RESULT_CANCELED)
{
bitmap = null;
}
} catch (Exception e)
{
Toast.makeText(this, "Something went wrong", Toast.LENGTH_LONG).show();
}
}
private void sendMessageAndValidate()
{
String msg=inputMessage.getText().toString().replace(" ","");
String msgone=msg.replace("\n", "");
if (msgone.length() > 0)
{
if (chat.isConnected())
{
ctx.moveMessagetoXMPP(inputMessage.getText().toString(), 0);
inputMessage.setText("");
stopTimer();
}
}
}
String thread="";
protected void moveMessagetoXMPP(String msg, final int type)
{
data = session.getUserDetails();
if (checkChatRoomAvailablity(chatWithName))
{
thread = db.getThreadFromChatroom(chatWithName);
}
if (thread.equals(""))
thread = ChatRoomName;
chat.sendMesage(indexOfChatRoom, msg, FromChatJID, chatWithJID, thread, type);
try
{
chat.setCurrentState(ChatState.paused, chatWithJID, FromChatJID);
}
catch (XMPPException e)
{
e.printStackTrace();
}
}
public class MyThread implements Runnable
{
String message;
File file;
public MyThread(String message, File file)
{
this.message = message;
this.file = file;
}
#Override
public void run()
{
String fileName;
if(message.contains("::images::"))
fileName = saveFile(decodeBase64(message.substring(message.indexOf("imagePrefixEnd")+14, message.indexOf("::images::"))), file);
else
fileName = saveFile(decodeBase64(message.substring(message.indexOf("imagePrefixEnd")+14, message.indexOf("::doodle::"))), file);
}
}
public void appendMessageInListView(long _id)
{
if (messages.size() > 0)
{
System.out.println(messages.get(messages.size() - 1).getId());
ChatMessage cm = db.getFriendChatMessage(indexOfChatRoom, ""+ messages.get(messages.size() - 1).getId());
messages.add(messages.size(), cm);
}
else
{
ChatMessage cm = db.getFriendChatMessage(indexOfChatRoom, "" + _id);
messages.add(messages.size(), cm);
}
refreshChatList();
}
public void refreshChatList()
{
int state = REFRESH_CHAT_LIST;
Message msg = handler.obtainMessage(state);
msg.sendToTarget();
}
public void refreshChatStatus() {
int state = REFRESH_CHAT_STATUS;
Message msg = handler.obtainMessage(state);
msg.sendToTarget();
}
public int getChatIndex2(String participant) {
return db.getChatRoomIndex(participant);
}
ImageView img;
View oldview;
public class ChatMessageAdapter extends BaseAdapter
{
public ArrayList<ChatMessage> messages;
private Context ctx;
public ChatMessageAdapter(Context ctx, ArrayList<ChatMessage> messages)
{
this.ctx = ctx;
this.messages = messages;
}
#Override
public int getCount()
{
return messages.size();
}
#Override
public long getItemId(int arg0)
{
return arg0;
}
#Override
public View getView(int position, View oldView, ViewGroup parent)
{
if (ctx == null)
return oldView;
final ChatMessage msg = getItem(position);
if (oldView == null || (((Integer) oldView.getTag()) != msg.getIsOutgoing()))
{
LayoutInflater inflater = (LayoutInflater) getLayoutInflater();
if (msg.getIsOutgoing() == MyMessage.OUTGOING_ITEM)
{
oldView = inflater.inflate(R.layout.fragment_message_outgoing_item, null);
oldView.setTag(MyMessage.OUTGOING_ITEM);
}
else
{
oldView = inflater.inflate(R.layout.fragment_message_ingoing_item, null);
oldView.setTag(MyMessage.INGOING_ITEM);
}
}
TextView message = (TextView) oldView.findViewById(R.id.msg);
message.setTypeface(typeFaceCurseCasual);
LinearLayout lay_txt = (LinearLayout) oldView.findViewById(R.id.lay_txt);
LinearLayout lay_img = (LinearLayout) oldView.findViewById(R.id.lay_img);
img = (ImageView) oldView.findViewById(R.id.imagev);
FrameLayout fmlay=(FrameLayout) oldView.findViewById(R.id.fmlay);
ImageView textView1 = (ImageView) oldView.findViewById(R.id.textView1);
ImageView imgSticker = (ImageView) oldView.findViewById(R.id.img_sticker);
ImageView tickSent = (ImageView) oldView.findViewById(R.id.tickSent);
ImageView tickDeliver = (ImageView) oldView.findViewById(R.id.tickDeliver);
TextView timestamp = (TextView) oldView.findViewById(R.id.timestamp);
oldview=oldView;
timestamp.setTypeface(typeFaceCurseCasual);
message.setText(msg.getMessage());
System.out.println("message in adapter");
if (msg.getIsOutgoing() == MyMessage.OUTGOING_ITEM)
tickSent.setVisibility(View.VISIBLE);
else
tickSent.setVisibility(View.INVISIBLE);
if (msg.getIsDeliver() == true)
tickDeliver.setVisibility(View.VISIBLE);
else
tickDeliver.setVisibility(View.INVISIBLE);
if(msg.getTimeStamp()!= null) timestamp.setText(getTimeAgo(Long.parseLong(msg.getTimeStamp()),ctx));
if(msg.getMessage()!= null)
{
if(msg.getMessage().contains("::sticker::"))
{
lay_img.setVisibility(View.GONE);
lay_txt.setVisibility(View.GONE);
imgSticker.setVisibility(View.VISIBLE);
String Dir = msg.getMessage().substring(2, msg.getMessage().indexOf("-"));
String file = msg.getMessage().substring(2, msg.getMessage().indexOf("}}"));
if(isFileExist(Dir, file))
{
String path = ctx.getFilesDir() + "/booksFolder/"+Dir+"/"+file;
System.out.println("path- "+ path);
Uri imgUri = Uri.parse("file://"+path);
imgSticker.setImageURI(imgUri);
}
else
{
String url = "http://s3.amazonaws.com/rk-s-0ae8740/a/"+file;
System.out.println(url);
new ImageLoaderWithImageview(mcon).DisplayImage(url, imgSticker);
}
}
else if(!msg.getMessage().contains("::images::") && !msg.getMessage().contains("::doodle::"))
{
System.out.println("in text condition");
lay_img.setVisibility(View.GONE);
imgSticker.setVisibility(View.GONE);
lay_txt.setVisibility(View.VISIBLE);
System.out.println("msg coming :"+msg.getMessage());
message.setText(msg.getMessage());
}
else
{
lay_txt.setVisibility(View.GONE);
imgSticker.setVisibility(View.GONE);
lay_img.setVisibility(View.VISIBLE);
if (msg.getIsOutgoing() == MyMessage.INGOING_ITEM)
{
fmlay.setVisibility(View.VISIBLE);
}
Log.v("","msg getting:..."+msg.getMessage());
String pathOne = null ;
if(msg.getMessage().contains("imagePrefixEnd")){
Log.v("In images/doddle if", "askfk");
pathOne="default";
textView1.setVisibility(View.VISIBLE);
String imgpath=setdefaultImage(msg.getMessage());
textView1.setTag(imgpath);
}
else {
Log.v("In images else", "askfk");
try{
pathOne = msg.getMessage().substring(0, msg.getMessage().indexOf("::images::"));
}
catch(Exception ex){
pathOne = msg.getMessage().substring(0, msg.getMessage().indexOf("::doodle::"));
}
textView1.setVisibility(View.GONE);
Bitmap bitmap=setImage(pathOne);
img.setImageBitmap(bitmap);
textView1.setTag("");
}
}
}
return oldview;
}
#Override
public ChatMessage getItem(int position)
{
return messages.get(position);
}
}
public String setdefaultImage(String msg){
Bitmap bImage = BitmapFactory.decodeResource(ChatScreen.this.getResources(), R.drawable.dummyimage);
img.setImageBitmap(bImage);
String urlpath="";
try{
urlpath = msg.substring(0, msg.indexOf("::images::"));
}
catch(Exception ex){
urlpath = msg.substring(0, msg.indexOf("::doodle::"));
}
//Log.v("","msg getting:..."+urlpath);
String pt[]=urlpath.split("PrefixEnd");
//System.out.println("path :"+pt[1]);
return pt[1];
}
public Bitmap setImage(String pathOne){
Bitmap bitmap=null;
File imgFile = new File(pathOne);
//Log.v("","msg image path:..."+pathOne);
if(imgFile.exists())
{
//Log.v("","msg path exits:...");
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 3;
bitmap= BitmapFactory.decodeFile(pathOne, options);
}
else{
}
return bitmap;
}
}
Try to tag the data model/ data source with your list view view.setTag(dataModel) in getView method of your adapter class.
Why not try RecyclerView instead of ListView and use Fresco Image Library?
I am developing multiple file download app. in which, if switch is on then downloading is start and if switch is off then downloading is cancel. I am updating item value using timertask with handler. below is my code of adapter. everything is working fine but when I am scrolling listview, item value (percentage count) are conflict with other values which are other file downloaded progress.
Code:
public class DownloadAdapter extends ArrayAdapter<AudioSubModel> {
private static final String PDF_MIME_TYPE = "application/pdf";
private LayoutInflater lf;
Context mContext;
private List<ListContent> lstHolders;
private Handler mHandler = new Handler();
private Runnable updateRemainingTimeRunnable = new Runnable() {
#Override
public void run() {
synchronized (lstHolders) {
for (ListContent holder : lstHolders) {
holder.updateTimeRemaining();
}
}
}
};
AudioSubModel getAlarm(int position){
return ((AudioSubModel) getItem(position));
}
public DownloadAdapter(Context context, int resource, List<AudioSubModel> objects) {
super(context, resource, objects);
lf = LayoutInflater.from(context);
lstHolders = new ArrayList<ListContent>();
mContext = context;
Log.e("ADAPTER", "CONSTR");
startUpdateTimer();
}
private void startUpdateTimer() {
Timer tmr = new Timer();
tmr.schedule(new TimerTask() {
#Override
public void run() {
mHandler.post(updateRemainingTimeRunnable);
}
}, 1000, 1000);
}
#Override
public View getView(int position, View view, ViewGroup parent) {
ListContent holder = null;
if (view == null) {
view = lf.inflate(R.layout.row_audio_desc_layout, null);
holder = new ListContent();
holder.ivImg = (CircleImageView)view.findViewById(R.id.row_audio_desc_ivImg);
holder.tvTitle = (TextView) view
.findViewById(R.id.row_audio_desc_tvTitle);
holder.tvDesc = (TextView) view
.findViewById(R.id.row_audio_desc_tvDesc);
holder.llDownload = (LinearLayout)view.findViewById(R.id.row_audio_desc_llDownload);
holder.PBDownload = (RoundCornerProgressBar)view.findViewById(R.id.row_audio_desc_PBDownload);
holder.tvReadPdf = (TextView)view.findViewById(R.id.row_audio_desc_tvReadPdf);
holder.tvMakeOffline = (TextView)view.findViewById(R.id.row_audio_desc_tvMakeOffline);
holder.swtchDownload = (Switch)view.findViewById(R.id.row_audio_desc_swtchDownloadOn);
holder.tvDownload = (TextView)view.findViewById(R.id.row_audio_desc_tvDownload);
holder.tvDownloadPercent = (TextView)view.findViewById(R.id.row_audio_desc_tvDownloadPercent);
holder.ivCancel = (ImageView)view.findViewById(R.id.row_audio_desc_ivCancel);
holder.ivPlay = (ImageView)view.findViewById(R.id.row_audio_desc_ivPlay);
holder.tvTitle.setTypeface(MyApplication.app_bold);
holder.tvDesc.setTypeface(MyApplication.app_light);
holder.tvReadPdf.setTypeface(MyApplication.app_bold);
holder.tvMakeOffline.setTypeface(MyApplication.app_bold);
holder.swtchDownload.setTypeface(MyApplication.app_bold);
holder.tvDownload.setTypeface(MyApplication.app_bold);
holder.tvDownloadPercent.setTypeface(MyApplication.app_bold);
view.setTag(holder);
synchronized (lstHolders) {
lstHolders.add(holder);
}
} else {
holder = (ListContent) view.getTag();
}
holder.setData(getAlarm(position));
// convertView.setOnClickListener(new View.OnClickListener() {
// #Override
// public void onClick(View v) {
// ((MainActivity)mContext).ItemClickFetch(getItem(position).getId());
// }
// });
return view;
}
class ListContent {
LinearLayout llDownload;
RoundCornerProgressBar PBDownload;
CircleImageView ivImg;
ImageView ivCancel, ivPlay;
TextView tvTitle, tvDesc, tvReadPdf, tvMakeOffline, tvDownload, tvDownloadPercent;
Switch swtchDownload;
private AudioSubModel aItem;
DownloadFileFromURL dwnldFileUrl;
public void setData(AudioSubModel item) {
aItem = item;
dwnldFileUrl = new DownloadFileFromURL();
if(item.isPlaying()){
ivPlay.setImageResource(R.drawable.pausebtn);
}else{
ivPlay.setImageResource(R.drawable.playbtn);
}
if(aItem.isDownloading()){
swtchDownload.setOnCheckedChangeListener(null);
swtchDownload.setChecked(true);
tvDownloadPercent.setText(aItem.getPercent() + "");
}else{
swtchDownload.setOnCheckedChangeListener(null);
swtchDownload.setChecked(false);
tvDownloadPercent.setText("0");
}
// holder.tvDownloadPercent.setText(data.get(position).getPercent()+" %");
tvDownload.setText(aItem.getDwnLbl());
tvTitle.setText(aItem.getTitle());
tvDesc.setText(aItem.getDesc());
Bitmap bmp = BitmapFactory.decodeFile(aItem.getImage());
ivImg.setImageBitmap(bmp);
// Log.e("MAIN", "IS DONE: " + aItem.isOn());
tvReadPdf.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(isPDFSupported(mContext)){
Uri path = Uri.fromFile(new File(aItem.getPdf()));
Intent objIntent = new Intent(Intent.ACTION_VIEW);
objIntent.setDataAndType(path, "application/pdf");
objIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
mContext.startActivity(objIntent);
}else{
if(GeneralClass.getConnectivityStatusString(mContext)){
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://docs.google.com/gview?embedded=true&url="+aItem.getPdfurl()));
mContext.startActivity(browserIntent);
}else{
GeneralClass.showToast("Check internet connection to view pdf file", mContext);
}
}
}
});
ivPlay.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
if(aItem.isPlaying()){
aItem.setPlaying(false);
((MainActivity)mContext).stopAudioFile();
}else{
aItem.setPlaying(true);
((MainActivity)mContext).playAudioFile(aItem);
}
}
});
swtchDownload.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton arg0, boolean arg1) {
// TODO Auto-generated method stub
// updateView(position, arg1);
Log.e("Audio ADAPTER", "file: " + arg1);
if(arg1){
aItem.setDownloading(true);
aItem.setDwnLbl("Downloading");
dwnldFileUrl.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, aItem.getAudiourl());
}else if(!arg1){
aItem.setDownloading(false);
aItem.setDwnLbl("Download");
dwnldFileUrl.cancel(true);
}
}
});
ivCancel.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
aItem.setDownloading(false);
aItem.setDwnLbl("Download");
dwnldFileUrl.cancel(true);
// updateView(position, false);
// new DownloadFileFromURL(holder, position).execute(data.get(position).getAudiourl());
}
});
updateTimeRemaining();
}
public void updateTimeRemaining() {
// Log.e("MAIN", "GET TIME: " + aItem.getTimeStamp());
if(aItem.isDownloading()){
llDownload.setVisibility(View.VISIBLE);
tvDownloadPercent.setVisibility(View.VISIBLE);
tvDownloadPercent.setText(aItem.getPercent()+"");
// PBDownload.setProgress(aItem.getPercent());
tvDownload.setText(aItem.getDwnLbl());
}else{
llDownload.setVisibility(View.INVISIBLE);
tvDownloadPercent.setVisibility(View.INVISIBLE);
tvDownloadPercent.setText("0");
// PBDownload.setProgress(0);
tvDownload.setText(aItem.getDwnLbl());
}
// if(aItem.isOn()){
// tvTitle.setText(aItem.getPercent()+"");
// }else{
// tvTitle.setText("0");
// }
}
class DownloadFileFromURL extends AsyncTask<String, String, String> {
private volatile boolean running = true;
String finalFilePath="";
/**
* Before starting background thread
* Show Progress Bar Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
}
/**
* Downloading file in background thread
* */
#Override
protected String doInBackground(String... f_url) {
int count;
try {
// URL url = new URL(f_url[0]);
URL url = new URL("http://www.robtowns.com/music/blind_willie.mp3");
URLConnection conection = url.openConnection();
conection.connect();
// getting file length
int lenghtOfFile = conection.getContentLength();
// input stream to read file - with 8k buffer
InputStream input = new BufferedInputStream(url.openStream(), 8192);
// Output stream to write file
String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
String outputFile = extStorageDirectory+"/"+GeneralClass.FILE_PATH;
finalFilePath = outputFile+"/audio"+aItem.getId()+".mp3";
OutputStream output = new FileOutputStream(finalFilePath);
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1 && running) {
if(isCancelled()){
Log.e("ADAPTER", "Async break");
break;
}
total += count;
// publishing the progress....
// After this onProgressUpdate will be called
publishProgress(""+(int)((total*100)/lenghtOfFile));
// writing data to file
output.write(data, 0, count);
}
// flushing output
output.flush();
// closing streams
output.close();
input.close();
} catch (Exception e) {
Log.e("Error: ", e.getMessage());
}
return null;
}
#Override
protected void onCancelled() {
running = false;
Log.e("ADAPTER", "Async cancelled");
}
/**
* Updating progress bar
* */
#Override
protected void onProgressUpdate(String... progress) {
// setting progress percentage
aItem.setPercent(Integer.parseInt(progress[0]));
}
/**
* After completing background task
* Dismiss the progress dialog
* **/
#Override
protected void onPostExecute(String file_url) {
// dismiss the dialog after the file was downloaded
// dismissDialog(progress_bar_type);
Log.e("ADAPTER", "DONE ID: " + aItem.getId());
((MainActivity)mContext).updateAudioFileDownload(aItem.getId(), finalFilePath);
ivCancel.setVisibility(View.INVISIBLE);
}
}
}
public static boolean isPDFSupported(Context context) {
Intent i = new Intent( Intent.ACTION_VIEW );
final File tempFile = new File( context.getExternalFilesDir( Environment.DIRECTORY_DOWNLOADS ), "test.pdf" );
i.setDataAndType( Uri.fromFile( tempFile ), PDF_MIME_TYPE );
return context.getPackageManager().queryIntentActivities( i, PackageManager.MATCH_DEFAULT_ONLY ).size() > 0;
}
}
Help me with this major issue.
I have made a program in which i am fetching list of all my Facebook Friends with their name, dob and profile picture, but i have decided to use tabs in my existing program therefore, i have also written code for that, but whenever i run my app, every time i am getting tabs but not getting list of friends..
In my case i am not getting FriendsList Activity data in TabSample Class, why?
SplashScreen.java:-
private final static int FACEBOOK_AUTHORIZE_ACTIVITY_RESULT_CODE = 0;
private final static int FRIENDS_LIST_ACTIVITY = 1;
public void onRequestReceived(int result, String message) {
Log.d(LOG_TAG, "onRequestReceived(" + result + ")");
if(isFinishing())
return;
switch (result) {
case FacebookRequest.COMPLETED:
Intent intent = new Intent(this, com.chr.tatu.sample.friendslist.TabSample.class);
intent.putExtra("FRIENDS", message);
while (System.currentTimeMillis() - startTime < DELAY) {
try { Thread.sleep(50); } catch (Exception e) {}
}
startActivityForResult(intent, FRIENDS_LIST_ACTIVITY);
isLoadingFriends = false;
break;
case FacebookRequest.IO_EXCEPTION:
case FacebookRequest.FILE_NOT_FOUND_EXCEPTION:
case FacebookRequest.MALFORMED_URL_EXCEPTION:
case FacebookRequest.FACEBOOK_ERROR:
FacebookUtility.displayMessageBox(this, this.getString(R.string.friends_error));
onButton();
break;
}
}
FriendsList.java:-
public class FriendsList extends Activity implements FacebookRequest, OnItemClickListener {
private static String LOG_TAG = "FriendsList";
private static JSONArray jsonArray;
private static ListView friendsList;
private Handler mHandler;
private Button saveGreeting;
public void onCreate(Bundle savedInstanceState) {
mHandler = new Handler();
super.onCreate(savedInstanceState);
try {
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
getActionBar().hide();
} catch (Exception e) {}
setContentView(R.layout.friends_list_screen);
try {
setProgressBarIndeterminateVisibility(false);
} catch (Exception e) {}
init();
saveGreeting = (Button) findViewById(R.id.greeting);
saveGreeting.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
customGreeting(v);
}
});
}
public void customGreeting(View v) {
Intent myWebLink = new Intent(android.content.Intent.ACTION_VIEW);
myWebLink.setData(Uri.parse("http://google.com/"));
startActivity(myWebLink);
}
#Override
public void onDestroy() {
super.onDestroy();
exit();
}
private void exit() {
if (friendsList != null)
friendsList.setAdapter(null);
friendsList = null;
jsonArray = null;
GetProfilePictures.clear();
}
#Override
public void onBackPressed() {
super.onBackPressed();
finish();
exit();
}
private void init() {
friendsList = (ListView) findViewById(R.id.friends_list);
friendsList.setOnItemClickListener(this);
friendsList.setAdapter(new FriendListAdapter(this));
friendsList.setTextFilterEnabled(true);
friendsList.setDivider(null);
friendsList.setDividerHeight(0);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
Log.d(LOG_TAG, "onCreateOptionsMenu()");
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.menu, menu);
return super.onCreateOptionsMenu(menu);
}
/**
#Override
public boolean onOptionsItemSelected(MenuItem item) {
Log.d(LOG_TAG, "onOptionsItemSelected()");
switch (item.getItemId()) {
case R.id.menu_refresh:
FacebookUtility.logout(this);
setProgressBarInDVisibility(true);
return true;
case R.id.retry_button:
GetProfilePictures.clear();
init();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
**/
public void onRequestReceived(int result, String message) {
Log.d(LOG_TAG, "onRequestReceived(" + result + ")");
if(isFinishing())
return;
// setProgressBarInDVisibility(false);
switch (result) {
case FacebookRequest.COMPLETED:
FacebookUtility.clearSession(this);
finish();
break;
case FacebookRequest.IO_EXCEPTION:
case FacebookRequest.FILE_NOT_FOUND_EXCEPTION:
case FacebookRequest.MALFORMED_URL_EXCEPTION:
case FacebookRequest.FACEBOOK_ERROR:
FacebookUtility.displayMessageBox(this, this.getString(R.string.logout_failed));
break;
}
}
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
// Log.d(LOG_TAG, "onItemClick()");
try {
final long friendId;
friendId = jsonArray.getJSONObject(position).getLong("uid");
String name = jsonArray.getJSONObject(position).getString("name");
new AlertDialog.Builder(this).setTitle(R.string.post_on_wall_title)
.setMessage(String.format(getString(R.string.post_on_wall), name))
.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Bundle params = new Bundle();
params.putString("to", String.valueOf(friendId));
params.putString("caption", getString(R.string.app_name));
params.putString("description", getString(R.string.app_desc));
params.putString("picture", FacebookUtility.HACK_ICON_URL);
params.putString("name", getString(R.string.app_action));
FacebookUtility.facebook.dialog(FriendsList.this, "feed", params,
(DialogListener) new PostDialogListener());
}
}).setNegativeButton(R.string.no, null).show();
} catch (JSONException e) {
showToast("Error: " + e.getMessage());
}
}
public class PostDialogListener extends BaseDialogListener {
#Override
public void onComplete(Bundle values) {
final String postId = values.getString("post_id");
if (postId != null) {
showToast("Message posted on the wall.");
} else {
showToast("No message posted on the wall.");
}
}
}
public void showToast(final String msg) {
mHandler.post(new Runnable() {
#Override
public void run() {
Toast toast = Toast.makeText(FriendsList.this, msg, Toast.LENGTH_LONG);
toast.show();
}
});
}
public class FriendListAdapter extends BaseAdapter implements SectionIndexer {
private LayoutInflater mInflater;
private GetProfilePictures picturesGatherer = null;
FriendsList friendsList;
private String[] sections;
Hashtable<Integer, FriendItem> listofshit = null;
public FriendListAdapter(FriendsList friendsList) {
Log.d(LOG_TAG, "FriendListAdapter()");
this.friendsList = friendsList;
sections = new String[getCount()];
listofshit = new Hashtable<Integer, FriendItem>();
for (int i = 0; i < getCount(); i++) {
try {
sections[i] = jsonArray.getJSONObject(i).getString("name").substring(0);
sections[i] = jsonArray.getJSONObject(i).getString("birthday").substring(1);
} catch (JSONException e) {
sections[i] = "";
Log.e(LOG_TAG, "getJSONObject: " + e.getMessage());
}
}
if (picturesGatherer == null) {
picturesGatherer = new GetProfilePictures();
}
picturesGatherer.setAdapterForListener(this);
mInflater = LayoutInflater.from(friendsList.getBaseContext());
}
public int getCount() {
Log.d(LOG_TAG, "getCount()");
if (jsonArray == null)
return 0;
return jsonArray.length();
}
public Object getItem(int position) {
Log.d(LOG_TAG, "getItem()");
return listofshit.get(position);
}
public long getItemId(int position) {
Log.d(LOG_TAG, "getItemId()");
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
Log.d(LOG_TAG, "getView(" + position + ")");
JSONObject jsonObject = null;
try {
jsonObject = jsonArray.getJSONObject(position);
} catch (JSONException e) {
Log.e(LOG_TAG, "getJSONObject: " + e.getMessage());
}
FriendItem friendItem;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.single_friend, null);
friendItem = new FriendItem();
convertView.setTag(friendItem);
}
else {
friendItem = (FriendItem) convertView.getTag();
}
friendItem.friendPicture = (ImageView) convertView.findViewById(R.id.picture_square);
friendItem.friendName = (TextView) convertView.findViewById(R.id.name);
friendItem.friendDob = (TextView) convertView.findViewById(R.id.dob);
friendItem.friendLayout = (RelativeLayout) convertView.findViewById(R.id.friend_item);
try {
String uid = jsonObject.getString("uid");
String url = jsonObject.getString("pic_square");
friendItem.friendPicture.setImageBitmap(picturesGatherer.getPicture(uid, url));
} catch (JSONException e) {
Log.e(LOG_TAG, "getJSONObject: " + e.getMessage());
friendItem.friendName.setText("");
friendItem.friendDob.setText("");
}
try {
friendItem.friendName.setText(jsonObject.getString("name"));
friendItem.friendDob.setText(jsonObject.getString("birthday"));
} catch (JSONException e) {
Log.e(LOG_TAG, "getJSONObject: " + e.getMessage());
friendItem.friendName.setText("");
friendItem.friendDob.setText("");
}
listofshit.put(position, friendItem);
return convertView;
}
public int getPositionForSection(int position) {
return position;
}
public int getSectionForPosition(int position) {
return position;
}
public Object[] getSections() {
return sections;
}
}
class FriendItem {
TextView friendDob;
int id;
ImageView friendPicture;
TextView friendName;
RelativeLayout friendLayout;
}
}
TabSample.java:-
public class TabSample extends TabActivity {
/** Called when the activity is first created. */
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.tabmain);
setTabs() ;
}
private void setTabs()
{
addTab("All", R.drawable.tab_menu, FriendsList.class);
addTab("Current Month", R.drawable.tab_offers, FriendsList.class);
addTab("Current Week", R.drawable.tab_location, FriendsList.class);
addTab("Today", R.drawable.tab_reservation, FriendsList.class);
}
private void addTab(String labelId, int drawableId, Class<?> c)
{
TabHost tabHost = getTabHost();
Intent intent = new Intent(this, c);
TabHost.TabSpec spec = tabHost.newTabSpec("tab" + labelId);
View tabIndicator = LayoutInflater.from(this).inflate(R.layout.tab_indicator, getTabWidget(), false);
TextView title = (TextView) tabIndicator.findViewById(R.id.title);
title.setText(labelId);
ImageView icon = (ImageView) tabIndicator.findViewById(R.id.icon);
icon.setImageResource(drawableId);
spec.setIndicator(tabIndicator);
spec.setContent(intent);
tabHost.addTab(spec);
}
}
Please tell me where i have to add this code :
Bundle extras = getIntent().getExtras();
String response = extras.getString("FRIENDS");
Log.d(LOG_TAG, "onCreate()" + response);
try {
jsonArray = new JSONArray(response);
} catch (JSONException e) {
FacebookUtility.displayMessageBox(this, this.getString(R.string.json_failed));
}
and any other code need to move from FriendsList class to TabSample Class
I need to prevent against lazy load in my custom list-view. so i found that scrollview onscroll listner are helpfull over there i have tryed it but not getting success to implement this functionality.
Code:
lviewAdapter = new ListViewAdapter(SaxParser2.this, Arr_ActivityName, Arr_AudioScript,Arr_RequestID,Arr_FolderPath,Arr_RequestTo);
lview.setOnScrollListener(SaxParser2.this);
#Override
public void onScroll(AbsListView arg0, int arg1, int arg2, int arg3) {
// TODO Auto-generated method stub
lview.setAdapter(lviewAdapter);
}
#Override
public void onScrollStateChanged(AbsListView arg0, int arg1) {
// TODO Auto-generated method stub
}
here is my BaseAdapter
package com.RecordingApp;
import it.sauronsoftware.ftp4j.FTPClient;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.net.HttpURLConnection;
import java.net.URL;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Typeface;
import android.graphics.drawable.AnimationDrawable;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.os.AsyncTask;
import android.os.CountDownTimer;
import android.os.Environment;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.Sharedpreferance.GMailSender;
public class ListViewAdapter extends BaseAdapter {
public static Activity context;
String title[];
String description[];
String RequestId[];
String Folderpath[];
String RequestTo[];
boolean b_Flag_Record_or_not = false;
boolean b_upload_or_not = false;
boolean start_or_not = false;
boolean start_play = false;
boolean upload_or_not = false;
boolean b_play_or_not = false;
boolean isplaying2 = false;
Thread welcomeThread,welcomeThread2;
int glob_position;
MediaPlayer mPlayer2;
int flag_stop_position;
AudioRecorder recorder;
AnimationDrawable frameAnimation, frameAnimation_play;
private static String mFileName = null;
private MediaRecorder mRecorder = null;
private MediaPlayer mPlayer = null;
Recording login = new Recording();
MediaPlayer MP_completeRequest = new MediaPlayer();
public ListViewAdapter(Activity context, String[] title,
String[] description, String[] req_id, String[] FolderPath,
String[] Arr_RequestTo) {
super();
this.context = context;
this.title = title;
this.description = description;
this.RequestId = req_id;
this.Folderpath = FolderPath;
this.RequestTo = Arr_RequestTo;
}
public int getCount() {
// TODO Auto-generated method stub
return title.length;
}
public Object getItem(int position) {
// TODO Auto-generated method stub
return null;
}
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
private class ViewHolder {
TextView txtViewTitle;
TextView txtViewDescription;
Button record, stop, play, upload;
}
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
final ViewHolder holder;
LayoutInflater inflater = context.getLayoutInflater();
glob_position = position;
if (convertView == null) {
convertView = inflater.inflate(R.layout.listitem_row, null);
holder = new ViewHolder();
holder.txtViewTitle = (TextView) convertView
.findViewById(R.id.textView1);
holder.txtViewDescription = (TextView) convertView
.findViewById(R.id.textView2);
holder.record = (Button) convertView.findViewById(R.id.record);
holder.stop = (Button) convertView.findViewById(R.id.stop);
holder.play = (Button) convertView.findViewById(R.id.play1);
holder.upload = (Button) convertView
.findViewById(R.id.audio_upload);
holder.record.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (isplaying2 == true) {
} else {
if (b_Flag_Record_or_not == true) {
} else {
try {
holder.record.setBackgroundResource(R.drawable.record_green);
b_Flag_Record_or_not = true;
b_play_or_not = true;
flag_stop_position = position;
AuthHandler dataHandler = new AuthHandler();
AuthDataset dataset = dataHandler
.getParsednewJobdtl_DataSet();
// Login l = new Login();
String str_useid = RequestTo[position];
recorder = new AudioRecorder(
"/audiometer/shanesh"
+ RequestId[position] + "-"
+ str_useid);
start_or_not = true;
recorder.start();
Toast.makeText(context, "Recording Started",
Toast.LENGTH_LONG).show();
CountDownTimer countDowntimer = new CountDownTimer(
120000000, 1000) {
public void onTick(long millisUntilFinished) {
}
public void onFinish() {
try {
Toast.makeText(
context,
"Stop recording Automatically ",
Toast.LENGTH_LONG).show();
recorder.stop();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
countDowntimer.start();
} catch (IOException e) {
gotoGmail(e);
} catch (Exception e) {
gotoGmail(e);
}
}
}
}
});
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
try {
Typeface face = Typeface.createFromAsset(context.getAssets(),
"fonts/tahoma.ttf");
holder.txtViewTitle.setTypeface(face);
holder.txtViewTitle.setText(title[position]);
holder.txtViewDescription.setText(description[position]);
} catch (ArrayIndexOutOfBoundsException e) {
e.printStackTrace();
}
holder.stop.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
try {
if (isplaying2 == true) {
mPlayer2.stop();
isplaying2 = false;
} else {
holder.record.setBackgroundResource(R.drawable.page7_15);
if (flag_stop_position == position) {
b_Flag_Record_or_not = false;
if (start_or_not == true) {
b_play_or_not = false;
recorder.stop();
upload_or_not = true;
start_play = true;
Toast.makeText(context, "Stoped Recording",
Toast.LENGTH_LONG).show();
} else {
Toast.makeText(context,
" Please Start recording ",
Toast.LENGTH_LONG).show();
}
} else {
}
}
} catch (Exception e) {
gotoGmail(e);
}
}
});
holder.play.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String temp = SaxParser2.str_completeORpendingFlag;
if (temp.equalsIgnoreCase("c")) {
try {
final MediaPlayer mPlayer = new MediaPlayer();
try {
mPlayer.setDataSource(Folderpath[position]);
mPlayer.prepare();
final int welcomeScreenDisplay = mPlayer
.getDuration();
welcomeThread = new Thread() {
int wait = 0;
#Override
public void run() {
try {
isplaying2 = true;
mPlayer.start();
while (wait < welcomeScreenDisplay) {
sleep(100);
wait += 100;
}
} catch (Exception e) {
} finally {
isplaying2 = false;
}
}
};
welcomeThread.start();
} catch (Exception e) {
gotoGmail(e);
}
} catch (Exception e) {
gotoGmail(e);
}
} else if (temp.equalsIgnoreCase("p")) {
try {
if (b_play_or_not == true) {
} else {
String str_useid = RequestTo[position];
java.io.File file = new java.io.File(Environment
.getExternalStorageDirectory()
+ "/audiometer/", "shanesh"
+ RequestId[position] + "-" + str_useid
+ ".amr");
if (file.exists()) {
Toast.makeText(context, "Playing",
Toast.LENGTH_LONG).show();
mPlayer2 = new MediaPlayer();
try {
mPlayer2.setDataSource(Environment
.getExternalStorageDirectory()
+ "/audiometer/shanesh"
+ RequestId[position]
+ "-"
+ str_useid + ".amr");
mPlayer2.prepare();
mPlayer2.start();
isplaying2 = true;
final int welcomeScreenDisplay = mPlayer2
.getDuration();
/**
* create a thread to show splash up to
* splash time
*/
welcomeThread = new Thread() {
int wait = 0;
#Override
public void run() {
try {mPlayer2.prepare();
while (wait < welcomeScreenDisplay) {
sleep(100);
wait += 100;
}
} catch (Exception e) {
} finally {
welcomeThread2 = new Thread() {
int wait = 0;
#Override
public void run() {
try {
mPlayer2.start();
while (wait < welcomeScreenDisplay) {
sleep(100);
wait += 100;
}
} catch (Exception e) {
} finally {
// frameAnimation_play.stop();
isplaying2 = false;
}
}
};
welcomeThread2.start();
}
}
};
welcomeThread.start();
} catch (Exception e) {
gotoGmail(e);
}
} else {
Toast.makeText(context, " File Not Found ",
Toast.LENGTH_LONG).show();
}
}
} catch (Exception e) {
gotoGmail(e);
}
}
}
});
holder.upload.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
glob_position = position;
// String str_useid = RequestTo[position];
if (upload_or_not == true) {
try {
new xyz().execute();
} catch (Exception e) {
gotoGmail(e);
}
}
}
});
return convertView;
}
private class xyz extends AsyncTask<Void, Void, Void> {
private final ProgressDialog dialog = new ProgressDialog(context);
protected void onPreExecute() {
try {
this.dialog.setMessage("Uploading...Please Wait..");
dialog.setIndeterminate(true);
dialog.setCancelable(false);
this.dialog.show();
// put your code which preload with processDialog
} catch (Exception e) {
gotoGmail(e);
}
}
#Override
protected Void doInBackground(Void... arg0) {
for (int i = 0; i < 100000; i++) {
}
it.sauronsoftware.ftp4j.FTPClient con = new it.sauronsoftware.ftp4j.FTPClient();
try {
String str_useid = RequestTo[glob_position];
con.connect("URL");
con.login("as", "asdasd");
con.changeDirectory("/rangam/RequestContent/audio");
con.setPassive(true);
con.setType(FTPClient.TYPE_BINARY);
con.upload(new java.io.File(Environment
.getExternalStorageDirectory()
+ "/audiometer/shanesh"
+ RequestId[glob_position] + "-" + str_useid + ".amr"));
String filename = "/shanesh" + RequestId[glob_position] + "-"
+ str_useid + ".amr";
con.logout();
con.disconnect(true);
String MachineName = Machinelist.str_Machinename;
sendFlagToServer(RequestId[glob_position], filename,
MachineName);
} catch (Exception e) {
gotoGmail(e);
}
return null;
}
protected void onPostExecute(final Void unused) {
if (this.dialog.isShowing()) {
try {
this.dialog.dismiss();
AlertDialog.Builder alertbox = new AlertDialog.Builder(
context);
alertbox.setTitle("Message");
alertbox.setMessage(":: Uploaded Successfully ::");
alertbox.setPositiveButton("OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0,
int arg1) {
Intent intent_request = new Intent(context,
SaxParser2.class);
intent_request.putExtra("value", Machinelist.str_UIDValue);
intent_request.putExtra("machineName",
Machinelist.str_Machinename);
intent_request.putExtra("captureBack_or_not", 2);
context.startActivity(intent_request);
context.finish();
}
});
alertbox.show();
} catch (Exception e) {
gotoGmail(e);
}
}
}
}
private void sendFlagToServer(String requestID, String filename,
String machineName) {
HttpURLConnection connection;
OutputStreamWriter request = null;
String MachineName = Machinelist.str_Machinename;
URL url = null;
String parameters = "RequestID=" + requestID + "&FileName=" + filename
+ "&MachineName=" + MachineName + "&RequestType=A";
try {
url = new URL(
"URL");
connection = (HttpURLConnection) url.openConnection();
connection.setDoOutput(true);
connection.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded");
connection.setRequestMethod("POST");
request = new OutputStreamWriter(connection.getOutputStream());
request.write(parameters);
request.flush();
request.close();
String line = "";
InputStreamReader isr = new InputStreamReader(
connection.getInputStream());
BufferedReader reader = new BufferedReader(isr);
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
isr.close();
reader.close();
} catch (Exception e) {
gotoGmail(e);
}
}
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK)) {
try {
context.finish();
} catch (Exception e) {
gotoGmail(e);
}
}
return false;
}
void gotoGmail(Exception e) {
Writer writer = new StringWriter();
PrintWriter printWriter = new PrintWriter(writer);
e.printStackTrace(printWriter);
String s = writer.toString();
}
}
Ok,
So first you'll have to define "what is the number of views I'd need to load in order my user not to see that it's lazy loading ?" :
Let's say, you'd want to load 20 rows...
Now in you onscroll, or wherever you want but somewhere like on scroll or Adapter.getView, you'll have to know what is displayed on screen at the moment... Let me explain :
I want to load 20 rows so my user doesn't notice,
I am display 10 of them
and 10 of them are just hidden (not displayed if the guy doesn't scroll).
Now, I wan't to load 10 more when the guy just hit my 15th row
What could be the best way to do that ???
Humm, let's see, trying to find something that returns the (ABSOLUTE) number of the last row displayed on screen - this could be a nice solution.
An otehr solution could be that your 10 or 15th row is the first one displayed on screen ?
etc, etc...
I think stuffs like that should do the trick. ;)
Here is a sample I grabbed from Net. It is loading the items by listening to the Scroll of the ListView . For sample it is loading dates in ListView. After reached the end position it will load next 15 dates. It is Never Ending List . You can modify the adapter to your custom adapter. The concept is:
You have set of data
Loading first n no of items
Set the scroll listener to the listview
If scroll reaches Last Visible Item in Listview , You trigger the worker thread to load additional m no of items.
Notify listview from an UI thread.
int itemsPerPage = 15;
boolean loadingMore = false;
ArrayList<String> myListItems;
ArrayAdapter<String> adapter;
//For test data :-)
Calendar d = Calendar.getInstance();
this.getListView().setOnScrollListener(new OnScrollListener(){
//useless here, skip!
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {}
#Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
//what is the bottom item that is visible
int lastInScreen = firstVisibleItem + visibleItemCount;
//is the bottom item visible & not loading more already ? Load more !
if((lastInScreen == totalItemCount) && !(loadingMore)){
Thread thread = new Thread(null, loadMoreListItems);
thread.start();
}
}
});
//Load the first 15 items
Thread thread = new Thread(null, loadMoreListItems);
thread.start();
}
//Runnable to load the items
private Runnable loadMoreListItems = new Runnable() {
#Override
public void run() {
//Set flag so we cant load new items 2 at the same time
loadingMore = true;
//Reset the array that holds the new items
myListItems = new ArrayList<String>();
//Get 15 new listitems
for (int i = 0; i < itemsPerPage; i++) {
//Fill the item with some bogus information
myListItems.add("Date: " + (d.get(Calendar.MONTH)+ 1) + "/" + d.get(Calendar.DATE) + "/" + d.get(Calendar.YEAR) );
// +1 day :-D
d.add(Calendar.DATE, 1);
}
//Done! now continue on the UI thread
runOnUiThread(returnRes);
}
};
//Since we cant update our UI from a thread this Runnable takes care of that!
private Runnable returnRes = new Runnable() {
#Override
public void run() {
//Loop thru the new items and add them to the adapter
if(myListItems != null && myListItems.size() > 0){
for(int i=0;i<myListItems.size();i++)
adapter.add(myListItems.get(i));
}
//Update the Application title
setTitle("Neverending List with " + String.valueOf(adapter.getCount()) + " items");
//Tell to the adapter that changes have been made, this will cause the list to refresh
adapter.notifyDataSetChanged();
//Done loading more.
loadingMore = false;
}
};
EDIT:
You can get tutorial and full project here