imageview not showing, wieght and height 0 - android

Hello and thank you for taking the time to read this. I am a beginner in Android though I have experience in C# and C++. I am currently generating a qr with a button that is supposed to turn an invisible imageview visible. here is my xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".ChargeActivity">
<include layout="#layout/toolbar" />
<EditText
android:id="#+id/currency_amount"
android:layout_width="200dp"
android:layout_height="40dp"
android:layout_centerHorizontal="true"
android:layout_marginTop="272dp"
android:inputType="numberDecimal"
android:hint="Ingrese el monto"
app:layout_anchor="#+id/include"
app:layout_anchorGravity="center" />
<Spinner
android:id="#+id/spinner"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_alignParentTop="true"
android:layout_alignParentEnd="true"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="-143dp"
android:layout_marginEnd="-12dp"
android:layout_marginBottom="3dp" />
<Button
android:id="#+id/generateqr_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:gravity="center"
android:onClick="onClick"
android:text="Generar QR"
app:layout_anchor="#+id/include"
app:layout_anchorGravity="center" />
<ListView
android:id="#+id/transactions"
android:layout_width="match_parent"
android:layout_height="300dp"
android:layout_alignParentStart="true"
android:layout_alignParentBottom="true"
android:layout_marginBottom="19dp" />
<ImageView
android:id="#+id/qr_image"
android:layout_width="300dp"
android:layout_height="300dp"
android:layout_centerInParent="true"
/>
</RelativeLayout>
and here is my java
public class ChargeActivity extends AppCompatActivity {
public static final String ARG_USER = "USER";
String user = "";
private Bitmap bitmap;
private ImageView qrImage;
private String inputValue;
private EditText amount;
private ListView transactions;
private Spinner spinner;
private static final String[] currencies = {"Bolivars", "Petros", "Dollars"};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_charge);
user = getIntent().getStringExtra(ARG_USER);
qrImage = findViewById(R.id.qr_image);
qrImage.setVisibility(View.GONE);
Toolbar toolbar = findViewById(R.id.toolbar);
toolbar.setTitle(user);
setSupportActionBar(toolbar);
// Get a support ActionBar corresponding to this toolbar
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
setContentView(R.layout.activity_charge);
//Spinner Setup
spinner = (Spinner) findViewById(R.id.spinner);
final ArrayAdapter<String> adapter = new ArrayAdapter<String>(ChargeActivity.this,
android.R.layout.simple_spinner_item, currencies);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
//ListView Setup
transactions = findViewById(R.id.transactions);
ArrayList<String> transaction_list = new ArrayList<String>();
transaction_list.add("bolaeyunke te ha enviado 1920 petros");
transaction_list.add("bolaeyunke te ha enviado 1932232320 bolivares");
transaction_list.add("bolaeyunke te ha enviado 1923230 dolares");
transaction_list.add("El Comandante te ha enviado 120 petros");
ArrayAdapter transaction_adapter = new ArrayAdapter(ChargeActivity.this, android.R.layout.simple_list_item_1, transaction_list);
transactions.setAdapter(transaction_adapter);
//Generate QR button setup
Button generateQRButton = findViewById(R.id.generateqr_button);
generateQRButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
amount = findViewById(R.id.currency_amount);
String montos = amount.getText().toString();
inputValue = user + ";" + adapter.getItem(spinner.getSelectedItemPosition()).toString()+";"+amount.getText().toString();
//setting up for qr display
WindowManager manager = (WindowManager) getSystemService(WINDOW_SERVICE);
Display display = manager.getDefaultDisplay();
Point point = new Point();
display.getSize(point);
int width = point.x;
int height = point.y;
int smallerDimension = width < height ? width : height;
smallerDimension = smallerDimension * 3 / 4;
QRGEncoder qrgEncoder = new QRGEncoder(inputValue, null, QRGContents.Type.TEXT, smallerDimension);
qrgEncoder.setColorBlack(Color.RED);
qrgEncoder.setColorWhite(Color.BLUE);
try {
// Getting QR-Code as Bitmap
bitmap = qrgEncoder.getBitmap();
// Setting Bitmap to ImageView
qrImage.setImageBitmap(Bitmap.createScaledBitmap(bitmap, 120, 120, false));
qrImage.setVisibility(View.VISIBLE);
//Still need to implement an escape from showing the qr image
} catch (Exception e) {
e.getMessage();
}
}
});
}
My imageview not only stays invisible, but when I debug, I see that the width and height are 0 for the imageview. I get no errors but it just does not show. I added the bitmap resizing after reading through some questions and thinking that that was the problem.

