change dynamically added button background from another function - android

I dinamically add some buttons to my TableL like this
TableLayout table = (TableLayout) findViewById( R.id.tableLayout1 );
Bitmap bmp = BitmapFactory.decodeFile(Environment.getExternalStorageDirectory()+ myPrefLocalMedia + mat_foto);
final ImageButton b = new ImageButton(this);
b.setScaleType(ImageView.ScaleType.FIT_CENTER);
b.setAdjustViewBounds(true);
b.setImageBitmap(bmp);
b.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
ProgressDialog progressDialog = new ProgressDialog(SuperlineaActivity.this);
progressDialog.setMessage("Realizando el pedido...");
progressDialog.setCancelable(false);
b.setPressed(true);
if ( (miPedido == null) || ( miPedido.isEnproceso()==false) ) {
Log.e("log_","Hago post! Creo pedido!!");
Hacerpost eginpost = new Hacerpost(SuperlineaActivity.this, progressDialog);
eginpost.execute(myPrefApiPeticionMaterial,mat_id, PUESTOID, LINEAID, USUARIOID, PRODUCTOID);
} else {
Hacerput puttask = new Hacerput(SuperlineaActivity.this, progressDialog);
puttask.execute(myPrefApiPeticionMaterial,miPedido.getId());
}
}
});
row.addView( b, 300,300 );
When it is pressed it performs some AsyncTask (HttpPost) and it returns one color code. I need to change the pressed background color with that color code but how do I know witch button I clicked?
This is the function where I receive the HttpPost data:
#TargetApi(Build.VERSION_CODES.JELLY_BEAN)
public void erantzuna(JSONObject myJson) {
if ( miPedido == null ) {
AlertDialog alerta = new AlertDialog.Builder(SuperlineaActivity.this).create();
alerta.setTitle("PEDIDO EN PROCESO");
alerta.setMessage("El pedido se a procesado. Espera.");
alerta.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(getApplicationContext(), "Registrado", Toast.LENGTH_SHORT).show();
}
});
alerta.show();
String kolorea = null;
String pedidoid = null;
try {
kolorea = myJson.getString("kolorea");
pedidoid = myJson.getString("pedidoid");
} catch (JSONException e) {
e.printStackTrace();
}
Log.e("log_", "Bueltan da: => " + kolorea);
Log.e("log_", "Bueltan da: => " + pedidoid);
miPedido = new Pedido(pedidoid, kolorea);
try {
if (miPedido.getKolorea().equals("kuadro-gorria")) {
//
// Here I need to change the pressed ImageButton color to RED
//
} elseif ( miPedido.getKolorea().equals("kuadro-urdina")) {
//
// Here I need to change the pressed ImageButton color to BLUE
//
} else {
//
// Here I need to change the pressed ImageButton color to transparent
//
}
} catch (Exception e) {
Log.e("log_","Boton Color => " + e.toString());
}
} else {
miPedido = null;
}
}
Any help or clue?
Thanks in advance

Maybe you should manage your dynamically added buttons, like put them into a list, or, if you won't need a reference for them later, just give the Button to the asyncTask (like in the constructor or something) and change its color in the onPostExecute method of the asynctask. But don't forget to prepare for cases like the Activity gets destroyed while the task waits for the response, as in that case the Button will no longer exist, and this could cause memory leaks as well.

Related

app crash when increase and decrease buttons are pushed

I have 2 buttons for the quality. If the quality is set by typing first, the buttons work well, but if I don't write any quantity and I want to set it by plus button, the app crash.
increaseQuantity.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String textQuantity = quantity.getText().toString();
givenQuantity = Integer.parseInt(textQuantity);
quantity.setText(String.valueOf(givenQuantity + 1));
}
});
decreaseQuantity.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String textQuantity = quantity.getText().toString();
givenQuantity = Integer.parseInt(textQuantity);
//To validate if quantity is greater than 0
if ((givenQuantity - 1) >= 0) {
quantity.setText(String.valueOf(givenQuantity - 1));
} else {
Toast.makeText(EditorActivity.this, R.string.quantity_no_less_then_0, Toast.LENGTH_SHORT).show();
return;
}
}
});
Surround all your parsing lines with try/catch, like:
try {
givenQuantity = Integer.parseInt(textQuantity);
} catch (NumberFormatException e) {
e.printStackTrace();
givenQuantity = 0;
}
when the EditText is empty, a NumberFormatException is thrown because an empty string can not be parsed to int.
check is edittext is empty or not. If empty show toast message to user asking to enter some value to calculate.

