randomly output quiz questions from xml file using array - android

This is my code for questions, my problem is that i cannot create a code to randomly output a question from xml without any duplication,
Here's my code:
public class QuizFunActivity extends Activity{
Intent menu = null;
BufferedReader bReader = null;
static JSONArray quesList = null;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main2);
Thread thread = new Thread() {
public void run() {
try {
Thread.sleep(3*1000);
finish();
loadQuestions();
Intent intent = new Intent(QuizFunActivity.this, QuestionActivity.class);
QuizFunActivity.this.startActivity(intent);
} catch (Exception e) {
}
}
};
thread.start();
}
private void loadQuestions() throws Exception {
try {
InputStream questions = this.getBaseContext().getResources()
.openRawResource(R.raw.questions);
bReader = new BufferedReader(new InputStreamReader(questions));
StringBuilder quesString = new StringBuilder();
String aJsonLine = null;
while ((aJsonLine = bReader.readLine()) != null) {
quesString.append(aJsonLine);
}
Log.d(this.getClass().toString(), quesString.toString());
JSONObject quesObj = new JSONObject(quesString.toString());
quesList = quesObj.getJSONArray("Questions");
Log.d(this.getClass().getName(),
"Num Questions " + quesList.length());
} catch (Exception e){
} finally {
try {
bReader.close();
} catch (Exception e) {
Log.e("", e.getMessage().toString(), e.getCause());
}
}
}
public static JSONArray getQuesList() {
return quesList;
}
}
can you give me a sample of which part on my code should i create a code for random output?
thanks for the help!
you may take a look with this activity,
public class QuestionActivity extends Activity {
/** Called when the activity is first created. */
EditText question = null;
RadioButton answer1 = null;
RadioButton answer2 = null;
RadioButton answer3 = null;
RadioButton answer4 = null;
RadioGroup answers = null;
Button finish = null;
int selectedAnswer = -1;
int quesIndex = 0;
int numEvents = 0;
int selected[] = null;
int correctAns[] = null;
boolean review =false;
Button prev, next = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.question);
TableLayout quizLayout = (TableLayout) findViewById(R.id.quizLayout);
quizLayout.setVisibility(android.view.View.INVISIBLE);
try {
question = (EditText) findViewById(R.id.question1);
answer1 = (RadioButton) findViewById(R.id.a0);
answer2 = (RadioButton) findViewById(R.id.a1);
answer3 = (RadioButton) findViewById(R.id.a2);
answer4 = (RadioButton) findViewById(R.id.a3);
answers = (RadioGroup) findViewById(R.id.answers);
RadioGroup questionLayout = (RadioGroup)findViewById(R.id.answers);
Button finish = (Button)findViewById(R.id.finish);
finish.setOnClickListener(finishListener);
prev = (Button)findViewById(R.id.Prev);
prev.setOnClickListener(prevListener);
next = (Button)findViewById(R.id.Next);
next.setOnClickListener(nextListener);
selected = new int[QuizFunActivity.getQuesList().length()];
java.util.Arrays.fill(selected, -1);
correctAns = new int[QuizFunActivity.getQuesList().length()];
java.util.Arrays.fill(correctAns, -1);
this.showQuestion(0,review);
quizLayout.setVisibility(android.view.View.VISIBLE);
} catch (Exception e) {
Log.e("", e.getMessage().toString(), e.getCause());
}
}
private void showQuestion(int qIndex,boolean review) {
try {
JSONObject aQues = QuizFunActivity.getQuesList().getJSONObject(qIndex);
String quesValue = aQues.getString("Question");
if (correctAns[qIndex] == -1) {
String correctAnsStr = aQues.getString("CorrectAnswer");
correctAns[qIndex] = Integer.parseInt(correctAnsStr);
}
question.setText(quesValue.toCharArray(), 0, quesValue.length());
answers.check(-1);
answer1.setTextColor(Color.WHITE);
answer2.setTextColor(Color.WHITE);
answer3.setTextColor(Color.WHITE);
answer4.setTextColor(Color.WHITE);
JSONArray ansList = aQues.getJSONArray("Answers");
String aAns = ansList.getJSONObject(0).getString("Answer");
answer1.setText(aAns.toCharArray(), 0, aAns.length());
aAns = ansList.getJSONObject(1).getString("Answer");
answer2.setText(aAns.toCharArray(), 0, aAns.length());
aAns = ansList.getJSONObject(2).getString("Answer");
answer3.setText(aAns.toCharArray(), 0, aAns.length());
aAns = ansList.getJSONObject(3).getString("Answer");
answer4.setText(aAns.toCharArray(), 0, aAns.length());
Log.d("",selected[qIndex]+"");
if (selected[qIndex] == 0)
answers.check(R.id.a0);
if (selected[qIndex] == 1)
answers.check(R.id.a1);
if (selected[qIndex] == 2)
answers.check(R.id.a2);
if (selected[qIndex] == 3)
answers.check(R.id.a3);
setScoreTitle();
if (quesIndex == (QuizFunActivity.getQuesList().length()-1))
next.setEnabled(false);
if (quesIndex == 0)
prev.setEnabled(false);
if (quesIndex > 0)
prev.setEnabled(true);
if (quesIndex < (QuizFunActivity.getQuesList().length()-1))
next.setEnabled(true);
if (review) {
Log.d("review",selected[qIndex]+""+correctAns[qIndex]);;
if (selected[qIndex] != correctAns[qIndex]) {
if (selected[qIndex] == 0)
answer1.setTextColor(Color.RED);
if (selected[qIndex] == 1)
answer2.setTextColor(Color.RED);
if (selected[qIndex] == 2)
answer3.setTextColor(Color.RED);
if (selected[qIndex] == 3)
answer4.setTextColor(Color.RED);
}
if (correctAns[qIndex] == 0)
answer1.setTextColor(Color.GREEN);
if (correctAns[qIndex] == 1)
answer2.setTextColor(Color.GREEN);
if (correctAns[qIndex] == 2)
answer3.setTextColor(Color.GREEN);
if (correctAns[qIndex] == 3)
answer4.setTextColor(Color.GREEN);
}
} catch (Exception e) {
Log.e(this.getClass().toString(), e.getMessage(), e.getCause());
}
}
private OnClickListener finishListener = new OnClickListener() {
public void onClick(View v) {
setAnswer();
//Calculate Score
int score = 0;
for(int i=0; i<correctAns.length; i++){
if ((correctAns[i] != -1) && (correctAns[i] == selected[i]))
score++;
}
AlertDialog alertDialog;
alertDialog = new AlertDialog.Builder(QuestionActivity.this).create();
alertDialog.setTitle("Score");
alertDialog.setMessage((score) +" out of " + (QuizFunActivity.getQuesList().length()));
alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "Retake", new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog, int which) {
review = false;
quesIndex=0;
QuestionActivity.this.showQuestion(0, review);
}
});
/* alertDialog.setButton(AlertDialog.BUTTON_POSITIVE, "Review", new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog, int which) {
review = true;
quesIndex=0;
QuestionActivity.this.showQuestion(0, review);
}
}); */
alertDialog.setButton(AlertDialog.BUTTON_NEGATIVE,"Quit", new DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog, int which) {
review = false;
Intent instructionsIntent = new Intent(QuestionActivity.this,MainBookActivity.class);
startActivity(instructionsIntent);
finish();
}
});
alertDialog.show();
}
};
private void setAnswer() {
if (answer1.isChecked())
selected[quesIndex] = 0;
if (answer2.isChecked())
selected[quesIndex] = 1;
if (answer3.isChecked())
selected[quesIndex] = 2;
if (answer4.isChecked())
selected[quesIndex] = 3;
Log.d("",Arrays.toString(selected));
Log.d("",Arrays.toString(correctAns));
}
private OnClickListener nextListener = new OnClickListener() {
public void onClick(View v) {
setAnswer();
quesIndex++;
if (quesIndex >= QuizFunActivity.getQuesList().length())
quesIndex = QuizFunActivity.getQuesList().length() - 1;
showQuestion(quesIndex,review);
}
};
private OnClickListener prevListener = new OnClickListener() {
public void onClick(View v) {
setAnswer();
quesIndex--;
if (quesIndex < 0)
quesIndex = 0;
showQuestion(quesIndex,review);
}
};
private void setScoreTitle() {
this.setTitle("SciQuiz3 " + (quesIndex+1)+ "/" + QuizFunActivity.getQuesList().length());
}
#Override
public void onBackPressed() {
moveTaskToBack(true);
}
}
Thanks!