Related

How to display Stacked Bar graph/chart in android studio?

I have to create a Stack-bar graph and my requirement is to graph should look like this.
I have checked many graph libraries but no one is providing this type of UI.
is this possible to achieve?
So I finally found a way for that.
Step 1: Add 3 views with respective colors and a button like in below XML:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<View
android:layout_width="75sp"
android:layout_height="15sp"
android:layout_marginTop="100sp"
android:layout_marginStart="10sp"
android:background="#ff0000"
android:id="#+id/viewOverdue"/>
<View
android:layout_width="75sp"
android:layout_height="15sp"
android:layout_marginTop="100sp"
android:layout_marginStart="2sp"
android:background="#FFDD00"
android:layout_toEndOf="#+id/viewOverdue"
android:id="#+id/viewActive"/>
<View
android:layout_width="75sp"
android:layout_height="15sp"
android:layout_marginTop="100sp"
android:layout_marginStart="2sp"
android:background="#00FF00"
android:layout_toEndOf="#+id/viewActive"
android:id="#+id/viewDone"/>
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:hint="Enter Overdue"
android:id="#+id/editOverdue"
android:layout_below="#+id/viewActive"
android:layout_marginTop="100sp"/>
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:hint="Enter Active"
android:layout_below="#+id/editOverdue"
android:id="#+id/editActive"
android:layout_marginTop="2sp"/>
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:hint="Enter Done"
android:layout_below="#+id/editActive"
android:id="#+id/editDone"
android:layout_marginTop="2sp"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="submit"
android:id="#+id/btnSubmit"
android:layout_below="#id/editDone"
android:layout_marginTop="20sp"/>
</RelativeLayout>
This is how it will Look:
Do note that views are set to invisible initially.
Step 2: The coding part:
MainActivity.java
public class MainActivity extends AppCompatActivity {
private EditText typeActive, typeDone, typeOverdue;
private Button btnSubmit;
private View viewDone, viewOverDue, viewActive;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
typeActive = findViewById(R.id.editActive);
typeDone = findViewById(R.id.editDone);
typeOverdue = findViewById(R.id.editOverdue);
btnSubmit = findViewById(R.id.btnSubmit);
viewDone = findViewById(R.id.viewDone);
viewActive = findViewById(R.id.viewActive);
viewOverDue = findViewById(R.id.viewOverdue);
viewDone.setVisibility(View.INVISIBLE);
viewOverDue.setVisibility(View.INVISIBLE);
viewActive.setVisibility(View.INVISIBLE);
//Type all the number of tasks and press the submit button
btnSubmit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final String tasksActive = typeActive.getText().toString();
final String tasksDone = typeDone.getText().toString();
final String tasksOverdue = typeOverdue.getText().toString();
int intTaskActive = Integer.parseInt(tasksActive);
int intTaskDone = Integer.parseInt(tasksDone);
int intTaskOverdue = Integer.parseInt(tasksOverdue);
int totalTasks = intTaskActive + intTaskOverdue + intTaskDone;
float percentageActive = (intTaskActive*100.0f)/totalTasks;
float percentageDone = (intTaskDone*100.0f)/totalTasks;
float percentageOverdue = (intTaskOverdue*100.0f)/totalTasks;
int intPercActive = (int)percentageActive;
int intPercDone = (int)percentageDone;
int intPercOverdue = (int)percentageOverdue;
viewDone.setVisibility(View.VISIBLE);
viewOverDue.setVisibility(View.VISIBLE);
viewActive.setVisibility(View.VISIBLE);
viewDone.setLayoutParams(new RelativeLayout.LayoutParams(intPercDone*10, 50));
viewActive.setLayoutParams(new RelativeLayout.LayoutParams(intPercActive*10, 50));
viewOverDue.setLayoutParams(new RelativeLayout.LayoutParams(intPercOverdue*10, 50));
}
});
}
}
This is the output after execution:
So how this works is you type the number of tasks in the edittext. It doesn't matter how you get the number of tasks but you need to convert it to percentage of total length of the stackBar or whatever you call it.
So finally you just assign each view the respective width as per the number.