RecyclerView scroll is messed up (in the presence of big Bitmaps)

P.S. the big chat bubbles at the bottom of the screen are an image (just like when you send an image via WhatsApp and other messaging apps)
I'm making a simple chatting app. The problem is, whenever I scroll to the top, the view comes back to the very bottom. Here's my OnBindViewHolder code (some parts are omitted because it's too long):
#Override
public void onBindViewHolder(final MessageViewHolder viewHolder, final int i) {
final ChatMessages c = messageList.get(i);
final String from_user = c.getFrom();
String message_type = c.getType();
if (currentUser.equals(from_user)) {
viewHolder.mydisplayName.setText(dummyright);
} else {
viewHolder.displayName.setText(dummyleft);
}
if (currentUser.equals(from_user)) {
leftLayout.setVisibility(View.VISIBLE);
rightLayout.setVisibility(View.GONE);
person = "leftLayout";
} else {
leftLayout.setVisibility(View.GONE);
rightLayout.setVisibility(View.VISIBLE);
person = "rightLayout";
}
if (message_type.equals("text")) {
//set visibility of TextViews and other elements according to which user is sending the message (left/right)
} else if (message_type.equals("image")) {
if (person.equals("leftLayout")) {
viewHolder.mymessageText.setVisibility(View.GONE);
viewHolder.myview_data.setVisibility(View.GONE);
viewHolder.mymessageImage.setVisibility(View.VISIBLE);
Cursor cursor = null;
final String tempUri = c.getDownload_link();
filename = null;
byte[] decodedString = Base64.decode(c.getMessage(), Base64.DEFAULT);
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
options.inPreferredConfig = Bitmap.Config.RGB_565;
options.inSampleSize=512;
decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length,options);
try {
Glide.with(viewHolder.mymessageImage.getContext())
.asBitmap()
.load(decodedString)
.thumbnail(0.5f)
.into(viewHolder.mymessageImage);
decodedString=null;
} catch (Exception e) {
Log.e("chat image right", e.getMessage());
}
File file = null;
if (tempUri != null) {
file = new File(tempUri);
String path = file.getAbsolutePath();
if (tempUri.startsWith("content://")) {
try {
cursor = context.getContentResolver().query(Uri.parse(c.getDownload_link()), null, null, null, null);
if (cursor != null && cursor.moveToFirst()) {
filename = cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME));
}
} finally {
cursor.close();
}
} else if (tempUri.startsWith("file://")) {
filename = file.getName();
}
viewHolder.mymessageImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
AlertDialog.Builder builder;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
builder = new AlertDialog.Builder(context, android.R.style.Theme_Material_Light_Dialog_Alert);
} else {
builder = new AlertDialog.Builder(context);
}
builder.setTitle("Save Image")
.setMessage("Do you want to save this image?")
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// continue with delete
startSaveImageToGallery();
}
})
.setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// do nothing
}
})
.setIcon(android.R.drawable.ic_dialog_alert)
.show();
}
});
} else {
}
} else if (person.equals("rightLayout")) {
//same as above but for the right layout
}
}
}
I've read a lot of questions about this issue and some of the answers said that it's caused by setting visibility inside onBindViewHolder. I don't know where else I would set them because my layouts' visibility are dependent on some data (in this case, who's sending the chats).
Edit: I've just tried my app several times and apparently it only jumps to the bottom when there are pictures being sent, especially when they're 600KB or more in size. I'm loading my images with Glide, they are stored in Base64 and converted to compressed Bitmaps. Do these images cause the messed up scrolling?
1.If the ImageView is wrap_content,set a fixed size value for it.
2.If the OnBindViewHolder method has other asyn operations which are relatived to the UI,deal with them before setData.
3.Check your code,if there are methods such as scroll to

Android: Main Thread blocked despite using AsyncTask

I have a Activity that contains over 100 complex views (with images, text views etc). Showing up these views is to hard to do it without a Thread that loads the views asynchronously. So I tried to do it with an AsyncTask. I am not sure whether this is the correct way because the "hard staff" is something that HAS to be done in the UI Thread.
Now I've got the problem that the UI freezes though I used the onProgressUpdate for adding the views in the to parent view. I thought that this would result in single loading views that appear successive in the parent view. But this is not the case.
doInBackground fires all publishProgress calls and after that the main thread is blocked (activity frozen, loadbar does not rotate anymore). Is there a way to achieve what I wanted to have? I looked for solutions but alway ended up with ideas of using AsyncTask and no one had to do view-stuff as "hard staff". I am not using "get" in the AsyncTask what seems to be a problem with AsyncTask.
Here is my code for this. If you need any further information please tell me!
Is there any other way to solute this problem? Is my AsyncTask implementation not correct? I am looking for a way to load these complex views asyncronous to the parent view without blocking the main thread.
Thanks in advance!
public class LoadKraut extends AsyncTask<Integer,Kraut,Void> {
private Context context;
private LinearLayout parent;
private HashMap<String,HeadlineAlphabet> headlinesAlphabet = new HashMap<String, HeadlineAlphabet>();
private long time;
private Integer kategorie;
private char letter = 'X';
private int counter = 0;
private ProgressDialog dialog;
public LoadKraut(Context context) {
/**
* Kategorie:
* 1 - A-Z
* 2 - Notiz
* 3 - Favorit
* 4 - Giftig
*/
Log.i("Kraut", "Start thread" + (System.currentTimeMillis()-time) + "ms");
this.context = context;
this.dialog = new ProgressDialog(context);
this.time = System.currentTimeMillis();
}
#Override
protected void onPreExecute() {
dialog.setMessage("Lade Kräuter. Dieser Vorgang kann einen Moment dauern.");
dialog.show();
}
#Override
protected Void doInBackground(Integer... params) {
this.kategorie = params[0];
//Create overview
try {
DatabaseHelper databaseHelper = new DatabaseHelper(context);
Dao<Kraut,Integer> dao = databaseHelper.getKrautDAO();
parent = (LinearLayout) ((Activity) context).findViewById(R.id.ll_conainter_sv_uebersicht_kraeuter);
//setKraeuter(list, linearLayout, giftig)
long test = System.currentTimeMillis();
List<Kraut> list = new ArrayList<>();
switch (kategorie) {
case 1:
list = dao.queryForAll();
break;
case 2:
list = dao.queryBuilder().where().ne("notiz","").query();
break;
case 3:
list = dao.queryBuilder().where().eq("favorit",true).query();
break;
case 4:
list = dao.queryBuilder().where().eq("toedlichBunny",true).query();
break;
}
Log.i("Kraut","Fetching duration: " + String.valueOf(System.currentTimeMillis() - test));
Iterator<Kraut> iterator = list.iterator();
while(iterator.hasNext()) {
Kraut kraut = iterator.next();
Log.i("Kraut","called pp for" + kraut.getName());
publishProgress(kraut);
}
} catch (SQLException e) {
e.printStackTrace();
}
Log.i("Kraut", "End " + (System.currentTimeMillis()-time) + "ms");
return null;
}
#Override
protected void onProgressUpdate(Kraut... value) {
//Set all Krauts and headlines A-Z
long test = System.currentTimeMillis();
Kraut kraut = value[0];
Log.i("Kraut", String.valueOf(counter));
if((kategorie==1 || kategorie==4) && kraut.getName().charAt(0)!=letter) {
letter = kraut.getName().charAt(0);
HeadlineAlphabet letterHeadline = new HeadlineAlphabet(context);
letterHeadline.setText(String.valueOf(kraut.getName().charAt(0)));
headlinesAlphabet.put(String.valueOf(letterHeadline.getText()),letterHeadline);
parent.addView(letterHeadline);
}
KrautView krautView=null;
if(kategorie==1 || kategorie==3) {
krautView = new KrautUebersicht(context,kategorie);
} else if(kategorie==2) {
krautView = new KrautUebersichtNotiz(context);
}
if(krautView!=null) {
krautView.setKraut(kraut);
parent.addView((LinearLayout) krautView, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
}
parent.getRootView().invalidate();
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
counter++;
Log.i("Kraut","Kraut View creation duration: " + String.valueOf(System.currentTimeMillis() - test));
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
if(kategorie==1) {
//Set Alphabet Column right side
ArrayList<String> anfangsbuchstaben = Kraut.getAnfangsbuchstaben(context);
// Do this with an xml !
for (int i = 1; i <= 26; i++) {
//Log.i("Kraut", String.valueOf(i));
String currentLetter = Helper.getCharForNumber(i);
int id = context.getResources().getIdentifier("tv_"+currentLetter.toLowerCase(),"id",context.getPackageName());
TextView textView = (TextView) ((Activity) context).findViewById(id);
//If no Kraut contains Letter
if (!anfangsbuchstaben.contains(currentLetter)) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
textView.setTextColor(context.getResources().getColor(R.color.darkgrey, context.getTheme()));
} else {
textView.setTextColor(context.getResources().getColor(R.color.darkgrey));
}
//Make clickable to jump to A-Z Headlines
} else {
textView.setOnClickListener(new JumpToLetterOnClickListener(headlinesAlphabet));
}
}
}
parent.invalidate();
if(dialog.isShowing()) {
dialog.dismiss();
}
}
}
Note that onProgressView() is called repeatedly as your AsyncTask runs. Therefore, it should be kept as short as possible. This also means that your current code is creating lots of views and adding them to the UI. Instead, you should add the view just once and then update its data in onProgressView().
Also, as Mike M. states in the comments, you should not call Thread.sleep() in onProgressView() since it runs on the UI thread. This is most likely the main reason your app is freezing.