Related

listview change to default when keyboard opens

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?

FAILED BINDER TRANSACTION,but there is nothing in intent

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();
}
}

Android contact picker returning nulll (resultCode == 0)

I'm new to Android and I'm trying to attach a contact picker to a form. This "contact picker code" works well when I test it with other forms but with this form, the resultCode = RESULT_CANCELED. I have checked other examples, but it doesn't work with this from but still works with other forms.
public class EmergencyButtonActivity extends Activity {
static private MoreEditText mPhonesMoreEditText = null;
private static final String DEBUG_TAG = "EmergencyButtonActivity";
private static final int CONTACT_PICKER_RESULT = 1001;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ExceptionHandler.register(this, new StackMailer());
setContentView(R.layout.main);
}
public void doLaunchContactPicker(View view) {
Intent contactPickerIntent = new Intent(Intent.ACTION_PICK,
Contacts.CONTENT_URI);
startActivityForResult(contactPickerIntent, CONTACT_PICKER_RESULT);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
switch (requestCode) {
case CONTACT_PICKER_RESULT:
Cursor cursor = null;
String phone = "";
try {
Uri result = data.getData();
Log.v(DEBUG_TAG, "Got a contact result: "
+ result.toString());
// get the contact id from the Uri
String id = result.getLastPathSegment();
// query for everything email
cursor = getContentResolver().query(Phone.CONTENT_URI,
null, Phone.CONTACT_ID + "=?", new String[] { id },
null);
int emailIdx = cursor.getColumnIndex(Phone.DATA);
// let's just get the first phone
if (cursor.moveToFirst()) {
phone = cursor.getString(emailIdx);
Log.v(DEBUG_TAG, "Got email: " + phone);
} else {
Log.w(DEBUG_TAG, "No results");
}
} catch (Exception e) {
Log.e(DEBUG_TAG, "Failed to get email data", e);
} finally {
if (cursor != null) {
cursor.close();
}
EditText txtPhoneNo = (EditText) findViewById(R.id.txtPhoneNo);
txtPhoneNo.setText(phone);
if (phone.length() == 0) {
Toast.makeText(this, "No number found for contact.",
Toast.LENGTH_LONG).show();
}
else{
Toast.makeText(getBaseContext(), "Phone : "+ phone, Toast.LENGTH_LONG).show();
}
}
break;
}
} else {
Log.w(DEBUG_TAG, "Warning: activity result not ok");
}
}
private void popup(String title, String text) {
AlertDialog.Builder builder = new AlertDialog.Builder(EmergencyButtonActivity.this);
builder.setMessage(text)
.setTitle(title)
.setCancelable(true)
.setPositiveButton("ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
private void initUI() {
setContentView(R.layout.main);
this.restoreTextEdits();
ImageButton btnEmergency = (ImageButton) findViewById(R.id.btnEmergency);
btnEmergency.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// try sending the message:
EmergencyButtonActivity.this.redButtonPressed();
}
});
ImageButton btnHelp = (ImageButton) findViewById(R.id.btnHelp);
btnHelp.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
popupHelp();
}
});
}
public void popupHelp() {
final String messages [] = {
"Welcome To App xxxxxx",
"XXXXXXXXXXXXXXXXXXXXXXX",
"XXXXXXXXXXXXXXXXXXXXXXXX."
};
// inverted order - They all popup and you hit "ok" to see the next one.
popup("3/3", messages[2]);
popup("2/3", messages[1]);
popup("1/3", messages[0]);
}
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
initUI();
}
private class StackMailer implements ExceptionHandler.StackTraceHandler {
public void onStackTrace(String stackTrace) {
EmailSender.send("a#zzz.com", "Error", "ButtonError\n" + stackTrace);
}
}
#Override
protected void onStart()
{
super.onStart();
}
#Override
protected void onResume()
{
super.onResume();
initUI();
//IntroActivity.openOnceAfterInstallation(this);
helpOnceAfterInstallation();
}
#Override
protected void onPause() {
super.onPause();
this.saveTextEdits();
}
#Override
protected void onStop() {
super.onStop();
}
public void helpOnceAfterInstallation() {
// runs only on the first time opening
final String wasOpenedName = "wasOpened";
final String introDbName = "introActivityState";
SharedPreferences settings = this.getSharedPreferences(introDbName, Context.MODE_PRIVATE);
boolean wasOpened = settings.getBoolean(wasOpenedName, false);
if (wasOpened) {
return;
}
// mark that it was opened once
SharedPreferences.Editor editor = settings.edit();
editor.putBoolean(wasOpenedName, true);
editor.commit();
popupHelp();
}
private class EditTextRow {
LinearLayout mLinlay;
EditText mEditText;
ImageButton mRemoveBtn;
public EditTextRow(String text, EditText example) {
mEditText = new EditText(EmergencyButtonActivity.this);
mEditText.setLayoutParams(example.getLayoutParams());
mEditText.setText(text);
mEditText.setInputType(example.getInputType());
mRemoveBtn = new ImageButton(EmergencyButtonActivity.this);
mRemoveBtn.setBackgroundResource(R.drawable.grey_x);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
params.gravity = Gravity.CENTER;
mRemoveBtn.setLayoutParams(params);
mLinlay = new LinearLayout(EmergencyButtonActivity.this);
mLinlay.setOrientation(LinearLayout.HORIZONTAL);
mLinlay.addView(mEditText);
mLinlay.addView(mRemoveBtn);
}
}
private class MoreEditText {
private LinearLayout mContainer;
private ArrayList<EditText> mEditTextList = null;
public MoreEditText(LinearLayout container, EditText textWidget, List<String> stringsList) {
// Create the rows from scratch, this should only happen onCreate
mContainer = container;
mEditTextList = new ArrayList<EditText>();
EditText edit;
edit = textWidget;
if(! stringsList.isEmpty()) {
edit.setText(stringsList.get(0));
}
mEditTextList.add(edit);
for (int i = 1; i < stringsList.size(); i++) {
addRow(stringsList.get(i));
}
}
public void restore(LinearLayout container, EditText textWidget, List<String> stringsList) {
// Create the rows from older existing rows, this can happen on
// changes of orientation, onResume, etc
mContainer = container;
for(int i = 0; i < mEditTextList.size(); i++) {
EditText edit;
if (i == 0) {
edit = textWidget;
mEditTextList.set(0, edit);
if (stringsList.size() > 0) {
edit.setText(stringsList.get(0));
}
} else {
edit = mEditTextList.get(i);
View viewRow = (LinearLayout) edit.getParent();
((LinearLayout)viewRow.getParent()).removeView(viewRow);
mContainer.addView(viewRow);
}
}
}
#SuppressWarnings("unused")
public EditText getDefaultTextEdit(LinearLayout container) {
// TODO: turn this into something like "getEditTextChild" rather than counting on the index "0"
return (EditText) ((LinearLayout)container.getChildAt(0)).getChildAt(0);
}
public void removeRow(EditText editText) {
mContainer.removeView((View) editText.getParent());
mEditTextList.remove(editText);
}
public void addRow(String text) {
final EditTextRow editRow = new EditTextRow(text, mEditTextList.get(0));
editRow.mRemoveBtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
MoreEditText.this.removeRow(editRow.mEditText);
}
});
mContainer.addView(editRow.mLinlay);
mEditTextList.add(editRow.mEditText);
}
public List<String> GetTexts() {
ArrayList<String> texts = new ArrayList<String>();
for (int i = 0; i < mEditTextList.size(); i ++) {
texts.add(mEditTextList.get(i).getText().toString());
}
return texts;
}
}
private void addPhonesEmailsUI(List<String> phones, List<String> emails) {
LinearLayout phoneNoLin = (LinearLayout)findViewById(R.id.linPhoneNo);
EditText txtPhoneNo = (EditText)findViewById(R.id.txtPhoneNo);
// NOTE: we don't always create from scratch so that empty textboxes
// aren't erased on changes of orientation.
if (mPhonesMoreEditText == null) {
mPhonesMoreEditText = new MoreEditText(phoneNoLin, txtPhoneNo, phones);
} else {
mPhonesMoreEditText.restore(phoneNoLin, txtPhoneNo, phones);
}
}
public void restoreTextEdits() {
EmergencyData emergencyData = new EmergencyData(this);
addPhonesEmailsUI(emergencyData.getPhones(), emergencyData.getEmails());
EditText txtMessage = (EditText) findViewById(R.id.txtMessage);
txtMessage.setText(emergencyData.getMessage());
}
#SuppressWarnings("unused")
public void saveTextEdits() {
EditText txtPhoneNo = (EditText) findViewById(R.id.txtPhoneNo);
EditText txtMessage = (EditText) findViewById(R.id.txtMessage);
EmergencyData emergencyData = new EmergencyData(this);
emergencyData.setPhones(mPhonesMoreEditText.GetTexts());
emergencyData.setMessage(txtMessage.getText().toString());
}
public void redButtonPressed() {
this.saveTextEdits();
EmergencyData emergency = new EmergencyData(this);
if ((emergency.getPhones().size() == 0) && (emergency.getEmails().size() == 0)) {
Toast.makeText(this, "Enter a phone number or email.",
Toast.LENGTH_SHORT).show();
return;
}
EmergencyActivity.armEmergencyActivity(this);
Intent myIntent = new Intent(EmergencyButtonActivity.this, EmergencyActivity.class);
EmergencyButtonActivity.this.startActivity(myIntent);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.ebutton_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
Intent i = new Intent(Intent.ACTION_VIEW);
switch (item.getItemId()) {
case R.id.project_page:
i.setData(Uri.parse("http://#/"));
startActivity(i);
break;
case R.id.credits:
Dialog dialog = new Dialog(this);
dialog.setContentView(R.layout.credits_dialog);
dialog.setTitle("Credits");
TextView text = (TextView) dialog.findViewById(R.id.textView);
try {
Resources res = getResources();
InputStream in_s = res.openRawResource(R.raw.credits);
byte[] b = new byte[in_s.available()];
in_s.read(b);
text.setText(new String(b));
} catch (Exception e) {
// e.printStackTrace();
text.setText("Error: can't show credits.");
}
dialog.show();
break;
}
return true;
}
}
Finally found a solution, the problem was with the android:launchMode in the manifest.