Issue resizing ImageView programmatically

I am stuck trying to resize ImageView objects.
The issue is that when I set the width/height programmatically, I see the width/height change with the debugger tool in eclipse.
However, the image will not scale to the new size, and maintains its current ratios. In some cases it even puts the original image at its current size, and moving to a different activity will resize it (somewhat) correctly.
Screenshots:
After opening the app
http://imgur.com/ha9s9rL
After opening and closing a different activity
http://imgur.com/DrBIJaI
I would like for the images to sit next to each other, with the same width/height for each image.
onCreate() Method:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_behavior);
listView = (ListView) findViewById(R.id.display_behavior_listview);
List<Behavior> behaviorList = parseCatagories();
List<View> views = getCatagoryViewsFromBehaviorList(behaviorList);
// Setup array adapter
BehaviorRow behaviorRows[] = getBehaviorRows(views);
int viewCount = 0;
View view;
for (BehaviorRow row : behaviorRows) {
if (viewCount < views.size()) {
view = views.get(viewCount);
row.setBehaviorOne(view);
viewCount++;
view = views.get(viewCount);
row.setBehaviorTwo(view);
viewCount++;
}
Log.i("BehaviorRowDat", row.toString());
}
BehaviorRowAdapter adapter = new BehaviorRowAdapter(getApplicationContext(), R.layout.catagory_row,
behaviorRows);
listView.setAdapter(adapter);
}
onWindowFocusChanged() Method:
#Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
ImageView catagoryOne;
ImageView catagoryTwo;
for (int i = 0; i < listView.getChildCount(); i++) {
catagoryOne = (ImageView) listView.getChildAt(i).findViewById(R.id.catagory_space_one);
catagoryTwo = (ImageView) listView.getChildAt(i).findViewById(R.id.catagory_space_two);
resizeImageView(catagoryOne);
resizeImageView(catagoryTwo);
}
}
Resize Image Code:
private ImageView resizeImageView(ImageView image) {
// Set length/width
int length = calculateLengthOfImages();
image.getLayoutParams().height = length;
image.getLayoutParams().width = length;
// Set Padding
int padding = calculatePaddingOfImages();
image.setPadding(padding, padding, padding, padding);
return image;
}
XML:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/catagory_row_created"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:baselineAligned="false"
android:orientation="horizontal"
android:padding="10dp"
android:weightSum="1" >
<ImageView
android:id="#+id/catagory_space_one"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:adjustViewBounds="true"
android:contentDescription="#string/catagory_placeholder"
android:scaleType="centerCrop" />
<ImageView
android:id="#+id/catagory_space_two"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:adjustViewBounds="true"
android:contentDescription="#string/catagory_placeholder"
android:scaleType="centerCrop" />
</LinearLayout>
Try changing the scaleType attribute in your ImageViews to:
android:scaleType="fitXY"
Alternatively, you can add this line in your resizeImageView() method:
image.setScaleType(ScaleType.FIT_XY);
Hope that helps!
Replace your xml with this:
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/catagory_row_created"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:baselineAligned="false"
android:orientation="horizontal"
android:padding="10dp">
<ImageView
android:id="#+id/catagory_space_one"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:layout_marginRight="5dp"
android:layout_marginEnd="5dp"
android:scaleType="centerCrop" />
<ImageView
android:id="#+id/catagory_space_two"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:layout_marginLeft="5dp"
android:layout_marginStart="5dp"
android:scaleType="centerCrop" />
</LinearLayout>
In onCreate() of your activity, add this:
final ImageView imageView1 = (ImageView) findViewById(R.id.catagory_space_one);
final ImageView imageView2 = (ImageView) findViewById(R.id.catagory_space_two);
imageView1.post(new Runnable() {
#Override
public void run() {
imageView1.getLayoutParams().height = imageView1.getWidth();
imageView1.requestLayout();
}
});
imageView2.post(new Runnable() {
#Override
public void run() {
imageView2.getLayoutParams().height = imageView2.getWidth();
imageView2.requestLayout();
}
});
So what basically I did is I have stretched the two images' width equally to take the whole space in xml using layout_weight, then I have set the images' height to be like their respective widths in code. So now they are square-shaped.
Hope that helps.