Unable to hide button from Listview in Custom Dialog Android

In first activity i have button(Named btIndividual) inside listview from that one custom dialog layout opens. In that custom dialog i have one text and edittext field inside listview and one save Button for posting data to server. Now i want that after posting data to server the button named btIndividual in first activity will go invisible.
Custom Adapter for first activity:
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final ProductChoosed productChoosed = productChoosedAr.get(position);
convertView = View.inflate(SolutionActivity.this, R.layout.custom_solution_row, null);
ImageView categoryImageView = (ImageView) convertView.findViewById(R.id.categoryImageView);
TextView categoryNameTextView = (TextView) convertView.findViewById(R.id.categoryNameTextView);
productsListTextView = (TextView) convertView.findViewById(R.id.productsListTextView);
btIndividual = (Button) convertView.findViewById(R.id.btIndividual);
String catgoryImage = "";
String isTradeProduct = productChoosed.isTradeProduct;
if(isTradeProduct.equals("0")){
btIndividual.setVisibility(View.VISIBLE);
productsListTextView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showTradDialog(position, productChoosedAr.get(position));
}
});
}else{
btIndividual.setVisibility(View.GONE);
}
btIndividual.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showIndividualTradDialog(position,productChoosedAr.get(position));
individual_productChoosedAr.clear();
myList.clear();
idIndividual = "";
mIndCount =1;
checkHideButton = position ;
checkButtonPosition = position;
idIndividual = productChoosedAr.get(position).categoryId;
GetIndividualProducts getIndividualProducts = new GetIndividualProducts();
getIndividualProducts.execute();
showDialog();
Toast toast = Toast.makeText(getApplicationContext(),"Loading...",Toast.LENGTH_LONG);
toast.show();
}
});
Custom Dialog layout :
private void showDialog(){
dialog1 = new Dialog(this);
final Dialog tradDialog = new Dialog(this, android.R.style.Theme_Light_NoTitleBar);
View view = getLayoutInflater().inflate(R.layout.trad_dialog_layout_individual, null);
tradDialog.setCanceledOnTouchOutside(false);
lv = (ListView) view.findViewById(R.id.productsListView);
RelativeLayout saveBtnLayout = (RelativeLayout) view.findViewById(R.id.saveBtnLayout);
// Change MyActivity.this and myListOfItems to your own values
clad = new CustomListAdapterDialog(SolutionActivity.this, individual_productChoosedAr);
lv.setAdapter(clad);
clad.notifyDataSetChanged();
mCount = lv.getChildCount();
saveBtnLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int getChildCount1 = lv.getChildCount();
System.out.print(getChildCount1);
for (int i = 0; i < myList.size(); i++) {
// v = lv.getChildAt(i);
// etPrice = (EditText) v.findViewById(R.id.etPrice);
if(myList.get(i).toString().equals("")){
ProductPrice = "NULL";
}else {
ProductPrice = myList.get(i).toString();
}
// if(ProductPrice.equals("")){
// ProductPrice = "NULL";
// }
productPriceAr.add(ProductPrice);
}
Toast toast = Toast.makeText(getApplicationContext(),"Please wait...",Toast.LENGTH_LONG);
toast.show();
SendIndividualDatatoServer sendIndividualData = new SendIndividualDatatoServer();
sendIndividualData.execute();
}
});
//lv.setOnItemClickListener(........);
dialog1.setContentView(view);
dialog1.show();
}
AsyncTask class for posting data from where i want to disable btIndividual button:
protected void onPostExecute(Void paramVoid) {
super.onPostExecute(paramVoid);
try {
String typeId = "", messageReceived = "";
JSONObject localJSONObject = new JSONObject(this.sendDataResponse);
typeId = localJSONObject.getString("type_id");
messageReceived = localJSONObject.getString("msg");
if (typeId.equals("1")) {
//if i reached here i want to disable that button
// if(checkHideButton == checkButtonPosition){
// btIndividual.setVisibility(View.GONE);
// customSelectedProductsAdapter.notifyDataSetChanged();
// customSelectedProductsAdapter.notifyDataSetInvalidated();
// }
Toast toast = Toast.makeText(SolutionActivity.this,"Individual Data Posted",Toast.LENGTH_LONG);
toast.show();
dialog1.dismiss();
customSelectedProductsAdapter.notifyDataSetChanged();
productPriceAr.clear();
individual_productChoosedAr.clear();
} else
Toast.makeText(SolutionActivity.this, messageReceived, Toast.LENGTH_SHORT).show();
btIndividual.setVisibility(View.VISIBLE);
} catch (Exception localException) {
localException.printStackTrace();
Toast.makeText(SolutionActivity.this, "Network Error Occured", Toast.LENGTH_SHORT).show();
}
I guess the problem is here:
} else
Toast.makeText(SolutionActivity.this, messageReceived, Toast.LENGTH_SHORT).show();
btIndividual.setVisibility(View.VISIBLE);
You set the button visible even if your condition below is true.
I suggest to modify the code something like this:
protected void onPostExecute(Void paramVoid) {
super.onPostExecute(paramVoid);
try {
//1. By default button is visible
btIndividual.setVisibility(View.VISIBLE);
String typeId = "", messageReceived = "";
JSONObject localJSONObject = new JSONObject(this.sendDataResponse);
typeId = localJSONObject.getString("type_id");
messageReceived = localJSONObject.getString("msg");
if (typeId.equals("1")) {
if(checkHideButton == checkButtonPosition){
//2. if condition is true - hide the button
btIndividual.setVisibility(View.GONE);
customSelectedProductsAdapter.notifyDataSetChanged();
customSelectedProductsAdapter.notifyDataSetInvalidated();
}
Toast toast = Toast.makeText(SolutionActivity.this,"Individual Data Posted",Toast.LENGTH_LONG);
toast.show();
dialog1.dismiss();
customSelectedProductsAdapter.notifyDataSetChanged();
productPriceAr.clear();
individual_productChoosedAr.clear();
} else
Toast.makeText(SolutionActivity.this, messageReceived, Toast.LENGTH_SHORT).show();
//3. it is not needed
//btIndividual.setVisibility(View.VISIBLE);
} catch (Exception localException) {
localException.printStackTrace();
Toast.makeText(SolutionActivity.this, "Network Error Occured", Toast.LENGTH_SHORT).show();
}

Android activity recreate itself

My app normally works just fine, until I face a strange problem on specific device. There are 2 activities in App. After I start ActivityB inside of ActivityA, ActivityA starts with no issue. However, after I go back to the ActivityA with pushing back hardware button or calling finish(); inside of closeButton in ActivityB, ActivityA reloads itself. It triggers onCreate() again and reloads all its contents. And I'm not changing orientation of phone. This strange behavior only appears in 15 phones over 1.000 download of app.
This problem only occurs on Galaxy S3 Android OS 4.1.2. And this is also strange.
Do you have any idea why this is happening?
When I start a new Activity inside of button listener like this:
ActivityA.java (MesajlarListViewActivity)
public class MesajlarListViewActivity extends TrackedActivity {
Context context = null;
// contacts JSONArray
JSONArray contacts = null;
ArrayList<Message> productArray = new ArrayList<Message>();
private ProductAdapter adapter;
private ListView productList;
private Runnable viewOrders;
private HoloProgressIndicator profilInfoProgress = null;
ImageView kapatButton = null;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.mesajlar_list);
context = this;
kapatButton = (ImageView) findViewById(R.id.kapat_button);
/* kapat button onclick listener. */
// =================================================================================================================
kapatButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view)
{
// Set vibration on touch.
KnetGenericClass.vibratePhone(context);
finish();
}
});
// =================================================================================================================
//Progress bar.
profilInfoProgress = (HoloProgressIndicator) findViewById(R.id.profil_info_progress);
// cheking internet connectivity.
if(KnetGenericClass.checkInternetConnection(context))
{
// start task!
/* internet var ise web service baglantisi kurmaya baslayabiliriz. */
startActivityIndicatorWithThread();
}
else
{
KnetGenericClass.printErrorMessage(context, "Bağlantı Hatası",
"Lütfen internet bağlantınızı kontrol ediniz.");
}
productList = (ListView) findViewById(R.id.product_list);
adapter = new ProductAdapter(this, R.layout.message_row, productArray);
productList.setAdapter(adapter);
// When user click a view on list view new page is appearing.
productList.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
// Set vibration on touch.
KnetGenericClass.vibratePhone(context);
/* Navigate to message detay activity class with ilan ID. */
Intent myIntent = new Intent(view.getContext(), MesajDetayActivity.class);
myIntent.putExtra("messageID", productArray.get(position).getId());
startActivity(myIntent);
// setting image of clicked message null.
RelativeLayout relativeLayout = (RelativeLayout) view;
ImageView unreadedImageView = (ImageView) relativeLayout.findViewById(R.id.unreaded_image);
unreadedImageView.setImageResource(0);
}
});
}
public class ProductAdapter extends ArrayAdapter<Message> {
ArrayList<Message> items;
public ProductAdapter(Context context, int textViewResourceId, ArrayList<Message> objects) {
super(context, textViewResourceId, objects);
this.items = objects;
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
if(convertView == null)
{
LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = vi.inflate(R.layout.message_row, null);
}
ImageView unreadedImageView = (ImageView) convertView.findViewById(R.id.unreaded_image);
TextView productName = (TextView) convertView.findViewById(R.id.product_name);
TextView productDetail = (TextView) convertView.findViewById(R.id.product_detail);
// TextView productDate = (TextView)
// convertView.findViewById(R.id.product_date);
TextView sentDate = (TextView) convertView.findViewById(R.id.product_date);
productName.setText(items.get(position).getSender());
productDetail.setText(items.get(position).getTitle());
// String bodyNoHTML = items.get(position).getBody();
if(items.get(position).getIsReaded())
{
unreadedImageView.setImageResource(0);
}
else
{
unreadedImageView.setImageResource(R.drawable.bluedot);
}
String dateStr = items.get(position).getSentDate();
try
{
sentDate.setText(dateStr.substring(6, 8) + "." + dateStr.substring(4, 6) + "." + dateStr.substring(0, 4)
+" "+dateStr.substring(8, 10)+":"+dateStr.substring(10, 12));
}
catch(Exception e)
{
sentDate.setText("");
}
return convertView;
}
}// #end of product adapter class.
/* web service'e baglanti kurulan methodu threadin icerisinde cagiriyoruz. */
public void startActivityIndicatorWithThread()
{
// ==============================================================================================
// getting ilan details into arraylist.
// setting up thread.
viewOrders = new Runnable() {
public void run()
{
getMessageListFromWebService();
}
};
Thread thread = new Thread(null, viewOrders, "MagentoBackground");
thread.start();
profilInfoProgress.start();
// ==============================================================================================
// #end of the thread declaration.
}
public void getMessageListFromWebService()
{
// Creating JSON Parser instance
JSONParser jParser = new JSONParser(context);
// getting JSON string from URL
JSONArray jsonArray = jParser.getAuthorizedInfoFromUrlToJSONArray(
WebServiceInfo.getKnetWebServiceLink()+"/API/Member/GetInboxMessageList", MainActivity.getAccessToken());
// if json is null then there is a problem.
if(jsonArray == null)
{
// if json array is null then print error message.
runOnUiThread(showAlertMessage);
runOnUiThread(returnRes);
return;
}
try
{
// Eger aranilan kritere gore ilan yok ise hata mesaji basiyoruz.
if(jsonArray.length() == 0)
{
// if json array is null then print error message.
runOnUiThread(showAlertIlanYokMessage);
runOnUiThread(returnRes);
return;
}
// looping through All Contacts
for (int i = 0; i < jsonArray.length(); i++)
{
JSONObject c = jsonArray.getJSONObject(i);
// Storing each json item in variable
// String id = c.getString(TAG_ID);
String id = c.getString("Id");
String sender = c.getString("Sender");
// String body = c.getString("Body");
String title = c.getString("Title");
String sentDate = c.getString("SentDate");
Boolean isReaded = c.getBoolean("IsRead");
Message productObject = new Message(id, sender, "", title, sentDate, isReaded);
productArray.add(productObject);
}
}
catch (Exception e)
{
Log.e("BACKGROUND_PROC", e.getMessage());
}
runOnUiThread(returnRes);
}
// #end of thread.
private Runnable returnRes = new Runnable() {
public void run()
{
profilInfoProgress.stop();
adapter.notifyDataSetChanged();// refreshing data over adapter in
// list view.
}
};
// #end of thread.
private Runnable showAlertMessage = new Runnable() {
public void run()
{
// Bu hata genelde linkteki problemden, servera ulasilamamasindan
// veya timeouttan meydana gelir.
Toast.makeText(getApplicationContext(),
"Mesajlar alınamadı lütfen daha sonra tekrar deneyiniz.",
Toast.LENGTH_LONG).show();
}
};
private Runnable showAlertIlanYokMessage = new Runnable() {
public void run()
{
// Bu hata aranilan kelimeye gore ilan bulunamazsa gelir.
Toast.makeText(getApplicationContext(),
"Mesajlar bulunamadı.",
Toast.LENGTH_LONG).show();
}
};
}
========================================================================
ActivityB.java (MesajDetayActivity.java)
public class MesajDetayActivity extends TrackedActivity {
private HoloProgressIndicator profilInfoProgress = null;
TextView titleTextView = null;
TextView senderTextView = null;
TextView dateTextView = null;
WebView bodyWebView = null;
Message messageObject = null;
String messageID = null;
ImageView kapatButton = null;
Context context;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.mesajdetaylari);
context = this;
kapatButton = (ImageView) findViewById(R.id.kapat_button);
/* kapat button onclick listener. */
// =================================================================================================================
kapatButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view)
{
// Set vibration on touch.
KnetGenericClass.vibratePhone(context);
finish();
}
});
// =================================================================================================================
//Progress bar.
profilInfoProgress = (HoloProgressIndicator) findViewById(R.id.profil_info_progress);
Bundle extras = getIntent().getExtras();
if(extras != null)
{
messageID = extras.getString("messageID");
}
titleTextView = (TextView) findViewById(R.id.title_textview);
senderTextView = (TextView) findViewById(R.id.sender_textview);
dateTextView = (TextView) findViewById(R.id.date_textview);
bodyWebView = (WebView) findViewById(R.id.mesaj_webView);
// Show the ProgressDialog on this thread
profilInfoProgress.start();
// Start a new thread that will download all the data
new MakeItTask().execute();
}
// Async task.
private class MakeItTask extends AsyncTask<String, Void, Object> {
protected Object doInBackground(String... args)
{
Log.i("MyApp", "Background thread starting");
// This is where you would do all the work of downloading your data
// getting message detay
/* connect to web service */
getMessageDetayFromWebService();
return null;
}
protected void onPostExecute(Object result)
{
// Pass the result data back to the main activity
// TakipListeActivity.this.data = result;
try
{
titleTextView.setText("Başlık: " + messageObject.getTitle());
senderTextView.setText("Gönderen: " + messageObject.getSender());
dateTextView.setText("Tarih: " + messageObject.getSentDate().substring(6, 8) + "."
+ messageObject.getSentDate().substring(4, 6) + "."
+ messageObject.getSentDate().substring(0, 4));
if(!messageObject.getBody().contains("img"))
{
bodyWebView.loadDataWithBaseURL(null, messageObject.getBody(), "text/html", "UTF-8", null);
}
}
catch (Exception e)
{
Log.e(CONNECTIVITY_SERVICE, "Mesaj Detayi bilgileri basilamadi.");
}
profilInfoProgress.stop();
}
}
/* web service'e baglanti kurulan methodu threadin icerisinde cagiriyoruz. */
public void getMessageDetayFromWebService()
{
// Creating JSON Parser instance
JSONParser jParser = new JSONParser(context);
// getting JSON string from URL
JSONObject jsonObject = jParser.getAuthorizedInfoFromUrlToJSONObject(
WebServiceInfo.getKnetWebServiceLink()+"/API/Member/GetInboxMessage/" + messageID, MainActivity.getAccessToken());
// if json is null then there is a problem.
if(jsonObject == null)
{
return;
}
try
{
String title = jsonObject.getString("Title");
String id = jsonObject.getString("Id");
String sender = jsonObject.getString("Sender");
String date = jsonObject.getString("SentDate");
String body = jsonObject.getString("Body");
messageObject = new Message(id, sender, body, title, date, true);
}
catch (Exception e)
{
Log.e("BACKGROUND_PROC", e.getMessage());
}
}// #end of getIlanDetayFromWebService.
}
Edit: Not only these two activities have this problem, all the activities acting same behavior on some phones.
Check to see whether Don't keep activities under Settings > System > Developer options > Apps is enabled or not.
The Activity documentation (http://developer.android.com/reference/android/app/Activity.html) says the following about the lifecycle of a background activity:
A background activity (an activity that is not visible to the user and has been paused) is no longer critical, so the system may safely kill its process to reclaim memory for other foreground or visible processes. If its process needs to be killed, when the user navigates back to the activity (making it visible on the screen again), its onCreate(Bundle) method will be called with the savedInstanceState it had previously supplied in onSaveInstanceState(Bundle) so that it can restart itself in the same state as the user last left it.
In other words, ActivityA may or may not be destroyed by the operating system while ActivityB is active, so this situation has to be handled in the code. If ActivityA has been destroyed, onCreate(Bundle) will be called, when the user presses the back button in ActivityB.
There's an Android developer setting called "Do not keep activities". The description for this option is "Destroy every activity as soon as the user leaves it." This sounds like a good description of what you're seeing, and since you're only seeing it on a few phones the idea that this is caused by a non-default system setting seems plausible.
Ideally your app would still work in this scenario, even if less optimally. But if this setting is a problem for your app, you may wish to document this problem for your users.
Have you tried changing the launchmode in the Android Manifest? Try adding this to your Activity declaration:
android:launchMode="singleTask"
Next, try using startActivityForResult, instead of startActivity. This will force Activity A to call its onActivityResult(int, int, Intent) method when Activity B finishes - which may skip this (buggy) call to onCreate. Then, in Activity A, implement the method to do something (such as printing a debug statement):
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
Log.i("Test", "Did this work???");
//TODO send notification to your server to verify this works?
}
I do not see any problem in this behaviour.
In case you wish to preserve the state of ActivityA, make use of the methods onSaveInstanceState and onRestoreInstanceState. See Activity Lifecycle at http://developer.android.com/reference/android/app/Activity.html#ActivityLifecycle for more details.
See also https://stackoverflow.com/a/10492967/332210 for a deeper understanding.
You can try one thing provide your layout in onCreate() and do the rest of the work in onStart() ?? if it works??
LIKE:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.show);
}
and
#Override
protected void onStart() {
// TODO Auto-generated method stub
super.onStart();
Log.i(TAG, "On Start .....");
}
See Activity Lifecycle
Perhaps you should use
Intent startIntent = new Intent(view.getContext(), ActivityB.class);
startActivity(startIntent);
finish() ;
And
Intent startIntent = new Intent(view.getContext(), ActivityA.class);
startActivity(startIntent);
finish() ;
each time you go back or forward.
It too faced the exact problem and solved issue by Using android:launchMode="standard" in activity of manifest.
Override onStart() and onResume method in Activity A and check if the problem is still persist. and if possible please give your activtiy A and B code here.
Activity A uses layout R.layout.mesajlar_list
Activity B uses layout R.layout.mesajdetaylari
But both have the following line of code:
kapatButton = (ImageView) findViewById(R.id.kapat_button);
Which layout is R.id.kapat_button in? Using the same id in different layouts is a very risky thing to do. I can't guarantee it's causing what you're seeing, but it is the sort of thing that may cause weird behaviour.
I think it is not because of memory the limit.
https://www.box.com/s/7pd0as03bb8wwumuc9l9
You should test these two activities and check whether it is happening in this example too or not. Please share your AndroidManifest.xml file content too, it will help with debugging.
I got this issue recently, and this make me annoyed. I think that issue around 2 options solution to check but useless.
About the setting "Don't keep activities" corrected here, I used this code to check that it optional checked or not (my test device customize base on version 2.3.5 and not show this option):
private boolean isAlwaysFinishActivitiesOptionEnabled() {
int alwaysFinishActivitiesInt = 0;
if (Build.VERSION.SDK_INT >= 17) {
alwaysFinishActivitiesInt = Settings.System.getInt(getApplicationContext().getContentResolver(), Settings.Global.ALWAYS_FINISH_ACTIVITIES, 0);
} else {
alwaysFinishActivitiesInt = Settings.System.getInt(getApplicationContext().getContentResolver(), Settings.System.ALWAYS_FINISH_ACTIVITIES, 0);
}
if (alwaysFinishActivitiesInt == 1) {
return true;
} else {
return false;
}
}
Result check is false in my case. I also check the memory when running application and it nothing occur.
you can use android:launchMode="singleTop"in manifest.
<activity
android:name=".MainActivity"
android:label="#string/app_name"
android:launchMode="singleTop"
android:configChanges="orientation|keyboardHidden|screenSize"
android:theme="#style/AppTheme.NoActionBar">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>

Categories

Resources