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
Related
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?
Hi Hello to everyone i am developing one app where i am using service to upload multipal images to server for uploading multipal images even if app is closed from background.
But i want to call one function but i am unable to call that function please help me.
UploadPhotos.java
public class UploadPhotos extends AppCompatActivity {
UploadService mBoundService;
boolean mServiceBound = false;
Context context;
SelectPaper paperSession;
private CoordinatorLayout coordinatorLayout;
SelectLab labSession;
SessionManager session;
String strSize,strType,str_username,strMRP,strPrice,strlab,strcity,strdel_type,album_type;
MaterialEditText ppr_size,ppr_type,mrp,disPrice;
SelectedAdapter_Test selectedAdapter;
long totalprice=0;
int i=0;
ProgressBar pb;
String imageName,user_mail,total;
GridView UploadGallery;
Handler handler;
ArrayList<CustomGallery> listOfPhotos;
ImageLoader imageLoader;
String Send[];
Snackbar snackbar;
OrderId orderidsession;
AlertDialog dialog;
Button btnGalleryPickup, btnUpload;
TextView noImage;
String abc;
NotificationManager manager;
Notification.Builder builder;
ArrayList<CustomGallery> dataT;
Notification myNotication;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_upload_photos);
context = this;
manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
final ActionBar ab = getSupportActionBar();
assert ab != null;
ab.setDisplayHomeAsUpEnabled(true);
coordinatorLayout = (CoordinatorLayout) findViewById(R.id.main_content);
labSession = new SelectLab(getApplicationContext());
paperSession = new SelectPaper(getApplicationContext());
orderidsession=new OrderId(getApplicationContext());
session = new SessionManager(getApplicationContext());
HashMap<String, String> user = session.getUserDetails();
user_mail = user.get(SessionManager.KEY_EMAIL);
noImage = (TextView)findViewById(R.id.noImage);
final String symbol = getResources().getString(R.string.rupee_symbol);
HashMap<String, String> paper = paperSession.getPaperDetails();
strSize = paper.get(SelectPaper.KEY_SIZE);
strType = paper.get(SelectPaper.KEY_TYPE);
strdel_type=paper.get(SelectPaper.DEL_TYPE);
HashMap<String, String> lab = labSession.getLabDetails();
strMRP = lab.get(SelectLab.KEY_MRP);
strPrice = lab.get(SelectLab.KEY_PRICE);
strlab = lab.get(SelectLab.KEY_LAB);
strcity = lab.get(SelectLab.KEY_CITY);
str_username=lab.get(SelectLab.KEY_USERNAME);
ppr_size = (MaterialEditText) findViewById(R.id.paper_size);
ppr_type = (MaterialEditText) findViewById(R.id.paper_type);
mrp = (MaterialEditText) findViewById(R.id.MRP);
disPrice = (MaterialEditText) findViewById(R.id.discount_price);
ppr_size.setText(strSize);
ppr_type.setText(strType);
mrp.setText(symbol + " " + strMRP);
disPrice.setText(symbol + " " + strPrice);
initImageLoader();
init();
}
private void initImageLoader() {
DisplayImageOptions defaultOptions = new DisplayImageOptions.Builder()
.cacheOnDisc().imageScaleType(ImageScaleType.EXACTLY_STRETCHED)
.bitmapConfig(Bitmap.Config.RGB_565).build();
ImageLoaderConfiguration.Builder builder = new ImageLoaderConfiguration.Builder(
this).defaultDisplayImageOptions(defaultOptions).memoryCache(
new WeakMemoryCache());
ImageLoaderConfiguration config = builder.build();
imageLoader = ImageLoader.getInstance();
imageLoader.init(config);
}
private void init() {
handler = new Handler();
UploadGallery = (GridView) findViewById(R.id.uploadGallery);
UploadGallery.setFastScrollEnabled(true);
selectedAdapter = new SelectedAdapter_Test(getApplicationContext(), imageLoader);
UploadGallery.setAdapter(selectedAdapter);
btnGalleryPickup = (Button) findViewById(R.id.btnSelectPhoto);
btnGalleryPickup.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(Action.ACTION_MULTIPLE_PICK);
startActivityForResult(i, 200);
}
});
btnUpload = (Button) findViewById(R.id.btn_upload);
btnUpload.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
listOfPhotos = selectedAdapter.getAll();
if (listOfPhotos != null && listOfPhotos.size() > 0) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
abc = sdf.format(new Date());
Log.d("Orderid Session", ""+abc);
abc="EPP"+abc;
orderidsession.CreateOrderId(abc);
Toast.makeText(getApplicationContext(),""+abc,Toast.LENGTH_LONG).show();
//progressDialog = ProgressDialog.show(UploadPhotos.this, "", "Uploading files to server.....", false);
//AlertDialog dialog;;
dialog = new SpotsDialog(UploadPhotos.this);
dialog.show();
Thread thread = new Thread(new Runnable() {
public void run() {
Intent in = new Intent(UploadPhotos.this, UploadService.class);
in.putExtra("listof",dataT);
in.putExtra("strsize",strSize);
in.putExtra("strtype",strType);
in.putExtra("user_mail",user_mail);
in.putExtra("strmrp",strMRP);
in.putExtra("strprice",strPrice);
in.putExtra("strlab",strlab);
in.putExtra("strcity",strcity);
in.putExtra("strdel_type",strdel_type);
in.putExtra("strusername",str_username);
in.putExtra("foldername",abc);
startService(in);
bindService(in, mServiceConnection, Context.BIND_AUTO_CREATE);
// doFileUpload();
runOnUiThread(new Runnable() {
public void run() {
if (dialog.isShowing()) {
dialog.dismiss();
totalprice=0;
}
}
});
}
});
thread.start();
}else{
Toast.makeText(getApplicationContext(),"Please select two files to upload.", Toast.LENGTH_SHORT).show();
}
}
});
UploadGallery.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
CustomGallery objDetails = (CustomGallery) selectedAdapter.getItem(position);
selectedAdapter.getItem(position);
// selectedAdapter.Pbbar(view );
Toast.makeText(getApplicationContext(), "Position : " + position + " Path : " + objDetails.sdcardPath, Toast.LENGTH_SHORT).show();
//selectedAdapter.changeSelection(view, position);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 200 && resultCode == Activity.RESULT_OK) {
String[] all_path = data.getStringArrayExtra("all_path");
noImage.setVisibility(View.GONE);
UploadGallery.setVisibility(View.VISIBLE);
dataT = new ArrayList<CustomGallery>();
for (String string : all_path) {
CustomGallery item = new CustomGallery();
item.sdcardPath = string;
dataT.add(item);
}
Log.d("DATAt",dataT.toString());
selectedAdapter.addAll(dataT);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_upload_photos, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
finish();
return true;
}
return super.onOptionsItemSelected(item);
}
private ServiceConnection mServiceConnection = new ServiceConnection() {
#Override
public void onServiceDisconnected(ComponentName name) {
mServiceBound = false;
}
#Override
public void onServiceConnected(ComponentName name, IBinder service) {
UploadService.MyBinder myBinder = (UploadService.MyBinder) service;
mBoundService = myBinder.getService();
mServiceBound = true;
}
};
}
SelectedAdapter_Test.java
public class SelectedAdapter_Test extends BaseAdapter{
private Context mContext;
private LayoutInflater inflater;
private ArrayList<CustomGallery> data = new ArrayList<CustomGallery>();
ImageLoader imageLoader;
private boolean isActionMultiplePick;
public SelectedAdapter_Test(Context c, ImageLoader imageLoader) {
mContext = c;
inflater = (LayoutInflater) c.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
this.imageLoader = imageLoader;
// clearCache();
}
public class ViewHolder {
ImageView imgQueue;
ImageView imgEdit;
EditText qty;
Button ok;
ProgressBar pb;
}
#Override
public int getCount() {
return data.size();
}
#Override
public Object getItem(int i) {
return data.get(i);
}
#Override
public long getItemId(int i) {
return i;
}
public void changeSelection(View v, int position) {
if (data.get(position).isSeleted) {
data.get(position).isSeleted = false;
((ViewHolder) v.getTag()).imgEdit.setVisibility(View.GONE);
((ViewHolder) v.getTag()).qty.setVisibility(View.GONE);
((ViewHolder) v.getTag()).ok.setVisibility(View.GONE);
} else {
data.get(position).isSeleted = true;
((ViewHolder) v.getTag()).qty.setVisibility(View.VISIBLE);
((ViewHolder) v.getTag()).ok.setVisibility(View.VISIBLE);
((ViewHolder) v.getTag()).imgEdit.setVisibility(View.VISIBLE);
}
}
public void Pbbar(View v) {
((ViewHolder)v.getTag()).pb.setVisibility(View.VISIBLE);
}
#Override
public View getView(final int i, View convertView, ViewGroup viewGroup) {
final ViewHolder holder;
if (convertView == null) {
convertView = inflater.inflate(R.layout.inflate_photo_upload, null);
holder = new ViewHolder();
holder.pb=(ProgressBar)convertView.findViewById(R.id.pb_image_upload);
holder.imgQueue = (ImageView) convertView.findViewById(R.id.imgQueue);
holder.imgEdit = (ImageView) convertView.findViewById(R.id.imgedit);
holder.qty = (EditText)convertView.findViewById(R.id.quantity);
holder.ok = (Button)convertView.findViewById(R.id.btn_ok);
holder.imgEdit.setVisibility(View.GONE);
holder.qty.setVisibility(View.GONE);
holder.ok.setVisibility(View.GONE);
holder.ok.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
data.get(i).qty = 1;
}
});
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
//holder.imgQueue.setTag(position);
imageLoader.displayImage("file://" + data.get(i).sdcardPath, holder.imgQueue, new SimpleImageLoadingListener() {
#Override
public void onLoadingStarted(String imageUri, View view) {
holder.imgQueue.setImageResource(R.drawable.no_media);
super.onLoadingStarted(imageUri, view);
}
});
if (isActionMultiplePick) {
holder.imgEdit.setSelected(data.get(i).isSeleted);
holder.qty.setSelected(data.get(i).isSeleted);
holder.ok.setSelected(data.get(i).isSeleted);
Log.d("Position Data", data.get(i).toString());
Log.d("Position", String.valueOf(i));
}
return convertView;
}
public void addAll(ArrayList<CustomGallery> files) {
try {
this.data.clear();
this.data.addAll(files);
} catch (Exception e) {
e.printStackTrace();
}
notifyDataSetChanged();
}
public ArrayList getAll(){
return data;
}
}
and here is the service
public class UploadService extends Service {
private static String LOG_TAG = "BoundService";
private IBinder mBinder = new MyBinder();
ArrayList<CustomGallery> listOfPhotos;
int i=0;
ImageLoader imageLoader;
NotificationManager manager;
Notification myNotication;
String response_str=null;
long totalprice=0;
Notification.Builder builder;
SelectedAdapter_Test selectedAdapter;
String strsize,strtype,usermail,total,strmrp,strprice,strlab,strcity,abc,strdel_type,struname,imageName;
#Nullable
#Override
public IBinder onBind(Intent intent) {
Log.v(LOG_TAG, "in onBind");
return mBinder;
}
#Override
public void onRebind(Intent intent) {
Log.v(LOG_TAG, "in onRebind");
super.onRebind(intent);
}
#Override
public boolean onUnbind(Intent intent) {
Log.v(LOG_TAG, "in onUnbind");
return true;
}
#Override
public void onCreate() {
super.onCreate();
}
#Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
selectedAdapter = new SelectedAdapter_Test(getApplicationContext(), imageLoader);
Toast.makeText(UploadService.this, "Service Started ", Toast.LENGTH_SHORT).show();
manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
listOfPhotos = (ArrayList<CustomGallery>) intent.getSerializableExtra("listof");
strsize = intent.getStringExtra("strsize");
strtype = intent.getStringExtra("strtype");
usermail = intent.getStringExtra("user_mail");
strmrp = intent.getStringExtra("strmrp");
strprice = intent.getStringExtra("strprice");
strlab = intent.getStringExtra("strlab");
strcity = intent.getStringExtra("strcity");
struname = intent.getStringExtra("strusername");
strdel_type = intent.getStringExtra("strdel_type");
abc = intent.getStringExtra("foldername");
// selectedAdapter.Pbbar(view);
Intent intn = new Intent("com.dhruva.eprintpost.digitalPrinting");
PendingIntent pendingIntent = PendingIntent.getActivity(UploadService.this, 1, intn, 0);
builder = new Notification.Builder(UploadService.this);
builder.setAutoCancel(true);
builder.setOngoing(true);
builder.setContentTitle("Uploading Photos");
builder.setContentText("Uploading PhotoPrinting Images");
builder.setSmallIcon(R.drawable.ic_launcher);
builder.setContentIntent(pendingIntent);
builder.setOngoing(true);
for( i = 0 ; i<listOfPhotos.size();i++) {
try {
File f = new File(listOfPhotos.get(i).sdcardPath.toString());
//Toast.makeText(UploadService.this, "aa "+listOfPhotos.get(i).sdcardPath, Toast.LENGTH_SHORT).show();
int j=i+1;
builder.setSubText("Uploading " + j + " of " + listOfPhotos.size() + " image"); //API level 16
j++;
Toast.makeText(UploadService.this, "i is = "+i, Toast.LENGTH_SHORT).show();
builder.build();
myNotication = builder.getNotification();
manager.notify(11, myNotication);
imageName = f.getName();
totalprice = totalprice + Long.parseLong(strprice);
total = String.valueOf(totalprice);
Log.v("Abhijit", "" + totalprice);
String responseString = null;
final HttpClient httpclient = new DefaultHttpClient();
final HttpPost httppost = new HttpPost("http://abcdefg.com/abcd/UploadFile?foldername=" + abc); //TODO - to hit URL);
try {
AndroidMultiPartEntity entity = new AndroidMultiPartEntity(
new AndroidMultiPartEntity.ProgressListener() {
#Override
public void transferred(long num) {
}
});
File sourceFile = new File(listOfPhotos.get(i).sdcardPath);
Toast.makeText(UploadService.this, "aa "+sourceFile.getName(), Toast.LENGTH_SHORT).show();
// Adding file data to http body
entity.addPart("image", new FileBody(sourceFile));
entity.addPart("foldername", new StringBody(abc));
entity.addPart("size",
new StringBody(strsize));
entity.addPart("type",
new StringBody(strtype));
entity.addPart("username",
new StringBody(usermail));
entity.addPart("total",
new StringBody(total));
entity.addPart("mrp",
new StringBody(strmrp));
entity.addPart("price",
new StringBody(strprice));
entity.addPart("lab",
new StringBody(strlab));
Toast.makeText(UploadService.this, "aa Ky Ho raha hai bhai", Toast.LENGTH_SHORT).show();
entity.addPart("city",
new StringBody(strcity));
entity.addPart("imagename",
new StringBody(imageName));
entity.addPart("deltype",
new StringBody(strdel_type));
String initflag = String.valueOf(i + 1);
entity.addPart("initflag",
new StringBody(initflag));
entity.addPart("lab_username",
new StringBody(struname));
// totalSize = entity.getContentLength();
httppost.setEntity(entity);
Thread thread = new Thread(new Runnable() {
public void run() {
try {
HttpResponse response = httpclient.execute(httppost);
HttpEntity r_entity = response.getEntity();
response_str = EntityUtils.toString(r_entity);
if (r_entity != null) {
Toast.makeText(UploadService.this, "SSS"+response_str, Toast.LENGTH_SHORT).show();
}
} catch (IOException e) {
e.printStackTrace();
}catch(Exception e)
{
e.printStackTrace();
}
}
});
thread.start();
Toast.makeText(UploadService.this, "SSS"+response_str, Toast.LENGTH_SHORT).show();
} catch (IOException e) {
responseString = e.toString();
Toast.makeText(UploadService.this, "Exception Occured2 ", Toast.LENGTH_SHORT).show();
}catch(Exception e)
{
Toast.makeText(UploadService.this, "Exception Occured 3", Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
}
return Service.START_NOT_STICKY;
}
public class MyBinder extends Binder {
UploadService getService() {
return UploadService.this;
}
}
}
Here i want to call pbbar function from adapter class but i am unable to send view parameter to function from server.
Please help me i am new to android
another problem is that the value in notification is not changing it take last value of i throughout the execuation.
i want to update the value of i according to the successful upload image
I have a failed binder transaction error when the app quits abnormally,but there is nothing in intent.
The images of every xml are lower than 40K,so I think it's not the problem of images.
This is my code.
... ...
public class MainActivity extends Activity implements OnClickListener{
private SlideMenu slideMenu;
static Socket socket;
private TextView titleName;
private RelativeLayout container;
private Map<String, String> mainleft;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mainleft = new LinkedHashMap<String, String>();
titleName = (TextView)findViewById(R.id.title_bar_name);
container = (RelativeLayout)findViewById(R.id.container);
slideMenu = (SlideMenu) findViewById(R.id.slide_menu);
ImageView menuImg = (ImageView) findViewById(R.id.title_bar_menu_btn);
menuImg.setOnClickListener(this);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
TelephonyManager telephonyManager = (TelephonyManager) this.getSystemService(Context.TELEPHONY_SERVICE);
String IMEI = telephonyManager.getDeviceId();
System.out.println("IMEI:" + IMEI);
try {
FragmentViewall fragment1 = new FragmentViewall(getBaseContext(),"zhuxitong.xml");
getFragmentManager().beginTransaction().replace(R.id.container, fragment1).commit();
slideMenu.closeMenu();
titleName.setText((CharSequence) "zhuxitong");
container.setBackgroundColor(Color.WHITE);
InputStream input = getResources().getAssets().open("mainleftcfg.xml");
XmlPullParser pullParser = Xml.newPullParser();
pullParser.setInput(input, "UTF-8");
int event = pullParser.getEventType();
String[] temp = null;
while (event != XmlPullParser.END_DOCUMENT)
{
switch (event)
{
case XmlPullParser.START_DOCUMENT:
break;
case XmlPullParser.START_TAG:
if("item".equals(pullParser.getName()))
{
temp = new String[2];
}
if ("name".equals(pullParser.getName()))
temp[0] = new String(pullParser.nextText());
if ("xmlname".equals(pullParser.getName()))
temp[1] = new String(pullParser.nextText());
break;
case XmlPullParser.END_TAG:
if("item".equals(pullParser.getName()))
{
mainleft.put(temp[0], temp[1]);
temp = null;
}
break;
}
event = pullParser.next();
}
} catch (XmlPullParserException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
initView();
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.title_bar_menu_btn:
if (slideMenu.isMainScreenShowing()) {
slideMenu.openMenu();
} else {
slideMenu.closeMenu();
}
break;
}
}
private int initView()
{
new Thread() {
public void run() {
String serverIP = LoginActivity.socketipValue;
String serverDK = LoginActivity.socketdkValue;
try {
socket = new Socket(serverIP, Integer.parseInt(serverDK));
} catch (NumberFormatException e) {
e.printStackTrace();
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}.start();
View line = new View(this);
line.setBackgroundResource(R.drawable.ic_shelf_category_divider);
Drawable drawable= getResources().getDrawable(R.drawable.ic_category_mark2);
drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
LinearLayout linearLayout = (LinearLayout) findViewById(R.id.leftq);
Iterator iter = mainleft.entrySet().iterator();
while (iter.hasNext())
{
Map.Entry entry = (Map.Entry) iter.next();
final String temp = (String)entry.getValue();
final String temp2 = (String)entry.getKey();
TextView textt = new TextView(this);
textt.setText((CharSequence) entry.getKey());
textt.setTextColor(Color.WHITE);
textt.setTextSize(18);
textt.setGravity(Gravity.CENTER);
textt.setBackgroundResource(R.drawable.selector_category_item);
textt.setCompoundDrawables(drawable,null,null,null);
textt.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
FragmentViewall fragment1 = new FragmentViewall(getBaseContext(), temp);
getFragmentManager().beginTransaction().replace(R.id.container, fragment1).commit();
slideMenu.closeMenu();
titleName.setText((CharSequence) temp2);
container.setBackgroundColor(Color.WHITE);
}
});
linearLayout.addView(textt);
}
TextView texttv = new TextView(this);
texttv.setText(getResources().getString(R.string.g6c1_video));
texttv.setTextColor(Color.WHITE);
texttv.setTextSize(18);
texttv.setGravity(Gravity.CENTER);
texttv.setBackgroundResource(R.drawable.ic_item_selected_bg);
texttv.setCompoundDrawables(drawable,null,null,null);
texttv.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
videoontimeFragment fragment1 = new videoontimeFragment();
getFragmentManager().beginTransaction().replace(R.id.container, fragment1).commit();
slideMenu.closeMenu();
titleName.setText(getResources().getString(R.string.g6c1_video));
container.setBackgroundColor(Color.WHITE);
}
});
linearLayout.addView(texttv);
TextView texttb = new TextView(this);
texttb.setText(getResources().getString(R.string.g6c2_video));
texttb.setTextColor(Color.WHITE);
texttb.setTextSize(18);
texttb.setGravity(Gravity.CENTER);
texttb.setBackgroundResource(R.drawable.ic_item_selected_bg);
texttb.setCompoundDrawables(drawable,null,null,null);
texttb.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
videobackFragment fragment1 = new videobackFragment();
getFragmentManager().beginTransaction().replace(R.id.container, fragment1).commit();
slideMenu.closeMenu();
titleName.setText(getResources().getString(R.string.g6c2_video));
container.setBackgroundColor(Color.WHITE);
}
});
linearLayout.addView(texttb);
TextView textt = new TextView(this);
textt.setText(getResources().getString(R.string.action_loginout));
textt.setTextColor(Color.WHITE);
textt.setTextSize(18);
textt.setGravity(Gravity.CENTER);
textt.setBackgroundResource(R.drawable.selector_category_item);
textt.setCompoundDrawables(drawable,null,null,null);
textt.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
LoginActivity.sp.edit().putBoolean("AUTO_ISCHECK", false).commit();
LoginActivity.sp.edit().clear().commit();
Intent intent = new Intent(MainActivity.this,LoginActivity.class);
MainActivity.this.startActivity(intent);
MainActivity.this.finish();
slideMenu.closeMenu();
}
});
linearLayout.addView(textt);
TextView textt2 = new TextView(this);
textt2.setText(getResources().getString(R.string.action_settings));
textt2.setTextColor(Color.WHITE);
textt2.setTextSize(18);
textt2.setGravity(Gravity.CENTER);
textt2.setBackgroundResource(R.drawable.selector_category_item);
textt2.setCompoundDrawables(drawable,null,null,null);
textt2.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
AlertDialog.Builder builder = new Builder(MainActivity.this);
builder.setMessage("1.0");
builder.setPositiveButton("Confirm",
new android.content.DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
builder.create().show();
slideMenu.closeMenu();
}
});
linearLayout.addView(textt2);
return 0;
}
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
dialog();
return true;
}
return true;
}
protected void dialog() {
AlertDialog.Builder builder = new Builder(MainActivity.this);
builder.setMessage("Quit?");
builder.setTitle("tips");
builder.setPositiveButton("Confirm",
new android.content.DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
android.os.Process.killProcess(android.os.Process.myPid());
}
});
builder.setNegativeButton("Cancel",
new android.content.DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
builder.create().show();
}
}
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();
}
});
I'm making an app that sends a notification to the status bar, it sends the notification when stepping through the code in the debugger, however it never sends the notification when run in realtime.
Here is my runnable that generates the notification, again when stepping through this code in the debugger the notification runs however in realtime nothing happens.
public class NewsEvents_Service extends Service {
private static final String NEWSEVENTS = "newsevents";
private static final String KEYWORDS = "keywords";
private NotificationManager mNM;
private ArrayList<NewsEvent> neList;
private int count;
#Override
public void onCreate() {
mNM = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
neList = new ArrayList<NewsEvent>();
getKeywords();
//getNewsEvents();
Thread thr = new Thread(null, mTask, "NewsEvents_Service");
thr.start();
Log.d("Thread", "IT STARTED!!!!!!????!!!!!!!!!!!!!!!?!!?");
}
#Override
public void onDestroy() {
// Cancel the notification -- we use the same ID that we had used to start it
mNM.cancel(R.string.ECS);
// Tell the user we stopped.
Toast.makeText(this, "Service Done", Toast.LENGTH_SHORT).show();
}
/**
* The function that runs in our worker thread
*/
Runnable mTask = new Runnable() {
public void run() {
getNewsEventsFromWeb();
for(NewsEvent ne : neList){
Log.d("Thread Running", "Service Code running!!!!!!!!!!!!!!!");
String body = ne.getBody().replaceAll("\\<.*?>", "");
String title = ne.getTitle();
for(String s : keyWordList){
if(body.contains(s) || body.contains(s.toLowerCase()) ||
title.contains(s) || title.contains(s.toLowerCase())){
ne.setInterested(true);
}
}
if(ne.isInterested() == true ){
Notification note = new Notification(R.drawable.icon,
"New ECS News Event", System.currentTimeMillis());
Intent i = new Intent(NewsEvents_Service.this, FullNewsEvent.class);
i.putExtra("ne", ne);
PendingIntent pi = PendingIntent.getActivity(NewsEvents_Service.this, 0,
i, 0);
note.setLatestEventInfo(NewsEvents_Service.this, "New Event", ne.getTitle(), pi);
note.flags = Notification.FLAG_AUTO_CANCEL;
mNM.notify(R.string.ECS, note);
}
}
}
};
#Override
public IBinder onBind(Intent intent) {
return mBinder;
}
/**
* Show a notification while this service is running.
*/
private void getNewsEventsFromWeb() {
HttpClient client = new DefaultHttpClient();
HttpGet get;
try {
get = new HttpGet(getString(R.string.jsonnewsevents));
ResponseHandler<String> response = new BasicResponseHandler();
String responseBody = client.execute(get, response);
String page = responseBody;
Bundle data = new Bundle();
data.putString("page",page);
Message msg = new Message();
msg.setData(data);
handler.sendMessage(msg);
}
catch (Throwable t) {
Log.d("UpdateNews", "PROBLEMS");
}
}
private Handler handler = new Handler(){
#Override
public void handleMessage(Message msg) {
String page = msg.getData().getString("page");
try {
JSONArray parseArray = new JSONArray(page);
for (int i = 0; i < parseArray.length(); i++) {
JSONObject jo = parseArray.getJSONObject(i);
String title = jo.getString("title");
String body =jo.getString("body");
String pd = jo.getString("postDate");
String id = jo.getString("id");
NewsEvent ne = new NewsEvent(title, pd , body, id);
boolean unique = true;
for(NewsEvent ne0 : neList){
if(ne.getId().equals(ne0.getId())){
unique = false;
}else{
unique = true;
}
}
if(unique == true){
neList.add(ne);
}
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
private ArrayList<String> keyWordList;
public void getNewsEvents(){
try {
InputStream fi = openFileInput(NEWSEVENTS);
if (fi!=null) {
ObjectInputStream in = new ObjectInputStream(fi);
neList = (ArrayList<NewsEvent>) in.readObject();
in.close();
}
}
catch (java.io.FileNotFoundException e) {
// that's OK, we probably haven't created it yet
}
catch (Throwable t) {
Toast
.makeText(this, "Exception: "+t.toString(), Toast.LENGTH_LONG)
.show();
}
if(neList == null){
neList = new ArrayList<NewsEvent>();
}
}
public ArrayList<String> getKeywords(){
try {
InputStream fi = openFileInput(KEYWORDS);
if (fi!=null) {
ObjectInputStream in = new ObjectInputStream(fi);
keyWordList = (ArrayList<String>) in.readObject();
in.close();
}
}
catch (java.io.FileNotFoundException e) {
// that's OK, we probably haven't created it yet
}
catch (Throwable t) {
Toast
.makeText(this, "Exception: "+t.toString(), Toast.LENGTH_LONG)
.show();
}
if(keyWordList == null){
keyWordList = new ArrayList<String>();
return keyWordList;
}
return keyWordList;
}
/**
* This is the object that receives interactions from clients. See RemoteService
* for a more complete example.
*/
private final IBinder mBinder = new Binder() {
#Override
protected boolean onTransact(int code, Parcel data, Parcel reply,
int flags) throws RemoteException {
return super.onTransact(code, data, reply, flags);
}
};
}
Here is my activity that schedules the service to run
public class NewsEvents extends ListActivity{
private URL JSONNewsEvents;
private ArrayList<NewsEvent> neList;
private ArrayList<String> keyWordList;
private Worker worker;
private NewsEvents ne;
public static final String KEYWORDS = "keywords";
private static final String NEWSEVENTS = "newsevents";
public static final int ONE_ID = Menu.FIRST+1;
private PendingIntent newsAlarm;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.newsevents);
ne = this;
neList = new ArrayList<NewsEvent>();
try {
JSONNewsEvents = new URL(getString(R.string.jsonnewsevents));
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
worker = new Worker(handler, this);
setListAdapter(new IconicAdapter());
getKeywords();
worker.execute(JSONNewsEvents);
}
#Override
protected void onStop() {
super.onStop();
writeNewsEvents() ;
}
#Override
protected void onPause(){
super.onPause();
writeNewsEvents();
}
private void writeNewsEvents() {
try {
OutputStream fi = openFileOutput(NEWSEVENTS, 0);
if (fi!=null) {
ObjectOutputStream out = new ObjectOutputStream(fi);
out.writeObject(neList);
out.close();
}
}
catch (java.io.FileNotFoundException e) {
// that's OK, we probably haven't created it yet
}
catch (Throwable t) {
Toast
.makeText(this, "Exception: "+t.toString(), Toast.LENGTH_LONG)
.show();
}
}
/**
* #return
*/
public ArrayList<String> getKeywords(){
try {
InputStream fi = openFileInput(KEYWORDS);
if (fi!=null) {
ObjectInputStream in = new ObjectInputStream(fi);
keyWordList = (ArrayList<String>) in.readObject();
in.close();
}
}
catch (java.io.FileNotFoundException e) {
// that's OK, we probably haven't created it yet
}
catch (Throwable t) {
Toast
.makeText(this, "Exception: "+t.toString(), Toast.LENGTH_LONG)
.show();
}
if(keyWordList == null){
keyWordList = new ArrayList<String>();
return keyWordList;
}
return keyWordList;
}
public void onListItemClick(ListView parent, View v,
int position, long id) {
startFullNewsEvent(neList.get(position));
}
/**
* #param newsEvent
*/
public void startFullNewsEvent(NewsEvent ne) {
Intent intent = new Intent(this, FullNewsEvent.class);
intent.putExtra("ne", ne);
this.startActivity(intent);
finish();
}
private Handler handler = new Handler(){
#Override
public void handleMessage(Message msg) {
String page = msg.getData().getString("page");
try {
JSONArray parseArray = new JSONArray(page);
for (int i = 0; i < parseArray.length(); i++) {
JSONObject jo = parseArray.getJSONObject(i);
String title = jo.getString("title");
String body =jo.getString("body");
String pd = jo.getString("postDate");
String id = jo.getString("id");
NewsEvent ne = new NewsEvent(title, pd , body, id);
boolean unique = true;
for(NewsEvent ne0 : neList){
if(ne.getId().equals(ne0.getId())){
unique = false;
}else{
unique = true;
}
}
if(unique == true){
neList.add(ne);
}
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ne.setListAdapter(new IconicAdapter());
}
};
public class IconicAdapter extends ArrayAdapter<NewsEvent> {
IconicAdapter() {
super(NewsEvents.this, R.layout.rownews, neList);
}
public View getView(int position, View convertView,ViewGroup parent) {
LayoutInflater inflater=getLayoutInflater();
View row=inflater.inflate(R.layout.rownews, parent, false);
TextView label=(TextView)row.findViewById(R.id.label);
ImageView image= (ImageView)row.findViewById(R.id.icon);
String body = neList.get(position).getBody();
body.replaceAll("\\<.*?>", "");
String title = neList.get(position).getTitle();
for(String s : keyWordList){
if(body.contains(s) || body.contains(s.toLowerCase()) ||
title.contains(s) || title.contains(s.toLowerCase())){
neList.get(position).setInterested(true);
}
}
if(neList.get(position).isInterested() == true){
image.setImageResource(R.drawable.star);
}
label.setText(neList.get(position).getTitle());
return(row);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
populateMenu(menu);
return(super.onCreateOptionsMenu(menu));
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
return(applyMenuChoice(item) || super.onOptionsItemSelected(item));
}
//Creates our activity to menus
private void populateMenu(Menu menu) {
menu.add(Menu.NONE, ONE_ID, Menu.NONE, "Home");
}
private boolean applyMenuChoice(MenuItem item) {
switch (item.getItemId()) {
case ONE_ID: startHome(); return(true);
}
return(false);
}
public void startHome() {
Intent intent = new Intent(this, ECS.class);
this.startActivity(intent);
finish();
}
}
Race conditions, I'm making an HTTP Request and then handing it off to a handler, immediately following that I iterator through the array list, which at full speed is empty because the HTTP hasn't completed. In debugging it all slows down so the HTTP is complete and all works well.
Threads and Network Connections, a deadly combination.