Cardslib - How to set action for button events of custom cards on CardRecyclerView

I am trying to use Cardslib to create a RecyclerView with custom layout rows that would expand when I click a button on them. I followed customization guide and create both custom layout and custom card class, the cards do appear correctly like this
but I cant figure out how to set clicking event for view elements on this card.
In activity_main.xml, I have a CardRecyclerView:
<it.gmariotti.cardslib.library.recyclerview.view.CardRecyclerView
android:layout_width="match_parent"
android:layout_height="match_parent"
card:list_card_layout_resourceID="#layout/my_cardview_layout"
android:id="#+id/my_recyclerview"/>
my_cardview_layout.xml:
<it.gmariotti.cardslib.library.view.CardViewNative xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:card="http://schemas.android.com/apk/res-auto"
android:id="#+id/list_cardId"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="12dp"
android:layout_marginRight="12dp"
card:card_layout_resourceID="#layout/my_material_card_layout"
style="#style/card_external"
android:layout_marginTop="12dp" />
my_material_card_layout.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<it.gmariotti.cardslib.library.view.ForegroundLinearLayout
android:id="#+id/card_main_layout"
style="#style/card.native.main_layout_foreground"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<ImageView
android:layout_width="match_parent"
android:layout_height="210dp"
android:id="#+id/mycard_image"
android:src="#drawable/sea"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Title"
android:id="#+id/mycard_title"
android:paddingTop="24dp"
android:paddingLeft="20dp"/>
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"
android:text="Subtitle"
android:id="#+id/mycard_subtitle"
android:paddingLeft="20dp" />
<LinearLayout
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="#dimen/actions_padding"
android:paddingLeft="#dimen/actions_padding_left"
android:paddingRight="#dimen/actions_padding_left">
<TextView
android:id="#+id/mycard_suppaction1"
android:text="SHARE"
android:background="?android:selectableItemBackground"
android:layout_width="wrap_content"
style="#style/card.native.actions"
android:layout_height="wrap_content"/>
<TextView
android:id="#+id/mycard_suppaction2"
android:text="LEARN MORE"
android:background="?android:selectableItemBackground"
android:layout_width="wrap_content"
style="#style/card.native.actions"
android:layout_height="wrap_content"/>
</LinearLayout>
</it.gmariotti.cardslib.library.view.ForegroundLinearLayout>
<FrameLayout
android:id="#+id/card_content_expand_layout"
style="#style/card.native.main_contentExpand"
android:layout_width="match_parent"
android:layout_height="wrap_content"
>
</FrameLayout>
My main activity:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ArrayList<Card> cards = new ArrayList<Card>();
//CardViewNative cardView = (CardViewNative) findViewById(R.id.myMaterialCardView);
for(int i = 0; i<3; i++) {
MyMaterialCard card = new MyMaterialCard(this);
CardExpand expand = new CardExpand(getApplicationContext());
//Set inner title in Expand Area
expand.setTitle(" Hidden content");
card.addCardExpand(expand);
card.setId("" + i);
cards.add(card);
}
CardArrayRecyclerViewAdapter mCardArrayAdapter = new CardArrayRecyclerViewAdapter(this, cards);
//Staggered grid view
CardRecyclerView mRecyclerView = (CardRecyclerView) this.findViewById(R.id.my_recyclerview);
mRecyclerView.setHasFixedSize(false);
mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
//Set the empty view
if (mRecyclerView != null) {
mRecyclerView.setAdapter(mCardArrayAdapter);
}
}
my custom card class:
public class MyMaterialCard extends Card {
ImageView mImage;
TextView mTitle;
TextView mSubtitle;
TextView mActionButton1;
TextView mActionButton2;
public MyMaterialCard(Context context) {
super(context, R.layout.my_cardview_layout);
}
public MyMaterialCard(Context context, int innerLayout) {
super(context, innerLayout);
}
#Override
public void setupInnerViewElements(ViewGroup parent, View view) {
mImage = (ImageView) view.findViewById(R.id.mycard_image);
mTitle = (TextView) view.findViewById(R.id.mycard_title);
mSubtitle = (TextView) view.findViewById(R.id.mycard_subtitle);
mActionButton1 = (TextView) view.findViewById(R.id.mycard_suppaction1);
mActionButton2 = (TextView) view.findViewById(R.id.mycard_suppaction2);
mActionButton1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(getContext(), "action 1", Toast.LENGTH_SHORT).show();
}
});
ViewToClickToExpand viewToClickToExpand =
ViewToClickToExpand.builder()
.setupView(mActionButton2);
setViewToClickToExpand(viewToClickToExpand);
}}
I think the problem maybe the my_cardview_layout.xml, however, if i set card:list_card_layout_resourceID="#layout/my_material_card_layout"
in recyclerview and
public MyMaterialCard(Context context) {
super(context, R.layout.my_material_card_layout);}
they will not appear as cards:
have been working on this for 2 days and still can not get those buttons to work ( tried using Cardslib material card but when add expand, nothing happened). Really appreciate any help, thank you!
On main activity, add function setOnClickListener:
for(int i = 0; i<3; i++) {
MyMaterialCard card4 = new MyMaterialCard(this);
card.setOnClickListener(new Card.OnCardClickListener() {
#Override
public void onClick(Card card, View view) {
Toast.makeText(view.getContext()," Click on ActionArea ",Toast.LENGTH_SHORT).show();
}
});
CardExpand expand = new CardExpand(getApplicationContext());
//Set inner title in Expand Area
expand.setTitle(" Hidden content");
card.addCardExpand(expand);
card.setId("" + i);
cards.add(card4);
}
I think this could help some people, I hope not you xD (1 year, 10 months ago)

