Related
I'm Using Yandex Translator in my app, it works great if i'm using Activity, But when i add it to fragment , the app crashes before the launch.
Also no errors shown in the code , like everything is good, what could be the problem :
I looked for similar answers here, but i got nothing, no one had this issue before using fragments.
And here is the code for fragment :
public class FavoritesFragment extends Fragment implements TextToSpeech.OnInitListener{
private TextView header, toText, toLabel, fromLabel;
private ImageView micFrom, volFrom, volTo, reverse;
private EditText fromText;
private CircleButton convertBTN;
private CircleButton convertLayout;
private final int REQ_CODE_SPEECH_INPUT = 100;
private final int SR_CODE = 123;
private String ENGLISH_CONSTANT = "";
private String TURKISH_CONSTANT = "";
private String ENGLISH_CONVERT = "";
private String TURKISH_CONVERT = "";
private String TURKISH_CODE = "";
private String currentFrom = "";
TextToSpeech ttsEnglish, ttsTURKISH;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_favorites, container, false);
setUpInitialConstants();
setUpInteraction();
setUpSpeakingListeners();
setUpListeners();
return v;
}
private void setUpInitialConstants() {
ENGLISH_CONSTANT = ("ENGLISH");
TURKISH_CONSTANT = ("TURKISH");
ENGLISH_CONVERT = ("en") + "-" + ("tr");//"en-zh";
TURKISH_CONVERT = ("tr") + "-" + ("en");
//"zh-en";
TURKISH_CODE = ("tr");
currentFrom = ENGLISH_CONSTANT;
}
private void setUpSpeakingListeners() {
ttsEnglish = new TextToSpeech(getContext().getApplicationContext(), new TextToSpeech.OnInitListener() {
#Override
public void onInit(int status) {
// TODO Auto-generated method stub
if (status == TextToSpeech.SUCCESS) {
int result = ttsEnglish.setLanguage(Locale.ENGLISH);
if (result == TextToSpeech.LANG_MISSING_DATA ||
result == TextToSpeech.LANG_NOT_SUPPORTED) {
Log.e("error", "This Language is not supported");
} else {
//ConvertTextToSpeech();
}
} else
Log.e("error", "Initilization Failed!");
}
});
ttsTURKISH = new TextToSpeech(getContext().getApplicationContext(), new TextToSpeech.OnInitListener() {
#Override
public void onInit(int status) {
// TODO Auto-generated method stub
if (status == TextToSpeech.SUCCESS) {
Locale locale = new Locale("tr-TR");
int result = ttsTURKISH.setLanguage(locale);
if (result == TextToSpeech.LANG_MISSING_DATA ||
result == TextToSpeech.LANG_NOT_SUPPORTED) {
Log.e("error", "not supported");
} else {
//ConvertTextToSpeech();
}
} else
Log.e("error", "Initilization Failed!");
}
});
}
#SuppressLint("ClickableViewAccessibility")
private void setUpListeners() {
convertLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Vibrator vibrator = (Vibrator) getActivity().getSystemService(Context.VIBRATOR_SERVICE);
vibrator.vibrate(200);
callReverse();
}
});
micFrom.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Vibrator vibrator = (Vibrator) getActivity().getSystemService(Context.VIBRATOR_SERVICE);
vibrator.vibrate(200);
askSpeechInput(currentFrom);
}
});
volFrom.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Vibrator vibrator = (Vibrator) getActivity().getSystemService(Context.VIBRATOR_SERVICE);
vibrator.vibrate(200);
ConvertTextToSpeech(currentFrom, fromText.getText().toString());
}
});
volTo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Vibrator vibrator = (Vibrator) getActivity().getSystemService(Context.VIBRATOR_SERVICE);
vibrator.vibrate(200);
String currentFromR = reverseCurrentFrom(currentFrom);
ConvertTextToSpeech(currentFromR, toText.getText().toString());
}
});
convertBTN.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Vibrator vibrator = (Vibrator) getActivity().getSystemService(Context.VIBRATOR_SERVICE);
vibrator.vibrate(200);
if (currentFrom.equals(ENGLISH_CONSTANT))
translateText(fromText.getText().toString(), ENGLISH_CONVERT);
else
translateText(fromText.getText().toString(), TURKISH_CONVERT);
}
});
toText.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Vibrator vibrator = (Vibrator) getActivity().getSystemService(Context.VIBRATOR_SERVICE);
vibrator.vibrate(200);
if (copyToClipboard(getContext().getApplicationContext(), toText.getText().toString())) {
if (currentFrom.equals(ENGLISH_CONSTANT)) {
Toast.makeText(getContext().getApplicationContext(), ("copied"), Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getContext().getApplicationContext(), (" copied successfully "), Toast.LENGTH_SHORT).show();
}
}
}
});
fromText.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
fromText.setFocusableInTouchMode(true);
return false;
}
});
}
private String reverseCurrentFrom(String currentFrom) {
if (currentFrom.equals(ENGLISH_CONSTANT)) {
return TURKISH_CONSTANT;
} else return ENGLISH_CONSTANT;
}
private void callReverse() {
if (currentFrom.equals(ENGLISH_CONSTANT)) {
currentFrom = TURKISH_CONSTANT;
//header.setText(getString(R.string.convertHeaderR));
fromLabel.setText(("TURKISH"));
fromText.setHint(("push to talk"));
toLabel.setText(("English"));
toText.setText(("Click translate Button to get English text"));
} else {
currentFrom = ENGLISH_CONSTANT;
//header.setText(getString(R.string.convertHeader));
fromLabel.setText(("English"));
fromText.setHint(("Speak or type text here"));
toLabel.setText(("TURKISH"));
toText.setText(("click to translate"));
}
fromText.setText("");
fromText.setFocusable(false);
}
private void setUpInteraction() {
this.getActivity().getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
toText = getView().findViewById(R.id.toText);
toLabel = getView().findViewById(R.id.toLabel);
fromLabel = getView().findViewById(R.id.fromLabel);
micFrom = getView().findViewById(R.id.micFrom);
volFrom = getView().findViewById(R.id.volFrom);
volTo = getView().findViewById(R.id.toVol);
convertBTN = getView().findViewById(R.id.convertBTN);
fromText = getView().findViewById(R.id.fromText);
convertLayout = getView().findViewById(R.id.swapLanguage);
fromText.setFocusable(false);
currentFrom = TURKISH_CONSTANT;
callReverse();
}
private void ConvertTextToSpeech(String lang_type, String text) {
if (text == null || "".equals(text)) {
if (lang_type.equals(ENGLISH_CONSTANT)) {
text = ("Content not available");
} else {
text = ("something wrong !");
}
}
if (lang_type.equals(ENGLISH_CONSTANT)) {
ttsEnglish.speak(text, TextToSpeech.QUEUE_FLUSH, null);
} else {
ttsTURKISH.speak(text, TextToSpeech.QUEUE_FLUSH, null);
}
}
private void askSpeechInput(String lang_type) {
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
if (lang_type.equals(ENGLISH_CONSTANT)) {
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.ENGLISH);
intent.putExtra(RecognizerIntent.EXTRA_PROMPT,
"Hi speak something");
startActivityForResult(intent, REQ_CODE_SPEECH_INPUT);
} else {
//Specify language
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, TURKISH_CODE);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, TURKISH_CODE);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_PREFERENCE, TURKISH_CODE);
intent.putExtra(RecognizerIntent.EXTRA_SUPPORTED_LANGUAGES, TURKISH_CODE);
intent.putExtra(RecognizerIntent.EXTRA_ONLY_RETURN_LANGUAGE_PREFERENCE, TURKISH_CODE);
intent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE, TURKISH_CODE);
intent.putExtra(RecognizerIntent.EXTRA_RESULTS, TURKISH_CODE);
intent.putExtra(RecognizerIntent.EXTRA_PROMPT, ("speak please"));
startActivityForResult(intent, SR_CODE);
}
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case REQ_CODE_SPEECH_INPUT: {
if (resultCode == RESULT_OK && null != data) {
ArrayList<String> result = data
.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
fromText.setText(result.get(0));
}
break;
}
case SR_CODE: {
if (resultCode == RESULT_OK) {
if (data != null) {
ArrayList<String> nBestList = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
String bestResult = nBestList.get(0);
fromText.setText(bestResult);
}
}
break;
}
}
if (currentFrom.equals(ENGLISH_CONSTANT))
translateText(fromText.getText().toString(), ENGLISH_CONVERT);
else
translateText(fromText.getText().toString(), TURKISH_CONVERT);
}
#Override
public void onInit(int status) {
if (status == TextToSpeech.SUCCESS) {
} else {
Log.e("TTS", "Initialization failed");
}
}
String text_to_return = "";
private String translateText(final String text, final String lang) {
class getQData extends AsyncTask<String, String, String> {
ProgressDialog loading;
String ROOT_URL = "https://translate.yandex.net";
Retrofit adapter = new Retrofit.Builder()
.baseUrl(ROOT_URL)
.addConverterFactory(JacksonConverterFactory.create())
.build();
APICalls api = adapter.create(APICalls.class);
#Override
protected void onPreExecute() {
super.onPreExecute();
showPD();
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
}
#Override
protected String doInBackground(String... params) {
text_to_return = "";
String key = translator_Constants.MY_KEY;
Call<TranslateResponse> call = api.translate(key, text, lang);
call.enqueue(new Callback<TranslateResponse>() {
#Override
public void onResponse(retrofit.Response<TranslateResponse> response, Retrofit retrofit) {
//loading.dismiss();
hidePD();
Log.d("succ", "onResponse:code" + String.valueOf(response.code()));
Log.d("error mesg", String.valueOf(response.message()));
switch (response.code()) {
case 200:
TranslateResponse tr = response.body();
text_to_return = tr.getText().get(0);
toText.setText(text_to_return);
String currentFromR = reverseCurrentFrom(currentFrom);
ConvertTextToSpeech(currentFromR, toText.getText().toString());
break;
default:
if (currentFrom.equals(ENGLISH_CONSTANT))
Toast.makeText(getContext().getApplicationContext(), ("Please Try Again"), Toast.LENGTH_SHORT).show();
else
Toast.makeText(getContext().getApplicationContext(), ("again"), Toast.LENGTH_SHORT).show();
break;
}
}
#Override
public void onFailure(Throwable t) {
pd.dismiss();
Log.d("retro error", t.getMessage());
if (currentFrom.equals(ENGLISH_CONSTANT))
Toast.makeText(getContext().getApplicationContext(), ("Failed to Convert!Check Internet Connection"), Toast.LENGTH_SHORT).show();
else
Toast.makeText(getContext().getApplicationContext(), ("no connexion"), Toast.LENGTH_SHORT).show();
}
});
return text_to_return;
}
}
getQData ru = new getQData();
try {
ru.execute().get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
return text_to_return;
}
ProgressDialog pd;
private void showPD() {
pd = new ProgressDialog(getActivity());
if (currentFrom.equals(ENGLISH_CONSTANT)) {
pd.setMessage(("Patience, We are translating…"));
} else {
pd.setMessage(("translating ..."));
}
pd.show();
}
private void hidePD() {
pd.dismiss();
}
public boolean copyToClipboard(Context context, String text) {
try {
int sdk = android.os.Build.VERSION.SDK_INT;
if (sdk < android.os.Build.VERSION_CODES.HONEYCOMB) {
android.text.ClipboardManager clipboard = (android.text.ClipboardManager) context
.getSystemService(CLIPBOARD_SERVICE);
clipboard.setText(text);
} else {
android.content.ClipboardManager clipboard = (android.content.ClipboardManager) context
.getSystemService(CLIPBOARD_SERVICE);
android.content.ClipData clip = android.content.ClipData
.newPlainText("copy", text);
clipboard.setPrimaryClip(clip);
}
return true;
} catch (Exception e) {
return false;
}
}
}
Call setupInteraction() from onViewCreated(), not from onCreateView(). You are trying to use getView(), which will not work until onCreateView() returns.
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?
In android , i create a application based on RFID Card Reader on mobile. While i tapping Card on RFID Reader it generates same value at many times until the card untapped from the reader.
I want to show only one value per tapping card on RFID reader. Here i place my code and Sample snapshot of my application.
Guide me and tell solution for my problem.
public static MediaPlayer mp;
FT_Device ftDev = null;
int DevCount = -1;
int currentIndex = -1;
int openIndex = 0;
/*graphical objects*/
EditText readText;
Button readEnButton;
static int iEnableReadFlag = 1;
/*local variables*/
int baudRate; /*baud rate*/
byte stopBit; /*1:1stop bits, 2:2 stop bits*/
byte dataBit; /*8:8bit, 7: 7bit*/
byte parity; /* 0: none, 1: odd, 2: even, 3: mark, 4: space*/
byte flowControl; /*0:none, 1: flow control(CTS,RTS)*/
int portNumber; /*port number*/
long wait_sec=3000;
byte[] readData; //similar to data.
public static final int readLength = 1024; // changed length from 512
public int iavailable = 0;
char[] readDataToText;
//char readDataToTextSudha;
public boolean bReadThreadGoing = false;
public readThread read_thread;
public static D2xxManager ftD2xx = null;
boolean uart_configured = false;
// Empty Constructor
public MainActivity() {
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
readData = new byte[readLength];
readDataToText = new char[readLength];
//readDataToTextSudha = new char;
readText = (EditText) findViewById(R.id.ReadValues);
readText.setInputType(0);
readEnButton = (Button) findViewById(R.id.readEnButton);
baudRate = 9600;
/* default is stop bit 1 */
stopBit = 1;
/* default data bit is 8 bit */
dataBit = 8;
/* default is none */
parity = 0;
/* default flow control is is none */
flowControl = 0;
portNumber = 1;
try {
ftD2xx = D2xxManager.getInstance(this);
} catch (D2xxManager.D2xxException ex) {
ex.printStackTrace();
}
//Opening Coding
if (DevCount <= 0) {
createDeviceList();
} else {
connectFunction();
}
//Configuration coding
if (DevCount <= 0 || ftDev == null) {
Toast.makeText(getApplicationContext(), "Device not open yet...", Toast.LENGTH_SHORT).show();
} else {
SetConfig(baudRate, dataBit, stopBit, parity, flowControl);
}
readEnButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (DevCount <= 0 || ftDev == null) {
Toast.makeText(getApplicationContext(), "Device not open yet...", Toast.LENGTH_SHORT).show();
} else if (uart_configured == false) {
Toast.makeText(getApplicationContext(), "UART not configure yet...", Toast.LENGTH_SHORT).show();
return;
} else {
EnableRead();
}
}
});
}
public void EnableRead() {
iEnableReadFlag = (iEnableReadFlag + 1) % 2;
if (iEnableReadFlag == 1) {
ftDev.purge((byte) (D2xxManager.FT_PURGE_TX));
ftDev.restartInTask();
readEnButton.setText("Read Enabled");
Toast.makeText(getApplicationContext(),"Read Enabled",Toast.LENGTH_LONG).show();
} else {
ftDev.stopInTask();
readEnButton.setText("Read Disabled");
Toast.makeText(getApplicationContext(),"Read Disabled",Toast.LENGTH_LONG).show();
}
}
public void createDeviceList() {
int tempDevCount = ftD2xx.createDeviceInfoList(getApplicationContext());
if (tempDevCount > 0) {
if (DevCount != tempDevCount) {
DevCount = tempDevCount;
updatePortNumberSelector();
}
} else {
DevCount = -1;
currentIndex = -1;
}
};
public void disconnectFunction() {
DevCount = -1;
currentIndex = -1;
bReadThreadGoing = false;
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
if (ftDev != null) {
synchronized (ftDev) {
if (true == ftDev.isOpen()) {
ftDev.close();
}
}
}
}
public void connectFunction() {
int tmpProtNumber = openIndex + 1;
if (currentIndex != openIndex) {
if (null == ftDev) {
ftDev = ftD2xx.openByIndex(getApplicationContext(), openIndex);
} else {
synchronized (ftDev) {
ftDev = ftD2xx.openByIndex(getApplicationContext(), openIndex);
}
}
uart_configured = false;
} else {
Toast.makeText(getApplicationContext(), "Device port " + tmpProtNumber + " is already opened", Toast.LENGTH_LONG).show();
return;
}
if (ftDev == null) {
Toast.makeText(getApplicationContext(), "open device port(" + tmpProtNumber + ") NG, ftDev == null", Toast.LENGTH_LONG).show();
return;
}
if (true == ftDev.isOpen()) {
currentIndex = openIndex;
Toast.makeText(getApplicationContext(), "open device port(" + tmpProtNumber + ") OK", Toast.LENGTH_SHORT).show();
if (false == bReadThreadGoing) {
read_thread = new readThread(handler);
read_thread.start();
bReadThreadGoing = true;
}
} else {
Toast.makeText(getApplicationContext(), "open device port(" + tmpProtNumber + ") NG", Toast.LENGTH_LONG).show();
}
}
public void updatePortNumberSelector() {
if (DevCount == 2) {
Toast.makeText(getApplicationContext(), "2 port device attached", Toast.LENGTH_SHORT).show();
} else if (DevCount == 4) {
Toast.makeText(getApplicationContext(), "4 port device attached", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(), "1 port device attached", Toast.LENGTH_SHORT).show();
}
}
public void SetConfig(int baud, byte dataBits, byte stopBits, byte parity, byte flowControl) {
if (ftDev.isOpen() == false) {
Log.e("j2xx", "SetConfig: device not open");
return;
}
ftDev.setBitMode((byte) 0, D2xxManager.FT_BITMODE_RESET);
ftDev.setBaudRate(baud);
ftDev.setDataCharacteristics(dataBits, stopBits, parity);
uart_configured = true;
Toast.makeText(getApplicationContext(), "Config done", Toast.LENGTH_SHORT).show();
}
final Handler handler = new Handler() {
#Override
public void handleMessage(Message msg) {
if (iavailable > 0) {
mp = MediaPlayer.create(MainActivity.this, R.raw.beep);
mp.start();
readText.append(String.copyValueOf(readDataToText, 0, iavailable));
}
}
};
private class readThread extends Thread {
Handler mHandler;
readThread(Handler h) {
mHandler = h;
this.setPriority(Thread.MIN_PRIORITY);
}
#Override
public void run() {
int i;
while (true == bReadThreadGoing) {
try {
Thread.sleep(1000); //changed
} catch (InterruptedException e) {
}
synchronized (ftDev) {
iavailable = ftDev.getQueueStatus();
if (iavailable > 0) {
if (iavailable > readLength) {
iavailable = readLength;
}
ftDev.read(readData, iavailable,wait_sec);
for (i = 0; i < iavailable; i++) {
readDataToText[i] = (char) readData[i];
}
Message msg = mHandler.obtainMessage();
mHandler.sendMessage(msg);
}
}
}
}
}
#Override
public void onResume() {
super.onResume();
DevCount = 0;
createDeviceList();
if (DevCount > 0) {
connectFunction();
SetConfig(baudRate, dataBit, stopBit, parity, flowControl);
}
}
}
My problem would snapped here
Getting Value continuously from Reader
I want this type of value when i tap the card
If i tap some other cards, old card value replaces from the new one.
Guide me.
Thanks in Advance
I got the answer by using of Threads. When the card tapping it get some values after sleep of one or two seconds only the next value have to get from the reader.
public void run() {
int i;
while (true == bReadThreadGoing) { // Means Make sure , getting value from Reader
try {
Thread.sleep(1000); // Wait for a second to get another value.
clearText(); //clear the old value and get new value.
} catch (InterruptedException e) {
}
And clearing the edittext by using this command.
public void clearText() {
runOnUiThread(new Runnable() {
public void run() {
readText.setText("");
}
});
}
when i try to get a true/false value from a different class it seems that it is defaulting to false. here are the snippets of my code that should be the problem. the first snippet is the class i'm getting the values from, the second one is the one that is requesting that information. and at the bottom of the second class is the function that should make the class render on the apps screen but seems to not work at all every time. you should be able to understand my coding cause i practice the art of commenting profusely.
private boolean AddProb;
private boolean SubProb;
private boolean MultiProb;
private boolean DivisProb;
public int ANum = 0;
public int SNum;
public int MNum;
public int DNum;
//ProblemSelector PS = new ProblemSelector();
CheckBox checkbox1, checkbox2, checkbox3, checkbox4;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_problem_selector);
checkbox1 = (CheckBox) findViewById(R.id.checkBox1);
checkbox2 = (CheckBox) findViewById(R.id.checkBox2);
checkbox3 = (CheckBox) findViewById(R.id.checkBox3);
checkbox4 = (CheckBox) findViewById(R.id.checkBox4);
/** waits for checkbox1 to be clicked then triggers the arguments below it **/
/** also sets the lists position if the other problems for training have been selected to practice **/
checkbox1.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
if (b) {
AddProb = true;
Toast.makeText(getBaseContext(), "Addition: True", Toast.LENGTH_SHORT).show();
System.out.println("Addition: True");
if(AddProb) {
Log.d("ProblemSelector.java","AddProb did successfully change to true");
} else if(!AddProb){
Log.d("ProblemSelector.java","AddProb did not successfully change to true");
} else {
Log.d("ProblemSelector.java","Something went horribly wrong at line: 50-56");
}
} else {
AddProb = false;
Toast.makeText(getBaseContext(), "Addition: False", Toast.LENGTH_SHORT).show();
System.out.println("Addition: False");
if(AddProb) {
Log.d("ProblemSelector.java","AddProb did successfully change to false");
} else if(!AddProb) {
Log.d("ProblemSelector.java","AddProb did not successfully change to false");
} else {
Log.d("ProblemSelector.java","Something went horribly wrong at line: 61-67");
}
}
}
});
/** waits for checkbox2 to be clicked then triggers the arguments below it **/
/** also sets the lists position if the other problems for training have been selected to practice **/
checkbox2.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
if (b) {
SubProb = true;
Toast.makeText(getBaseContext(), "Subtraction: True", Toast.LENGTH_SHORT).show();
System.out.println("Subtraction: True");
if(SubProb) {
Log.d("ProblemSelector.java","SubProb did successfully change to true");
} else if(!SubProb) {
Log.d("ProblemSelector.java","SubProb did not successfully change to true");
} else {
Log.d("ProblemSelector.java","Something went horribly wrong at line: 82-88");
}
if(AddProb == false) {
SNum = 0;
}
else if(AddProb == true) {
SNum = 1;
}
} else {
SubProb = false;
Toast.makeText(getBaseContext(), "Subtraction: False", Toast.LENGTH_SHORT).show();
System.out.println("Subtraction: False");
if(SubProb) {
Log.d("ProblemSelector.java","SubProb did successfully change to false");
} else if(!SubProb) {
Log.d("ProblemSelector.java","SubProb did not successfully change to false");
} else {
Log.d("ProblemSelector.java","Something went horribly wrong at line: 99-105");
}
}
}
});
/** waits for checkbox3 to be clicked then triggers the arguments below it **/
/** also sets the lists position if the other problems for training have been selected to practice **/
checkbox3.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
if (b) {
MultiProb = true;
Toast.makeText(getBaseContext(), "Multiplication: True", Toast.LENGTH_SHORT).show();
System.out.println("Multiplication: True");
if(MultiProb) {
Log.d("ProblemSelector.java","MultiProb did successfully change to true");
} else if(!MultiProb) {
Log.d("ProblemSelector.java","MultiProb did not successfully change to true");
} else {
Log.e("ProblemSelector.java","Something went horribly wrong at line: 120-126");
}
if(AddProb == false && SubProb == false) {
MNum = 0;
}
else if(AddProb == true && SubProb == false || AddProb == false && SubProb == true) {
MNum = 1;
}
else if(AddProb == true && SubProb == true) {
MNum = 2;
}
} else {
MultiProb = false;
Toast.makeText(getBaseContext(), "Multiplication: False", Toast.LENGTH_SHORT).show();
System.out.println("Multiplication: False");
if(MultiProb) {
Log.d("ProblemSelector.java","MultiProb did successfully change to false");
} else if(!MultiProb) {
Log.d("ProblemSelector.java","MultiProb did not successfully change to false");
} else {
Log.e("ProblemSelector.java","Something went horribly wrong at line: 140-146");
}
}
}
});
/** waits for checkbox4 to be clicked then triggers the arguments below it **/
/** also sets the lists position if the other problems for training have been selected to practice **/
/** and determines if the value of the boolean for this function has changed successfully or not **/
checkbox4.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
if (b) {
DivisProb = true;
Toast.makeText(getBaseContext(), "Division: True", Toast.LENGTH_SHORT).show();
System.out.println("Division: True");
if(DivisProb) {
Log.d("ProblemSelector.java","DivisProb did successfully change to true");
} else if(!DivisProb) {
Log.d("ProblemSelector.java","DivisProb did not successfully change to true");
} else {
Log.e("ProblemSelector.java","Something went horribly wrong at line: 162-168");
}
if(AddProb == false && SubProb == false && MultiProb == false) {
DNum = 0;
}
else if(AddProb == true && SubProb == false && MultiProb == false || AddProb == false && SubProb == true && MultiProb == false || AddProb == false && SubProb == false && MultiProb == true) {
DNum = 1;
}
else if(AddProb == true && SubProb == true && MultiProb == false || AddProb == false && SubProb == true && MultiProb == true || AddProb == true && SubProb == false && MultiProb == true) {
DNum = 2;
}
else if(AddProb == true && SubProb == true && MultiProb == true) {
DNum = 3;
}
} else {
DivisProb = false;
Toast.makeText(getBaseContext(), "Division: False", Toast.LENGTH_SHORT).show();
System.out.println("Division: False");
if(DivisProb) {
Log.d("ProblemSelector.java","DivisProb did successfully change to false");
} else if(!DivisProb) {
Log.d("ProblemSelector.java","DivisProb did not successfully change to false");
} else {
Log.e("ProblemSelector.java","Something went horribly wrong at line: 184-189");
}
}
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_problem_selector, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
/** this is called when the user hits the continue button **/
public void DifficultyMenu(View view) {
String S1 = String.valueOf(AddProb);
Log.d("ProblemSelector.java","AddProb: " + S1);
Intent DifficultyView = new Intent(this, DifficultyMenu.class);
//DifficultyView.putExtra("addProb", PS.AddProb);
//DifficultyView.putExtra("subProb", PS.SubProb);
//DifficultyView.putExtra("multiProb", PS.MultiProb);
//DifficultyView.putExtra("divisProb", PS.DivisProb);
startActivity(DifficultyView);
}
/** this converts the 1st version bools to 2nd version bools and outputs the values to the command line **/
public boolean AddP = AddProb;
public boolean SubP = SubProb;
public boolean MultiP = MultiProb;
public boolean DivisP = DivisProb;
}
here is the second class.
private boolean AddP = PS.AddP;
private boolean SubP = PS.SubP;
private boolean MultiP = PS.MultiP;
private boolean DivisP = PS.DivisP;
private int ANum = PS.ANum;
private int SNum = PS.SNum;
private int MNum = PS.MNum;
private int DNum = PS.DNum;
ExpandableListAdapter listAdapter;
ExpandableListView expListView;
List<String> listDataHeader;
HashMap<String, List<String>> listDataChild;
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_difficulty_menu);
// here you'll retrieve the data sent...you can google how to do that.
// get the list view
expListView = (ExpandableListView) findViewById(R.id.lvExp);
// preparing list data
prepareListData();
listAdapter = new ExpandableListAdapter(this, listDataHeader, listDataChild);
// setting list adapter
expListView.setAdapter(listAdapter);
// List view Group click listener
expListView.setOnGroupClickListener(new OnGroupClickListener() {
#Override
public boolean onGroupClick(ExpandableListView parent, View v,
int groupPosition, long id) {
// Toast.makeText(getApplicationContext(),
// "Group Clicked " + listDataHeader.get(groupPosition),
// Toast.LENGTH_SHORT).show();
return false;
}
});
// List view Group expanded listener
expListView.setOnGroupExpandListener(new OnGroupExpandListener() {
#Override
public void onGroupExpand(int groupPosition) {
Toast.makeText(getApplicationContext(),
listDataHeader.get(groupPosition) + " Expanded",
Toast.LENGTH_SHORT).show();
}
});
// List view Group collapsed listener
expListView.setOnGroupCollapseListener(new OnGroupCollapseListener() {
#Override
public void onGroupCollapse(int groupPosition) {
Toast.makeText(getApplicationContext(),
listDataHeader.get(groupPosition) + " Collapsed",
Toast.LENGTH_SHORT).show();
}
});
// List view on child click listener
expListView.setOnChildClickListener(new OnChildClickListener() {
#Override
public boolean onChildClick(ExpandableListView parent, View v,
int groupPosition, int childPosition, long id) {
Toast.makeText(
getApplicationContext(),
listDataHeader.get(groupPosition)
+ " : "
+ listDataChild.get(listDataHeader.get(groupPosition)).get(childPosition), Toast.LENGTH_SHORT)
.show();
/** converts the selected number in the expandable list to a usable integer variable **/
/** also detects if a Difficulty has been selected for each for of problem to practice **/
/** also gives an error to debug console level if something unexpected has happened **/
if(listDataHeader.get(groupPosition).equals("AdditionDifficulty")) {
String St1 = listDataHeader.get(childPosition);
int AddDiff = Integer.parseInt(St1);
if(PS.AddP) {
AChecked = true;
} else {
Log.e("DifficultyMenu.java","Somehow got to line: 123 : for some reason this seems to have happened");
}
}
else if(listDataHeader.get(groupPosition).equals("SubtractionDifficulty")) {
String St2 = listDataHeader.get(childPosition);
int SubDiff = Integer.parseInt(St2);
if(PS.SubP) {
SChecked = true;
} else {
Log.e("DifficultyMenu.java","Somehow got to line: 132 : for some reason this seems to have happened");
}
}
else if(listDataHeader.get(groupPosition).equals("MultiplicationDifficulty")) {
String St3 = listDataHeader.get(childPosition);
int MultiDIff = Integer.parseInt(St3);
if(PS.MultiP) {
MChecked = true;
} else {
Log.e("DifficultyMenu.java","Somehow got to line: 141 : for some reason this seems to have happened");
}
}
else if(listDataHeader.get(groupPosition).equals("DivisionDifficulty")) {
String St4 = listDataHeader.get(childPosition);
int DivisDiff = Integer.parseInt(St4);
if(PS.DivisP) {
DChecked = true;
} else {
Log.e("DifficultyMenu.java","Somehow got to line: 150 : for some reason this seems to have happened");
}
}
else {
Log.e("DifficultyMenu.java","could not parse a group position when user selected a field");
}
return false;
}
});
}
/*
* Preparing the list data
*/
private void prepareListData() {
listDataHeader = new ArrayList<>();
listDataChild = new HashMap<>();
// Adding child data
if(AddP) { listDataHeader.add("AdditionDifficulty"); }
if(SubP) { listDataHeader.add("SubtractionDifficulty"); }
if(MultiP) { listDataHeader.add("MultiplicationDifficulty"); }
if(DivisP) { listDataHeader.add("DivisionDifficulty"); }
System.out.println(listDataHeader);
/** this removes fields that the user has not selected to practice **/
// if(!PS.AddProb) { listDataHeader.remove("AdditionDifficulty"); }
// if(!PS.SubProb) { listDataHeader.remove("SubtractionDifficulty"); }
// if(!PS.MultiProb) { listDataHeader.remove("MultiplicationDifficulty"); }
// if(!PS.DivisProb) { listDataHeader.remove("DivisionDifficulty"); }
// Adding child data
List<String> AdditionDifficulty = new ArrayList<>();
while (true) {
if (T1 < 11) {
String S1 = Integer.toString(T1);
AdditionDifficulty.add(S1);
T1++;
} else {
break;
}
}
List<String> SubtractionDifficulty = new ArrayList<>();
while (true) {
if (T2 < 11) {
String S2 = Integer.toString(T2);
SubtractionDifficulty.add(S2);
T2++;
} else {
break;
}
}
List<String> MultiplicationDifficulty = new ArrayList<>();
while (true) {
if (T3 < 11) {
String S3 = Integer.toString(T3);
MultiplicationDifficulty.add(S3);
T3++;
} else {
break;
}
}
List<String> DivisionDifficulty = new ArrayList<>();
while (true) {
if (T4 < 11) {
String S4 = Integer.toString(T4);
DivisionDifficulty.add(S4);
T4++;
} else {
break;
}
}
/** this draws out the Expandable lists **/
if(AddP) {
listDataChild.put(listDataHeader.get(ANum), AdditionDifficulty);
} else {
Log.d("DifficultyMenu.java","Something went wrong at line: 230");
}
if(SubP) {
listDataChild.put(listDataHeader.get(SNum), SubtractionDifficulty);
} else {
Log.d("DifficultyMenu.java","Something went wrong at line: 231");
}
if(MultiP) {
listDataChild.put(listDataHeader.get(MNum), MultiplicationDifficulty);
} else {Log.d("DifficultyMenu.java","Something went wrong at line: 232");
}
if(DivisP) {
listDataChild.put(listDataHeader.get(DNum), DivisionDifficulty);
} else {Log.d("DifficultyMenu.java","Something went wrong at line: 233");
}
}
I am working with ASYNTask. And I have used a custom progressbar. It stops working after sometime of spinning, and after that a blank(black colored) screen comes for 2 secs and then my UI for the next screen loads on.
public class LoginActivity extends Activity {
/** Variable define here. */
private EditText metLoginUserName, metLoginPassword;
private Button mbtnLogin;
private ImageView ivRegister;
private String Host, username, password;
private int Port;
private UserChatActivity xmppClient;
public static ArrayList<String> all_user = new ArrayList<String>();
public static CustomProgressDialog mCustomProgressDialog;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.loginlayout);
metLoginUserName = (EditText) this.findViewById(R.id.etLoginUserName);
metLoginPassword = (EditText) this.findViewById(R.id.etLoginPassword);
mbtnLogin = (Button) findViewById(R.id.btnLogin);
ivRegister = (ImageView) findViewById(R.id.ivRegister);
/** Set the hint in username and password edittext */
metLoginUserName = CCMStaticMethod.setHintEditText(metLoginUserName,
getString(R.string.hint_username), true);
metLoginPassword = CCMStaticMethod.setHintEditText(metLoginPassword,
getString(R.string.hint_password), true);
/** Click on login button */
mbtnLogin.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
/** Login Activity */
username = metLoginUserName.getText().toString();
password = metLoginPassword.getText().toString();
CCMStaticVariable.musername = username;
CCMStaticVariable.musername = password;
if(CCMStaticMethod.isInternetAvailable(LoginActivity.this)){
LoginUserTask loginUserTask = new LoginUserTask(v.getContext());
loginUserTask.execute();
}
}
});
/** Click on forgot button */
this.findViewById(R.id.ivForgot).setOnClickListener(
new OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(LoginActivity.this,
ForgotPassActivity.class));
}
});
/** Click on register button */
ivRegister.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(LoginActivity.this,
RegisterActivity.class));
}
});
}
public class LoginUserTask extends AsyncTask<Void, Void, XMPPConnection> {
public LoginUserTask(Context context) {
super();
this.context = context;
}
private Context context;
#Override
protected void onPostExecute(XMPPConnection result) {
if (result != null) {
/**Start services*/
startService(new Intent(LoginActivity.this, UpdaterService.class));
/**Call usermenu activity*/
finish();
startActivity(new Intent(LoginActivity.this,UserMenuActivity.class));
} else {
DialogInterface.OnClickListener LoginUnSuccessOkAlertListener = new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
};
CCMStaticMethod.showAlert(context, "Login",
"Invalid Username or Password. Try Again !", R.drawable.unsuccess,
true, true, "Ok", LoginUnSuccessOkAlertListener, null,
null);
}
mCustomProgressDialog.dismiss();
}
#Override
protected void onPreExecute() {
mCustomProgressDialog = CustomProgressDialog.createDialog(
LoginActivity.this, "", "");
mCustomProgressDialog.show();
}
#Override
protected XMPPConnection doInBackground(Void... params) {
CCMStaticVariable.CommonConnection = XMPPConn.checkXMPPConnection(username,
password);
return CCMStaticVariable.CommonConnection;
}
}
}
UserMenuActivity
public class UserMenuActivity extends ExpandableListActivity {
private XMPPConnection connection;
String name,availability,subscriptionStatus;
TextView tv_Status;
public static final String ACTION_UPDATE = "ACTION_UPDATE";
/** Variable Define here */
private String[] data = { "View my profile", "New Multiperson Chat",
"New Broad Cast Message", "New Contact Category", "New Group",
"Invite to CCM", "Search", "Expand All", "Settings", "Help",
"Close" };
private String[] data_Contact = { "Rename Category","Move Contact to Category", "View my profile",
"New Multiperson Chat", "New Broad Cast Message",
"New Contact Category", "New Group", "Invite to CCM", "Search",
"Expand All", "Settings", "Help", "Close" };
private String[] data_child_contact = { "Open chat", "Delete Contact","View my profile",
"New Multiperson Chat", "New Broad Cast Message",
"New Contact Category", "New Group", "Invite to CCM", "Search",
"Expand All", "Settings", "Help", "Close" };
private String[] menuItem = { "Chats", "Contacts", "CGM Groups", "Pending","Request" };
private List<String> menuItemList = Arrays.asList(menuItem);
private int commonGroupPosition = 0;
private String etAlertVal;
private DatabaseHelper dbHelper;
private int categoryID, listPos;
/** New Code here.. */
private ArrayList<String> groupNames;
private ArrayList<ArrayList<ChildItems>> childs;
private UserMenuAdapter adapter;
private Object object;
private CustomProgressDialog mCustomProgressDialog;
private String[] data2 = { "PIN Michelle", "IP Call" };
private ListView mlist2;
private ImageButton mimBtnMenu;
private LinearLayout mllpopmenu;
private View popupView;
private PopupWindow popupWindow;
private AlertDialog.Builder alert;
private EditText input;
private TextView mtvUserName, mtvUserTagLine;
private ExpandableListView mExpandableListView;
public static List<CategoryDataClass> categoryList;
public static ArrayList<String> chatUser;
private boolean menuType = false;
private String childValContact="";
public static Context context;
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.usermenulayout);
dbHelper = new DatabaseHelper(UserMenuActivity.this);
XMPPConn.getContactList();
connection = CCMStaticVariable.CommonConnection;
registerReceiver(UpdateList, new IntentFilter(ACTION_UPDATE));
}
#Override
public void onBackPressed() {
if (mllpopmenu.getVisibility() == View.VISIBLE) {
mllpopmenu.setVisibility(View.INVISIBLE);
} else {
if (CCMStaticVariable.CommonConnection.isConnected()) {
CCMStaticVariable.CommonConnection.disconnect();
}
super.onBackPressed();
}
}
#SuppressWarnings("unchecked")
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_MENU) {
if (mllpopmenu.getVisibility() == View.VISIBLE) {
mllpopmenu.setVisibility(View.INVISIBLE);
} else {
if (commonGroupPosition >= 4 && menuType == true) {
if(childValContact == ""){
mllpopmenu.setVisibility(View.VISIBLE);
mlist2.setAdapter(new ArrayAdapter(UserMenuActivity.this,
R.layout.listviewtext, R.id.tvMenuText,
data_Contact));
}else{
mllpopmenu.setVisibility(View.VISIBLE);
mlist2.setAdapter(new ArrayAdapter(UserMenuActivity.this,
R.layout.listviewtext, R.id.tvMenuText,
data_child_contact));
}
} else if (commonGroupPosition == 0) {
mllpopmenu.setVisibility(View.VISIBLE);
mlist2.setAdapter(new ArrayAdapter(UserMenuActivity.this,
R.layout.listviewtext, R.id.tvMenuText, data));
}
}
return true;
}
return super.onKeyDown(keyCode, event);
}
#Override
protected void onResume() {
super.onResume();
mCustomProgressDialog = CustomProgressDialog.createDialog(
UserMenuActivity.this, "", "");
mCustomProgressDialog.show();
new Thread(){
public void run() {
XMPPConn.getContactList();
expendableHandle.sendEmptyMessage(0);
};
}.start();
super.onResume();
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
unregisterReceiver(UpdateList);
}
public boolean onChildClick(ExpandableListView parent, View v,
int groupPosition, int childPosition, long id) {
if(groupPosition == 0){
Intent intent = new Intent(UserMenuActivity.this,UserChatActivity.class);
intent.putExtra("userNameVal",chatUser.get(childPosition));
intent.putExtra("message","");
startActivity(intent);
}else if (groupPosition == 1 && childPosition == 0) {
startActivity(new Intent(UserMenuActivity.this,
InvitetoCCMActivity.class));
} else if (groupPosition == 1 && childPosition != 0) {
Intent intent = new Intent(UserMenuActivity.this,
UserChatActivity.class);
intent.putExtra("userNameVal",
XMPPConn.mfriendList.get(childPosition - 1).friendName);
intent.putExtra("message","");
startActivity(intent);
} else if (groupPosition == 2 && childPosition == 0) {
startActivity(new Intent(UserMenuActivity.this,
CreateGroupActivity.class));
} else if (groupPosition == 2 && childPosition != 0) {
String GROUP_NAME = childs.get(groupPosition).get(childPosition)
.getName().toString();
int end = GROUP_NAME.indexOf("(");
CCMStaticVariable.groupName = GROUP_NAME.substring(0, end).trim();
startActivity(new Intent(UserMenuActivity.this,
GroupsActivity.class));
} else if (groupPosition >= 4) {
childValContact = childs.get(groupPosition).get(childPosition).getName().trim();
showToast("user==>"+childValContact, 0);
}
return false;
}
private void setExpandableListView() {
/***###############GROUP ARRAY ############################*/
final ArrayList<String> groupNames = new ArrayList<String>();
chatUser = dbHelper.getChatUser();
groupNames.add("Chats ("+chatUser.size()+")");
groupNames.add("Contacts (" + XMPPConn.mfriendList.size() + ")");
groupNames.add("CGM Groups (" + XMPPConn.mGroupList.size() + ")");
groupNames.add("Pending (1)");
XMPPConn.getGroup();
categoryList = dbHelper.getAllCategory();
/**Group From Sever*/
if (XMPPConn.mGroupList.size() > 0) {
for (int g = 0; g < XMPPConn.mGroupList.size(); g++) {
XMPPConn.getGroupContact(XMPPConn.mGroupList.get(g).groupName);
groupNames.add(XMPPConn.mGroupList.get(g).groupName + "("
+ XMPPConn.mGroupContactList.size()+ ")");
}
}
if(categoryList.size() > 0){
for (int cat = 0; cat < categoryList.size(); cat++) {
groupNames.add(categoryList.get(cat).getCategoryName()+ "(0)");
}
}
this.groupNames = groupNames;
/*** ###########CHILD ARRAY * #################*/
ArrayList<ArrayList<ChildItems>> childs = new ArrayList<ArrayList<ChildItems>>();
ArrayList<ChildItems> child = new ArrayList<ChildItems>();
if(chatUser.size() > 0){
for(int i = 0; i < chatUser.size(); i++){
child.add(new ChildItems(userName(chatUser.get(i)), "",0,null));
}
}else{
child.add(new ChildItems("--No History--", "",0,null));
}
childs.add(child);
child = new ArrayList<ChildItems>();
child.add(new ChildItems("", "",0,null));
if (XMPPConn.mfriendList.size() > 0) {
for (int n = 0; n < XMPPConn.mfriendList.size(); n++) {
child.add(new ChildItems(XMPPConn.mfriendList.get(n).friendNickName,
XMPPConn.mfriendList.get(n).friendStatus,
XMPPConn.mfriendList.get(n).friendState,
XMPPConn.mfriendList.get(n).friendPic));
}
}
childs.add(child);
/************** CGM Group Child here *********************/
child = new ArrayList<ChildItems>();
child.add(new ChildItems("", "",0,null));
if (XMPPConn.mGroupList.size() > 0) {
for (int grop = 0; grop < XMPPConn.mGroupList.size(); grop++) {
child.add(new ChildItems(
XMPPConn.mGroupList.get(grop).groupName + " ("
+ XMPPConn.mGroupList.get(grop).groupUserCount
+ ")", "",0,null));
}
}
childs.add(child);
child = new ArrayList<ChildItems>();
child.add(new ChildItems("Shuchi",
"Pending (Waiting for Authorization)",0,null));
childs.add(child);
/************************ Group Contact List *************************/
if (XMPPConn.mGroupList.size() > 0) {
for (int g = 0; g < XMPPConn.mGroupList.size(); g++) {
/** Contact List */
XMPPConn.getGroupContact(XMPPConn.mGroupList.get(g).groupName);
child = new ArrayList<ChildItems>();
for (int con = 0; con < XMPPConn.mGroupContactList.size(); con++) {
child.add(new ChildItems(
XMPPConn.mGroupContactList.get(con).friendName,
XMPPConn.mGroupContactList.get(con).friendStatus,0,null));
}
childs.add(child);
}
}
if(categoryList.size() > 0){
for (int cat = 0; cat < categoryList.size(); cat++) {
child = new ArrayList<ChildItems>();
child.add(new ChildItems("-none-", "",0,null));
childs.add(child);
}
}
this.childs = childs;
/** Set Adapter here */
adapter = new UserMenuAdapter(this, groupNames, childs);
setListAdapter(adapter);
object = this;
mlist2 = (ListView) findViewById(R.id.list2);
mimBtnMenu = (ImageButton) findViewById(R.id.imBtnMenu);
mllpopmenu = (LinearLayout) findViewById(R.id.llpopmenu);
mtvUserName = (TextView) findViewById(R.id.tvUserName);
mtvUserTagLine = (TextView) findViewById(R.id.tvUserTagLine);
//Set User name..
System.out.println("CCMStaticVariable.loginUserName==="
+ CCMStaticVariable.loginUserName);
if (!CCMStaticVariable.loginUserName.equalsIgnoreCase("")) {
mtvUserName.setText("" + CCMStaticVariable.loginUserName);
}
/** Expandable List set here.. */
mExpandableListView = (ExpandableListView) this
.findViewById(android.R.id.list);
mExpandableListView.setOnGroupClickListener(new OnGroupClickListener() {
#Override
public boolean onGroupClick(ExpandableListView parent, View v,
int groupPosition, long id) {
if (parent.isGroupExpanded(groupPosition)) {
commonGroupPosition = 0;
}else{
commonGroupPosition = groupPosition;
}
String GROUP_NAME = groupNames.get(groupPosition);
int end = groupNames.get(groupPosition).indexOf("(");
String GROUP_NAME_VALUE = GROUP_NAME.substring(0, end).trim();
if (menuItemList.contains(GROUP_NAME_VALUE)) {
menuType = false;
CCMStaticVariable.groupCatName = GROUP_NAME_VALUE;
} else {
menuType = true;
CCMStaticVariable.groupCatName = GROUP_NAME_VALUE;
}
long findCatId = dbHelper.getCategoryID(GROUP_NAME_VALUE);
if (findCatId != 0) {
categoryID = (int) findCatId;
}
childValContact="";
//showToast("Clicked on==" + GROUP_NAME_VALUE, 0);
return false;
}
});
/** Click on item */
mlist2.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int pos,long arg3) {
if (commonGroupPosition >= 4) {
if(childValContact == ""){
if (pos == 0) {
showAlertEdit(CCMStaticVariable.groupCatName);
}
/** Move contact to catgory */
if (pos == 1) {
startActivity(new Intent(UserMenuActivity.this,AddContactCategoryActivity.class));
}
}else{
if(pos == 0){
Intent intent = new Intent(UserMenuActivity.this,UserChatActivity.class);
intent.putExtra("userNameVal",childValContact);
startActivity(intent);
}
if(pos == 1){
XMPPConn.removeEntry(childValContact);
showToast("Contact deleted sucessfully", 0);
Intent intent = new Intent(UserMenuActivity.this,UserMenuActivity.class);
}
}
} else {
/** MyProfile */
if (pos == 0) {
startActivity(new Intent(UserMenuActivity.this,
MyProfileActivity.class));
}
/** New multiperson chat start */
if (pos == 1) {
startActivity(new Intent(UserMenuActivity.this,
NewMultipersonChatActivity.class));
}
/** New Broadcast message */
if (pos == 2) {
startActivity(new Intent(UserMenuActivity.this,
NewBroadcastMessageActivity.class));
}
/** Click on add category */
if (pos == 3) {
showAlertAdd();
}
if (pos == 4) {
startActivity(new Intent(UserMenuActivity.this,
CreateGroupActivity.class));
}
if (pos == 5) {
startActivity(new Intent(UserMenuActivity.this,
InvitetoCCMActivity.class));
}
if (pos == 6) {
startActivity(new Intent(UserMenuActivity.this,
SearchActivity.class));
}
if (pos == 7) {
onGroupExpand(2);
for (int i = 0; i < groupNames.size(); i++) {
mExpandableListView.expandGroup(i);
}
}
/** Click on settings */
if (pos == 8) {
startActivity(new Intent(UserMenuActivity.this,
SettingsActivity.class));
}
if (pos == 10) {
System.exit(0);
}
if (pos == 14) {
if (mllpopmenu.getVisibility() == View.VISIBLE) {
mllpopmenu.setVisibility(View.INVISIBLE);
if (popupWindow.isShowing()) {
popupWindow.dismiss();
}
} else {
mllpopmenu.setVisibility(View.VISIBLE);
mlist2.setAdapter(new ArrayAdapter(
UserMenuActivity.this,
R.layout.listviewtext, R.id.tvMenuText,
data));
}
}
}
}
});
}
/** Toast message display here.. */
private void showToast(String msg, int time) {
Toast.makeText(this, msg, time).show();
}
/** Show EditAlert Box */
private void showAlertEdit(String msg) {
alert = new AlertDialog.Builder(UserMenuActivity.this);
input = new EditText(UserMenuActivity.this);
input.setSingleLine();
input.setText(msg);
alert.setTitle("Edit Category Name");
alert.setView(input);
alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.cancel();
etAlertVal = input.getText().toString();
/** isGroupFromServerOrMobile */
RosterGroup isGroupExists = CCMStaticVariable.CommonConnection
.getRoster().getGroup(CCMStaticVariable.groupCatName);
if (isGroupExists == null) {
dbHelper.updateCategory(categoryID, etAlertVal);
Intent intent = new Intent(UserMenuActivity.this,
UserMenuActivity.class);
startActivity(intent);
showToast("Category updated sucessfully", 0);
} else {
CCMStaticVariable.CommonConnection.getRoster()
.getGroup(CCMStaticVariable.groupCatName)
.setName(etAlertVal);
Intent intent = new Intent(UserMenuActivity.this,
UserMenuActivity.class);
startActivity(intent);
showToast("Category updated sucessfully", 0);
}
}
});
alert.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.cancel();
}
});
alert.show();
}
/** ShowAlertBox Edit */
private void showAlertAdd() {
alert = new AlertDialog.Builder(UserMenuActivity.this);
input = new EditText(UserMenuActivity.this);
input.setSingleLine();
alert.setTitle("New Category Name");
alert.setView(input);
alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.cancel();
etAlertVal = input.getText().toString();
if (!etAlertVal.equalsIgnoreCase("request")) {
long lastInsertedId = dbHelper.insertCategory(etAlertVal);
CCMStaticVariable.groupCatName = etAlertVal;
Intent intent = new Intent(UserMenuActivity.this,AddContactCategoryActivity.class);
startActivity(intent);
}
}
});
alert.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
dialog.cancel();
}
});
alert.show();
}
public String showSubscriptionStatus(String friend){
return friend;
}
public String userName(String jid){
String username = "";
if(jid.contains("#")){
int index = jid.indexOf("#");
username = jid.substring(0, index);
}else{
username = jid;
}
return username;
}
/**Set expandable handler here..*/
Handler expendableHandle = new Handler(){
public void handleMessage(android.os.Message msg) {
mCustomProgressDialog.dismiss();
setExpandableListView();
};
};
BroadcastReceiver UpdateList = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
Toast.makeText(UserMenuActivity.this, "CALLED", Toast.LENGTH_SHORT).show();
adapter.notifyDataSetChanged();
}
};
}
Please suggest me what is the problem here. I have seen so many posts and have tried a lot of things regarding the same. But It has not worked for me. Please tell me.
Thanks
This
startActivity(new Intent(LoginActivity.this,UserMenuActivity.class));
This
CCMStaticMethod.showAlert(context, "Login",
"Invalid Username or Password. Try Again !", R.drawable.unsuccess,
true, true, "Ok", LoginUnSuccessOkAlertListener, null,
null);
}
and this
mCustomProgressDialog.dismiss();
Do not perform UI events from an async task. Use activity.runOnUiThread() instead.