Window type error

I'm creating a audio swipe card reader but I'm getting an error with windows. I can't trace what causing the error in my codes. Can anyone hel me to point what causing the error in my codes? any thought will be highly appreciated.
Here is my codes:
public class SReaderActivity extends Activity {
public final String TAG = "SReaderActivity";
Button swipe, get;// detect, stop
TextView result_text, mTitle;
private TimeCount time = null;
private AudioManager am = null;
int maxVol;
private ProgressDialog progressDialog;
private boolean mHeadsetPlugged = false;
private BroadcastReceiver mHeadsetReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action.equals(Intent.ACTION_HEADSET_PLUG)) {
boolean hasHeadset = (intent.getIntExtra("state", 0) == 1);
boolean hasMicroPhone = (intent.getIntExtra("microphone", 0) == 1);
if (hasHeadset && hasMicroPhone) {
mHeadsetPlugged = true;
} else {
mHeadsetPlugged = false;
if (sreader != null)
sreader.Stop();
handler.post(disable_button);
}
handler.post(mHeadsetPluginHandler);
}
}
};
private Handler handler = new Handler();
SReaderApi sreader = null;
private String version = null;
private String ksn = null;
private String random = null;
private String workingkey = null;
private String encryption_data = null;
private String decryption_data = null;
private String T1PAN_data = null;
private String T1Name_Exd = null;
private String T2PAN_data = null;
private String T2Exd_data = null;
private Runnable mHeadsetPluginHandler = new Runnable() {
public void run() {
String plug_str = mHeadsetPlugged ? "plugin" : "unplugin";
Toast.makeText(SReaderActivity.this, "Headset " + plug_str, Toast.LENGTH_SHORT).show();
if (sreader != null && mHeadsetPlugged == false) { // Device unplug APP close
CloseSinWave();
finish();
} else {
onDetect();
}
}
};
private Runnable disable_button = new Runnable() {
public void run() {
swipe.setEnabled(false);
get.setEnabled(false);
}
};
private Runnable enable_button = new Runnable() {
public void run() {
get.setText(R.string.get);
swipe.setClickable(true);
swipe.setEnabled(true);
swipe.setText(R.string.swipe);
}
};
private Runnable enable_get = new Runnable() {
public void run() {
get.setEnabled(true);
get.setClickable(true);
}
};
private Runnable timeout_ack = new Runnable() {
public void run() {
Toast.makeText(SReaderActivity.this, "Timeout!!!", Toast.LENGTH_SHORT).show();
}
};
private Runnable unknown_err = new Runnable() {
public void run() {
result_text.setText(R.string.unknown_error);
}
};
private Runnable detcet = new Runnable() {
public void run() {
String txt = "Detect OK\n";
result_text.setText(txt);
}
};
private Runnable display_encryptiondata = new Runnable() {
public void run() {
String txt = "Encryption data\n";
txt += encryption_data + "\n\n\n";
result_text.setText(txt);
}
};
private Runnable display_decryptiondata = new Runnable() {
public void run() {
String txt = "Encryption data\n";
txt += encryption_data + "\n\n\nDecryption data\n";
txt += decryption_data + "\n";
result_text.setText(txt);
}
};
private Runnable display_get_data = new Runnable() {
public void run() {
String txt = "Decryption data\n";
txt += decryption_data + "\n\n\n\n";
txt += "T1PAN:" + T1PAN_data + "\n";
txt += "T1Name_Exd:" + T1Name_Exd + "\n";
txt += "T2PAN:" + T2PAN_data + "\n";
txt += "T2Exd:" + T2Exd_data + "\n";
result_text.setText(txt);
}
};
private Runnable clear_all = new Runnable() {
public void run() {
encryption_data = "";
decryption_data = "";
T1PAN_data = "";
T1Name_Exd = "";
T2PAN_data = "";
T2Exd_data = "";
result_text.setText("");
}
};
private Runnable clear_encryption = new Runnable() {
public void run() {
encryption_data = "";
decryption_data = "";
T1PAN_data = "";
T1Name_Exd = "";
T2PAN_data = "";
T2Exd_data = "";
result_text.setText("");
}
};
private Runnable clear_carddata = new Runnable() {
public void run() {
encryption_data = "";
T1PAN_data = "";
T1Name_Exd = "";
T2PAN_data = "";
T2Exd_data = "";
result_text.setText("");
}
};
private Runnable settext_swpie = new Runnable() {
public void run() {
swipe.setClickable(true);
swipe.setText(R.string.swipe);
}
};
private Runnable begin_get = new Runnable() {
public void run() {
myToast = new MyToast(SReaderActivity.this, "get T1&T2 Data...");
myToast.show();
}
};
private Runnable settext_get = new Runnable() {
public void run() {
get.setClickable(true);
get.setText(R.string.get);
}
};
public class MyToast {
private Context mContext = null;
private Toast mToast = null;
private Handler mHandler = null;
private Runnable mToastThread = new Runnable() {
public void run() {
mToast.show();
mHandler.postDelayed(mToastThread, 3000);
}
};
public MyToast(Context context, String txt) {
mContext = context;
mHandler = new Handler(mContext.getMainLooper());
mToast = Toast.makeText(mContext, txt, Toast.LENGTH_LONG);
}
public void setText(String text) {
mToast.setText(text);
}
public void show() {
mHandler.post(mToastThread);
}
public void cancel() {
mHandler.removeCallbacks(mToastThread);
mToast.cancel();
}
}
private MyToast myToast = null;
class TimeCount extends CountDownTimer {
int id;
public TimeCount(int id, long millisInFuture, long countDownInterval) {
super(millisInFuture, countDownInterval);// ²ÎÊýÒÀ´ÎΪ×Üʱ³¤,ºÍ¼ÆʱµÄʱ¼ä¼ä¸ô
this.id = id;
}
#Override
public void onFinish() {// ¼ÆʱÍê±Ïʱ´¥·¢
if (id == R.id.swipe) {
swipe.setText(R.string.reswipe);
swipe.setClickable(true);
}
else if (id == R.id.get) {
get.setText(R.string.get);
get.setClickable(true);
}
}
#Override
public void onTick(long millisUntilFinished) {// ¼Æʱ¹ý³ÌÏÔʾ
CharSequence str = getString(R.string.second);
if (id == R.id.swipe) {
swipe.setClickable(false);
}
else if (id == R.id.get) {
get.setClickable(false);
}
}
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
setContentView(R.layout.swipe);
getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.title);
mTitle = (TextView) findViewById(R.id.title_left_text);
mTitle.setText(R.string.version_name);
am = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
IntentFilter iFilter = new IntentFilter();
iFilter.addAction(Intent.ACTION_HEADSET_PLUG);
iFilter.addCategory(Intent.CATEGORY_DEFAULT);
registerReceiver(mHeadsetReceiver, iFilter);
swipe = (Button) this.findViewById(R.id.swipe);
swipe.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
onSwipe();
}
});
get = (Button) this.findViewById(R.id.get);
get.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
onGet();
}
});
result_text = (TextView) this.findViewById(R.id.result);
swipe.setEnabled(false);
get.setEnabled(false);
setVolumeControlStream(AudioManager.STREAM_MUSIC);
maxVol = am.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
am.setStreamVolume(AudioManager.STREAM_MUSIC, maxVol, 0);
}
public void onDestroy() {
unregisterReceiver(mHeadsetReceiver);
super.onDestroy();
}
public boolean onKeyDown(int keyCode, KeyEvent event) {
switch (keyCode) {
case KeyEvent.KEYCODE_MENU: {
openOptionsDialog();
return true;
}
case KeyEvent.KEYCODE_BACK: { // Log.WritetoFile();
if (sreader != null) {
sreader.Stop();
sreader = null;
if (myToast != null)
myToast.cancel();
finish();
System.exit(0);
return true;
}
}
}
return super.onKeyDown(keyCode, event);
}
public void onUserLeaveHint() { // this only executes when Home is selected.
// do stuff
super.onUserLeaveHint();
if (sreader != null) {
sreader.Stop();
sreader = null;
if (myToast != null)
myToast.cancel();
finish();
System.exit(0);
}
}
public void onAttachedToWindow() {
super.onAttachedToWindow();
this.getWindow().setType(WindowManager.LayoutParams.TYPE_KEYGUARD);
}
private void openOptionsDialog() {
AlertDialog.Builder dialog = new AlertDialog.Builder(SReaderActivity.this);
dialog.setTitle("SS505 sReader");
dialog.setMessage("Magnetic Card Reader APP");
dialog.setNegativeButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
dialog.show();
}
private void onSwipe() {
if (sreader == null)
return;
progressDialog = ProgressDialog.show(this, "Loadding Key", "Please wait swipe card ...", true, false);
time = new TimeCount(R.id.swipe, 15000, 1000);
time.start();// ¿ªÊ¼¼Æʱ
swipe.setEnabled(false);
get.setEnabled(false);
new Thread() {
public void run() {
String data = null;
decryption_data = null;
encryption_data = null;
handler.post(clear_encryption);
try {
random = sreader.GetRandom(10000);
if (random == null) {
progressDialog.dismiss();
String err = sreader.GetErrorString();
if (err.equalsIgnoreCase("cancel all"))
return;
}
workingkey = sreader.GenerateWorkingKey(random, ksn);
progressDialog.dismiss();
data = sreader.ReadCard(15000);
} catch (Exception ex) {
progressDialog.dismiss();
if (ex instanceof TimeoutException) {
time.cancel();
sreader.Cancel();
handler.post(enable_button);
handler.post(timeout_ack);
return;
} else
handler.post(unknown_err);
CloseSinWave();
}
time.cancel();
if (data == null) {
encryption_data = sreader.GetErrorString();
if (encryption_data.equalsIgnoreCase("cancel all"))
return;
handler.post(display_encryptiondata);
} else {
encryption_data = "\n" + data;
handler.post(display_encryptiondata);
String d_str = sreader.TriDesDecryption(workingkey, data);
if (d_str != null) {
if (false == d_str.startsWith("A1")) {
return;
}
int index2 = FindSplitCharIndex(d_str, "A2", 2);
int index3 = FindSplitCharIndex(d_str, "A3", index2 + 2);
if (index2 < 0 || index3 < 0) {
return;
}
String t1 = d_str.substring(2, index2);
String t2 = d_str.substring(index2 + 2, index3);
String t3 = d_str.substring(index3 + 2);
String ex_msg = "";
if (t1.equals(""))
decryption_data = "\nT1=" + "T1 Empty";
else
decryption_data = "\nT1=" + changeHexString2CharString(t1);
if (t2.equals(""))
decryption_data += "\nT2=" + "T2 Empty";
else {
String e2 = changeHexString2CharString(t2);
if (e2.length() < 24 || e2.length() > 40)
ex_msg = "\nTrack2 " + getResources().getText(R.string.de_len) + e2.length() + "byte";
decryption_data += "\nT2=" + e2;
}
if (t3.equals(""))
decryption_data += "\nT3=" + "T3 Empty";
else
decryption_data += "\nT3=" + changeHexString2CharString(t3) + ex_msg;
handler.post(display_decryptiondata);
}
}
handler.post(enable_button);
handler.post(settext_swpie);
handler.post(enable_get);
}
}.start();
}
private int FindSplitCharIndex(String str, String split, int start) {
int i = start;
while (i < str.length() && i + 1 < str.length()) {
String e = str.substring(i, i + 2);
if (e.equals(split)) {
return i;
}
i += 2;
}
return -1;
}
private String changeHexString2CharString(String e) {
String char_txt = "";
for (int i = 0; i < e.length(); i = i + 2) {
String c = e.substring(i, i + 2);
char j = (char) Integer.parseInt(c, 16);
char_txt += j;
}
return char_txt;
}
private boolean Detect_sReader() {
mHeadsetPlugged = HeadSetUtils.checkHeadset();
if (!mHeadsetPlugged) {
result_text.setText(R.string.nodevice);
}
return mHeadsetPlugged;
}
private boolean GenerateSinWave() {
sreader = SReaderApi.getSreaderInstance();
if (sreader.Init() == true) {
sreader.Start();
am.setMode(AudioManager.MODE_NORMAL);
return true;
}
return false;
}
private void CloseSinWave() {
if (sreader != null)
sreader.Stop();
}
private void Initialization() {
swipe.setEnabled(false);
progressDialog = ProgressDialog.show(this, "", "Card Reader Detecting...", true, false);
new Thread() {
public void run() {
int i = 0;
try {
int j = 1;
boolean s_init = false;
while (j < 5) {
try {
s_init = sreader.Initial(2500);
if (s_init)
break;
} catch (Exception ex) {
if (ex instanceof TimeoutException) {
if (j == 4) {
handler.post(timeout_ack);
} else
sleep(1000);
} else {
handler.post(unknown_err);
break;
}
}
j++;
}
if (!s_init) {
CloseSinWave();
progressDialog.dismiss();
return;
}
i++;
ksn = sreader.GetKSN(5000);
if (ksn == null) {
String err = sreader.GetErrorString();
if (err.equalsIgnoreCase("cancel all"))
return;
throw new Exception("ksn is null");
}
handler.post(enable_button);
handler.post(detcet);
progressDialog.dismiss();
} catch (Exception ex) {
progressDialog.dismiss();
if (ex instanceof TimeoutException) {
handler.post(timeout_ack);
} else
handler.post(unknown_err);
CloseSinWave();
}
}
}.start();
}
private void onGet() {
if (sreader == null)
return;
time = new TimeCount(R.id.get, 10000, 1000);
time.start();// ¿ªÊ¼¼Æʱ
get.setEnabled(false);
swipe.setEnabled(false);
handler.post(begin_get);
new Thread() {
public void run() {
String Empty = "Empty";
int i = 0;
handler.post(clear_carddata);
try {
T1PAN_data = sreader.GetT1PAN(5000);
if (T1PAN_data == null) {
T1PAN_data = Empty;
} else {
T1PAN_data = changeHexString2CharString(T1PAN_data);
}
i++;
T1Name_Exd = sreader.GetT1HolderName_Exd(5000);
if (T1Name_Exd == null) {
T1Name_Exd = Empty;
} else {
T1Name_Exd = changeHexString2CharString(T1Name_Exd);
}
i++;
T2PAN_data = sreader.GetT2PAN(5000);
if (T2PAN_data == null) {
T2PAN_data = Empty;
} else {
T2PAN_data = changeHexString2CharString(T2PAN_data);
}
i++;
T2Exd_data = sreader.GetT2Exd(5000);
if (T2Exd_data == null) {
T2Exd_data = Empty;
} else {
T2Exd_data = changeHexString2CharString(T2Exd_data);
}
handler.post(display_get_data);
} catch (Exception ex) {
if (ex instanceof TimeoutException) {
time.cancel();
myToast.cancel();
sreader.Cancel();
handler.post(enable_button);
handler.post(timeout_ack);
return;
} else
handler.post(unknown_err);
CloseSinWave();
}
myToast.cancel();
time.cancel();
handler.post(settext_get);
handler.post(enable_button);
}
}.start();
}
private void onDetect() {
am.setStreamVolume(AudioManager.STREAM_MUSIC, maxVol, 0);
if (Detect_sReader() == true) {
handler.post(clear_all);
if (GenerateSinWave() == true) {
Initialization();
}
}
}
}
Here is the Log cat:
05-20 16:26:30.638: E/AndroidRuntime(1497): FATAL EXCEPTION: main
05-20 16:26:30.638: E/AndroidRuntime(1497): java.lang.IllegalArgumentException: Window type can not be changed after the window is added.
05-20 16:26:30.638: E/AndroidRuntime(1497): at android.os.Parcel.readException(Parcel.java:1429)
05-20 16:26:30.638: E/AndroidRuntime(1497): at android.os.Parcel.readException(Parcel.java:1379)
05-20 16:26:30.638: E/AndroidRuntime(1497): at android.view.IWindowSession$Stub$Proxy.relayout(IWindowSession.java:634)
05-20 16:26:30.638: E/AndroidRuntime(1497): at android.view.ViewRootImpl.relayoutWindow(ViewRootImpl.java:3835)
05-20 16:26:30.638: E/AndroidRuntime(1497): at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1384)
05-20 16:26:30.638: E/AndroidRuntime(1497): at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:998)
05-20 16:26:30.638: E/AndroidRuntime(1497): at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:4212)
05-20 16:26:30.638: E/AndroidRuntime(1497): at android.view.Choreographer$CallbackRecord.run(Choreographer.java:725)
05-20 16:26:30.638: E/AndroidRuntime(1497): at android.view.Choreographer.doCallbacks(Choreographer.java:555)
05-20 16:26:30.638: E/AndroidRuntime(1497): at android.view.Choreographer.doFrame(Choreographer.java:525)
Problem seems to be in onAttachedToWindow(). Change the function as below and give it a try.
public void onAttachedToWindow() {
this.getWindow().setType(WindowManager.LayoutParams.TYPE_KEYGUARD);
super.onAttachedToWindow();
}
your targetSdk must be less than 14.
try setting it to 13
Check this Answer. And it works for me.

Android Progress Bar stops working in the middle

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.

Categories

Resources