ListView is not visible

I cant set my ListView dynamically after getting json response from backend.
SherlockNavigationDrawer extends ActionBarActivity
Activity -
public class Forum extends SherlockNavigationDrawer implements OnClickListener {
AsyncTask<Void, String, Void> forumTask;
ProgressDialog pDialog;
TextView newPost;
Button first, last, next, prev;
ListView list;
LinearLayout nopost;
MyPostListAdapter adapter;
public static final String MyPREFERENCES = "MyPrefs";
SharedPreferences sharedpreferences;
String get = "";
JSONObject json;
JSONParser jp;
JSONArray id, user_id, user_name, date, file_path, description, title,
hut_name, hut_id, ttl_likes, ttl_comment;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.forum);
setTitle("Space Huts | Forum");
// newPost = (TextView) findViewById(R.id.tv_test);
first = (Button) findViewById(R.id.bt_first);
prev = (Button) findViewById(R.id.bt_prev);
next = (Button) findViewById(R.id.bt_next);
last = (Button) findViewById(R.id.bt_last);
list = (ListView) findViewById(R.id.lv_posts);
nopost = (LinearLayout) findViewById(R.id.ll_none);
first.setOnClickListener(this);
prev.setOnClickListener(this);
next.setOnClickListener(this);
last.setOnClickListener(this);
// do a get request to server for getting latest 5 pagination posts
doGETrqst("first");
}
private void doGETrqst(final String page) {
// TODO Auto-generated method stub
forumTask = new AsyncTask<Void, String, Void>() {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Forum.this);
pDialog.setMessage("Refreshing " + page + " page.....");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
sharedpreferences = getSharedPreferences(MyPREFERENCES,
Context.MODE_PRIVATE);
String usrid = sharedpreferences.getString("sesid", "");
// Create URL string
String URL = "http://xxx.xxx?id="
+ usrid + "&page=" + page;
Log.i("json url ", URL);
try {
jp = new JSONParser();
JSONObject json = jp.getJSONFromUrl(URL);
id = json.getJSONArray("id");
user_id = json.getJSONArray("user_id");
user_name = json.getJSONArray("user_name");
date = json.getJSONArray("date");
file_path = json.getJSONArray("file_path");
description = json.getJSONArray("description");
title = json.getJSONArray("title");
hut_name = json.getJSONArray("hut_name");
hut_id = json.getJSONArray("hut_id");
ttl_likes = json.getJSONArray("ttl_likes");
ttl_comment = json.getJSONArray("ttl_comment");
Log.e("recieved" , id.getString(2));
} catch (Exception ex) {
Log.e("error","error");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
forumTask = null;
pDialog.dismiss();
setListView();
}
};
forumTask.execute(null, null, null);
}
private void setListView() {
// TODO Auto-generated method stub
final List<Posts> listposts = new ArrayList<Posts>();
// create list view arraylist for list adapter
for (int i = 0, length = title.length(); i < length - 1; ++i) {
Posts post = new Posts();
try {
post.setHutname(hut_name.getString(i));
post.setPostname(title.getString(i));
post.setUsername(user_name.getString(i));
post.setDate(date.getString(i));
listposts.add(post);
} catch (JSONException e) {
Toast.makeText(this, "Oooppss connectivity error",
Toast.LENGTH_SHORT).show();
}
}
// if there are new posts to show , remove nopost linear layout
if (listposts.size() > 0) {
nopost.setVisibility(View.GONE);
//set the adapter
adapter = new MyPostListAdapter(listposts , Forum.this );
list.setAdapter(adapter);
}
}
#Override
public void onClick(View arg0) {
switch (arg0.getId()) {
case R.id.bt_first:
doGETrqst("first");
break;
case R.id.bt_next:
doGETrqst("next");
break;
case R.id.bt_prev:
doGETrqst("prev");
break;
case R.id.bt_last:
doGETrqst("last");
break;
}
}
}
I want to fill my list view dynamically by getting json response from backend , when user press buttons to get next or previous posts.
However there are no errors in logcat , neither the list view is shown .But this part of setListView() do works ,as my linearlayout implements View.GONE successfully -
if (listposts.size() > 0) {
nopost.setVisibility(View.GONE);
//set the adapter
adapter = new MyPostListAdapter(listposts , Forum.this );
list.setAdapter(adapter);
}
XML LAYOUT forum.xml -
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#000000"
android:orientation="vertical"
android:weightSum="0" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="20"
android:orientation="vertical" >
<TextView
android:id="#+id/tv_newpost"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_gravity="center"
android:background="#drawable/general_buttons"
android:clickable="true"
android:text="New Post"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#drawable/click_text_color"
android:textSize="30dp" />
<LinearLayout
android:id="#+id/ll_none"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="10dp"
android:background="#drawable/shadow"
android:gravity="center"
android:orientation="vertical" >
<TextView
android:id="#+id/tv_none"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:fontFamily="sans-serif-thin"
android:text="No New Post"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#000000" />
<ImageView
android:id="#+id/iv_none"
android:layout_width="150dp"
android:layout_height="match_parent"
android:src="#drawable/none" />
</LinearLayout>
<ScrollView
android:id="#+id/sv_posts"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<ListView
android:id="#+id/lv_posts"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="5dp"
android:visibility="gone" >
</ListView>
</ScrollView>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:orientation="horizontal" >
<Button
android:id="#+id/bt_first"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="10dp"
android:background="#drawable/general_buttons"
android:paddingLeft="15dp"
android:paddingRight="20dp"
android:text="FIRST"
android:textColor="#drawable/click_text_color" />
<Button
android:id="#+id/bt_prev"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#drawable/general_buttons"
android:paddingLeft="15dp"
android:paddingRight="20dp"
android:text="<<"
android:textColor="#drawable/click_text_color" />
<Button
android:id="#+id/bt_next"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#drawable/general_buttons"
android:paddingLeft="20dp"
android:paddingRight="15dp"
android:text=">>"
android:textColor="#drawable/click_text_color" >
</Button>
<Button
android:id="#+id/bt_last"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:background="#drawable/general_buttons"
android:paddingLeft="20dp"
android:paddingRight="15dp"
android:text="LAST"
android:textColor="#drawable/click_text_color" />
</LinearLayout>
</LinearLayout>
After getting responses i updated my code like this -
in onCreate() - before doGETReqst() -
adapter = new MyPostListAdapter(listResults , Forum.this );
list.setAdapter(adapter);
in setListView() -
if (listposts.size() > 0) {
nopost.setVisibility(View.GONE);
//set the adapter
listResults.clear();
listResults.addAll(listposts);
adapter.notifyDataSetChanged();
}
My result is this, now how can i set this into scrollview, in which i nested ListView...i checked my all layouts -
Finally after removing android:view="gone" , adding adapter.notifyDataSetChanged(); and removing scrollview above listview i was able to get this -
Thank you guyz
Your adapter should be created with a List object (for example listResults) and in the setListView do something like:
if (listposts.size() > 0) {
nopost.setVisibility(View.GONE);
//clear old results
listResults.clear();
//load all results
listResults.addAll(listposts);
//notify the adapter about the changes
adapter.notifyDataSetChanged();
}
The point is... create an adapter over an list so... you have ONE instance of that list.
Then update the contents of that list (don't create a new instance), and tell the adapter that the collection has changed.
Try it and let mw know if it works.
In your layout you have android:visibility="gone" set for your listview. I don't see that being toggled in your code.
The answer about updating the adapter instead of creating a new instance is also correct. Initialize your adapter along with your listview and set it (using setAdapter) in the initialization phase. Then when your new data comes in (I modified the code given in the other answer as it was confusing - what's listResults?):
adapter.clear();
//load all results
adapter.addAll(listposts);
//notify the adapter about the changes
adapter.notifyDataSetChanged();

I converted a fragment to a dialog and now text colors have changed

This is my first app. I had been setting a preference in an activity (with a fragment), but I want to move the fragment to a DialogPreference. It migrated okay, except my text colors have gone weird. See picture. The text should just be black, not white and gray. Any idea what I got wrong?
(Sorry, I know this is pretty sloppy code)
How it looks now:
My xml...
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/relLay_dialog_semester_root"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin" >
<TextView
android:id="#+id/select_semester_prompt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/select_semester_prompt" />
<LinearLayout
android:id="#+id/linLayGradeSum"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/select_semester_prompt"
android:layout_centerHorizontal="true"
android:layout_marginTop="20dp" >
<Spinner
android:id="#+id/semester_spinner"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="3"
android:hint="#string/hint_editSemester" />
<Spinner
android:id="#+id/year_spinner"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="4" />
</LinearLayout>
<TextView
android:id="#+id/active_semesters_str"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/linLayGradeSum"
android:layout_below="#+id/linLayGradeSum"
android:text="#string/active_semester_str"
android:textAppearance="?android:attr/textAppearanceMedium" />
<LinearLayout
android:id="#+id/active_semesters_list"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/active_semesters_str"
android:layout_below="#+id/active_semesters_str"
android:layout_marginTop="10dp"
android:orientation="vertical" >
</LinearLayout>
</RelativeLayout>
My extended DialogPreference class
public class SemesterDialogPreference extends DialogPreference {
SharedPreferences settings;
public static int YEAR_DEFAULT_VALUE = Activity_AddCourse.thisYear - Activity_AddCourse.baseYear;
public static int SEASON_DEFAULT_VALUE = Semester.getDefaultSemester().getSeasonInt();
public static int SEMESTER_DEFAULT_ID = 1;
String semester_id_key;
DBAdapter db;
// this is where I do everything view-related
#Override
public void onBindDialogView(View view){
settings = getSharedPreferences();
int curSemesterId = settings.getInt(semester_id_key, 1);
db = new DBAdapter(this.getContext().getApplicationContext());
db.open();
Semester curSemester = db.getSemester(curSemesterId);
db.close();
ArrayList<String> years = new ArrayList<String>();
for (int i = Activity_AddCourse.baseYear; i <= Activity_AddCourse.maxYear; i++)
{
years.add(Integer.toString(i));
}
ArrayAdapter<String> adapter_year = new ArrayAdapter<String>(this.getContext().getApplicationContext(),
android.R.layout.simple_spinner_item, years);
Spinner spinYear = (Spinner)view.findViewById(R.id.year_spinner);
adapter_year.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinYear.setAdapter(adapter_year);
spinYear.setSelection(curSemester.getYear() - Activity_AddCourse.baseYear);
Spinner spinner = (Spinner) view.findViewById(R.id.semester_spinner);
ArrayAdapter<CharSequence> adapter_spinner = ArrayAdapter.createFromResource(this.getContext().getApplicationContext(),
R.array.semester_spinner, android.R.layout.simple_spinner_item);
adapter_spinner.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter_spinner);
spinner.setSelection(Semester.seasonStringToInt(curSemester.getSeason()));
db = new DBAdapter(this.getContext().getApplicationContext());
db.open();
Semester[] s = db.getAllSemesters();
db.close();
String activeSem;
LinearLayout semesterList = (LinearLayout) view.findViewById(R.id.active_semesters_list);
if(s != null){
for(int i = 0; i < s.length; i++){
activeSem = s[i].getSemesterString();
TextView tv = (TextView) new TextView(this.getContext().getApplicationContext());
tv.setText(activeSem);
semesterList.addView(tv);
System.out.println(s[i].getSemesterString());
}
}
super.onBindDialogView(view);
}
public SemesterDialogPreference(Context context, AttributeSet attrs) {
super(context, attrs);
setDialogLayoutResource(R.layout.dialog_set_semester);
}
#Override
protected void onDialogClosed(boolean positiveResult) {
super.onDialogClosed(positiveResult);
persistBoolean(positiveResult);
}
}
UPDATE:
The DialogPreference pops up from my settings activity, as shown below.
public class SettingsActivity extends PreferenceActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.settings);
}
}
Also, I was able to get the spinner text to black by making my own xml layouts for them, just as Huy Tran suggested. However, I had to make one for each the spinner_item and the spinner_dropdown_item. See below.
ArrayAdapter<String> adapter_year = new ArrayAdapter<String>(this.getContext().getApplicationContext(),
R.layout.my_spinner_item, years);
Spinner spinYear = (Spinner)view.findViewById(R.id.year_spinner);
adapter_year.setDropDownViewResource(R.layout.my_spinner_dropdown_item);
Why did I have to do this? I don't know. Also, dropdown items are each now about 50% taller. I copied exactly from source code into my own xml and it still renders differently. Very weird.
Create a layout like below and use that layout in setDropDownViewResource instead of android.R.layout.simple_spinner_dropdown_item.
Create my_spinner_dropdown_item.xml in res/layout:
EDITED:
<?xml version="1.0" encoding="utf-8"?>
<CheckedTextView xmlns:android="http://schemas.android.com/apk/res/android"
style="?android:attr/spinnerDropDownItemStyle"
android:singleLine="true"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ellipsize="marquee"
android:textColor="#color/black"
/>
my_spinner_item
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#android:id/text1"
style="?android:attr/spinnerItemStyle"
android:singleLine="true"
android:textColor="#android:color/transparent"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ellipsize="marquee" />
Try using margin to change the size of each item.
And then in your SemesterDialogPreference:
setDropDownViewResource(R.layout.my_spinner_dropdown_item);

Categories

Resources