Async Task to download image not displaying on fragment - image

in my app I'm using this template and to download images I use ImageDownloader, which worked fine on another apps. When I come back to the tab/fragment where the image should be, I can see for a moment the download dialog and it disappears.
LogCat:
11-13 20:23:11.856: I/Async-Example(775): onPreExecute Called
11-13 20:23:11.956: D/dalvikvm(775): GC_CONCURRENT freed 80K, 2% free 11133K/11271K, paused 28ms+31ms, total 130ms
11-13 20:23:12.126: D/libEGL(775): loaded /system/lib/egl/libEGL_emulation.so
11-13 20:23:12.146: D/(775): HostConnection::get() New Host Connection established 0x2a0f48e8, tid 775
11-13 20:23:12.156: D/libEGL(775): loaded /system/lib/egl/libGLESv1_CM_emulation.so
11-13 20:23:12.165: D/libEGL(775): loaded /system/lib/egl/libGLESv2_emulation.so
11-13 20:23:12.186: E/ImageDownloader(775): Something went wrong while retrieving bitmap.
Manifest:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.lupradoa.lakari"
android:versionCode="1"
android:versionName="1.0">
<permission
android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-sdk android:minSdkVersion="8" android:targetSdkVersion="19" />
<application android:label="#string/app_name"
android:icon="#drawable/ic_launcher"
android:theme="#style/AppTheme"
android:allowBackup ="false">
<activity android:name="com.lupradoa.lakari.base.AppMainTabActivity" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
I think the guilty here is "onPreExecute()"
FragmentA.java:
package com.lupradoa.lakari.fragmenttabstudy.tabA;
import java.io.InputStream;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import android.app.ProgressDialog;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import com.lupradoa.lakari.R;
import com.lupradoa.lakari.base.AppConstants;
import com.lupradoa.lakari.base.BaseFragment;
public class AppTabAFirstFragment extends BaseFragment {
private Button mGotoButton;
private ImageView downloadedImg;
private ProgressDialog simpleWaitDialog;
private String downloadUrl = "http://www.9ori.com/store/media/images/8ab579a656.jpg";
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.app_tab_a_first_screen, container, false);
mGotoButton = (Button) view.findViewById(R.id.id_next_tab_a_button);
mGotoButton.setOnClickListener(listener);
//image downloaded
downloadedImg =(ImageView) view.findViewById(R.id.imageView);
new ImageDownloader().execute(downloadUrl);
return view;
}
private OnClickListener listener = new View.OnClickListener(){
#Override
public void onClick(View v){
/* Go to next fragment in navigation stack*/
mActivity.pushFragments(AppConstants.TAB_A, new AppTabASecondFragment(),true,true);
}
};
private class ImageDownloader extends AsyncTask<String, Void, Bitmap>{
#Override
protected Bitmap doInBackground (String... param){
return downloadBitmap(param[0]);
}
#Override
protected void onPreExecute(){
Log.i("Async-Example", "onPreExecute Called");
**//NOT SURE IF THE CONTEXT IS SET PROPERLY**
simpleWaitDialog = ProgressDialog.show(getActivity(), "Wait", "Downloading Image");
}
#Override
protected void onPostExecute(Bitmap result) {
Log.i("Async-Example", "onPostExecute Called");
downloadedImg.setImageBitmap(result);
simpleWaitDialog.dismiss();
}
private Bitmap downloadBitmap(String url){
final DefaultHttpClient client = new DefaultHttpClient();
final HttpGet getRequest = new HttpGet(url);
try{
HttpResponse response = client.execute(getRequest);
final int statusCode = response.getStatusLine().getStatusCode();
if(statusCode != HttpStatus.SC_OK){
Log.w("ImageDownloader", "Error" + statusCode + "while retrieving bitmap from "+ url);
return null;
}
final HttpEntity entity = response.getEntity();
if(entity != null){
InputStream inputStream = null;
try{
inputStream = entity.getContent();
final Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
return bitmap;
}finally {
if(inputStream !=null){
inputStream.close();
}
entity.consumeContent();
}
}
}catch (Exception e){
getRequest.abort();
Log.e("ImageDownloader", "Something went wrong while retrieving bitmap.");
}
return null;
}
}
}
Layout:
<?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:orientation="vertical" android:background="#aa5500"
android:gravity="center">
<ImageView
android:id="#+id/imageView"
android:layout_width="320dp"
android:layout_height="0dp"
android:layout_weight="1"
android:contentDescription="#string/description"
android:layout_marginBottom="50dp"
android:layout_marginTop="50dp"/>
<Button
android:id="#+id/id_next_tab_a_button"
android:layout_width="120dp"
android:layout_height="wrap_content"
android:padding="10dip"
android:text="#string/como_llegar" />
</LinearLayout>
How can this be fixed?

I don't think the problem is in onPreExecute() but that maybe the downloaded images are too big to be managed.
I recommend you to use UniversalImageLoader to load images, it's a fully featured library used in many apps the do that work properly. Maybe it also could help you.

Related

How to invoke another class when message received in android

This is my sms receiver
package com.example.smsTest;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsMessage;
import android.widget.Toast;
public class SmsReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent)
{
//---get the SMS message passed in---
Bundle bundle = intent.getExtras();
SmsMessage[] msgs = null;
String str = "";
if (bundle != null)
{
//---retrieve the SMS message received---
Object[] pdus = (Object[]) bundle.get("pdus");
msgs = new SmsMessage[pdus.length];
for (int i=0; i<msgs.length; i++){
msgs[i] = SmsMessage.createFromPdu((byte[])pdus[i]);
str += "SMS from " + msgs[i].getOriginatingAddress();
str += " :";
str += msgs[i].getMessageBody().toString();
str += "\n";
}
Toast.makeText(context, str, Toast.LENGTH_SHORT).show();
Intent mainActivityIntent = new Intent(context, SMSTest.class);
mainActivityIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(mainActivityIntent);
//---send a broadcast intent to update the SMS received in the activity---
Intent broadcastIntent = new Intent();
broadcastIntent.setAction("SMS_RECEIVED_ACTION");
broadcastIntent.putExtra("sms", str);
context.sendBroadcast(broadcastIntent);
}
}
}
This is manifest file
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.smsTest"
android:versionCode="1"
android:versionName="1.0">
<uses-sdk android:minSdkVersion="4"
android:targetSdkVersion="8"
android:maxSdkVersion="8" />
<application android:icon="#drawable/icon" android:label="#string/app_name">
<activity android:name=".SMSTest"
android:label="#string/app_name"
android:launchMode="singleTask">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver android:name=".SmsReceiver">
<intent-filter android:priority="99999">
<action android:name="android.provider.telephony.SMS_RECIEVED"></action>
</intent-filter>
</receiver>
</application>
<uses-permission android:name="android.permission.SEND_SMS">
</uses-permission>
<uses-permission android:name="android.permission.RECEIVE_SMS">
</uses-permission>
enter code here
</manifest>
I want to call the another class named as SMSText.class from above SmsReceiver class. I wrote the above but its not working.
In SmsReceiver do the following:
Intent mainActivityIntent = new Intent(context, SMSTest.class);
mainActivityIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
mainActivityIntent.putExtra("sms", str);
context.startActivity(mainActivityIntent);
Then, in the Activity's onCreate() method:
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
TextView SMSes = (TextView) findViewById(R.id.textView1);
String sms = getIntent().getStringExtra("sms");
SMSes.setText(sms);
}
You've misspelled "RECEIVED" in the <intent-filter> in your manifest, so your BroadcastReceiver isn't firing. It should be:
<action android:name="android.provider.Telephony.SMS_RECEIVED" />
String activity= "android.provider.telephony.SMS_RECIEVED";
Intent mainActivityIntent = new Intent(activity);
startActivity(mainActivityIntent);

Error in else value on android

i want to change visibility when special status
so i do else like that
else {
ImageView image_A_wrong = (ImageView)findViewById(R.id.imageView1);
image_A_wrong.setVisibility(View.GONE);
}
But appear error on eclipse.
Do you know why ?
my imageview
<ImageView
android:id="#+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/quo100px"
android:visibility="gone" />
Tks advance all
Here my complete file
package com.example.androidhive;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.apache.http.NameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
public class quoPAPIERCORD extends ListActivity {
// Progress Dialog
private ProgressDialog pDialog;
// Creating JSON Parser object
JSONParser jParser = new JSONParser();
ArrayList<HashMap<String, String>> productsList;
// url to get all products list
private static String url_all_products_quo = >"http://192.168.1.81/php/android/get_all_quotidiens.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_PRODUCTS = "products";
private static final String TAG_PID = "pid";
private static final String TAG_NAME = "name";
private static final String TAG_PRICE = "price";
private static String TAG_CU = "cu";
// products JSONArray
JSONArray products = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.quotidiens);
// Hashmap for ListView
productsList = new ArrayList<HashMap<String, String>>();
// Loading products in Background Thread
new LoadAllProducts().execute();
// Get listview
ListView lv = getListView();
// on seleting single product
// launching Edit Product Screen
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String pid = ((TextView) >view.findViewById(R.id.pid)).getText()
.toString();
// Starting new intent
Intent in = new Intent(getApplicationContext(),
EditProductActivity.class);
// sending pid to next activity
in.putExtra(TAG_PID, pid);
// starting new activity and expecting some response back
startActivityForResult(in, 100);
}
});
}
// Response from Edit Product Activity
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// if result code 100
if (resultCode == 100) {
// if result code 100 is received
// means user edited/deleted product
// reload this screen again
Intent intent = getIntent();
finish();
startActivity(intent);
}
}
/**
* Background Async Task to Load all product by making HTTP Request
* */
class LoadAllProducts extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(quoPAPIERCORD.this);
pDialog.setMessage("Loading products. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting All products from url
* */
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url_all_products_quo, >"GET", params);
// Check your log cat for JSON reponse
Log.d("All Products: ", json.toString());
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// products found
// Getting Array of Products
products = json.getJSONArray(TAG_PRODUCTS);
// looping through All Products
for (int i = 0; i < products.length(); i++) {
JSONObject c = products.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_PID);
String name = c.getString(TAG_NAME);
String price = c.getString(TAG_PRICE);
String cu = c.getString(TAG_CU);
/////////////
if (cu.equals("1")) {
cu = "oui";
} else {
ImageView image_A_wrong = (ImageView) >findViewById(R.id.imageView1);
image_A_wrong.setVisibility(View.GONE);
}
// creating new HashMap
HashMap<String, String> map = new >HashMap<String, String>();
// adding each child node to HashMap key => >value
map.put(TAG_PID, id);
map.put(TAG_NAME, name);
map.put(TAG_PRICE, price);
map.put(TAG_CU, cu);
// adding HashList to ArrayList
productsList.add(map);
}
} else {
// no products found
// Launch Add New product Activity
Intent i = new Intent(getApplicationContext(),
NewProductActivity.class);
// Closing all previous activities
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all products
pDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
quoPAPIERCORD.this, productsList,
R.layout.list_item, new String[] { >TAG_PID,
TAG_NAME, >TAG_PRICE, TAG_CU},
new int[] { R.id.pid, R.id.name, >R.id.price, R.id.cu });
// updating listview
setListAdapter(adapter);
}
});
}
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:padding="5px"
android:stretchColumns="1">
<!-- Product id (pid) - will be HIDDEN - used to pass to other activity -->
<TextView
android:id="#+id/pid"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:visibility="gone" />
<!-- Name Label -->
<TextView
android:id="#+id/name"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingRight="10px"
android:textSize="17sp"
android:layout_marginRight="10px"
android:layout_weight="0.2"
android:textColor="#fff"
android:gravity="left" />
<!-- price Label -->
<TextView
android:id="#+id/price"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingRight="5px"
android:textSize="17sp"
android:layout_marginRight="5px"
android:layout_weight="0.2"
android:textColor="#C00000"
android:gravity="left"
android:textStyle="bold" />
<ImageView
android:id="#+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/quo100px"/>
<TextView
android:id="#+id/cu"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingRight="5px"
android:textSize="17sp"
android:layout_marginRight="5px"
android:layout_weight="0.2"
android:textColor="#C00000"
android:gravity="left"
android:textStyle="bold" />
<TextView
android:id="#+id/mc"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingRight="5px"
android:textSize="17sp"
android:layout_marginRight="5px"
android:layout_weight="0.2"
android:textColor="#C00000"
android:gravity="left"
android:textStyle="bold" />
<TextView
android:id="#+id/tel"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingRight="5px"
android:textSize="17sp"
android:layout_marginRight="5px"
android:layout_weight="0.2"
android:textColor="#C00000"
android:gravity="left"
android:textStyle="bold" />
</LinearLayout>
Seeing your error here, You can't access UI (Textview, Edittext, ImageView, etc) inside DoInBackgroud. Do it on either OnPostExecute or OnProgressUpdate method
Edit: Change this
if (cu.equals("1"))
{
cu = "oui";
}
else
{
ImageView image_A_wrong = (ImageView) findViewById(R.id.imageView1);
image_A_wrong.setVisibility(View.GONE);
}
to
if (cu.equals("1"))
{
cu = "oui";
}
else
{
cu = "pas";
}
then add this to your OnPostExecute()
Edit 2: Seeing your code I've somewhat narrowed your error. the above code must be like
Declare the string cu globally and then try the follwing
ImageView image_A_wrong = (ImageView) findViewById(R.id.imageView1);
if(cu.equals("pas"))
{
image_A_wrong.setVisibility(View.GONE);
}
else
{
image_A_wrong.setVisibility(View.GONE);
}

Unable to insert values into tableview - JavaFx

I am new to JavaFx and I am trying to create a tableview and fxml is created using scene builder. If I run the program, the table is not getting the values. I found that this question is somehow matching with my requirement (javaFX 2.2 - Not able to populate table from Controller), but my code is matching with that too. But still I am not able to get the values in the table.
I have referenced the following video : http://www.youtube.com/watch?v=HiZ-glk9_LE
My code is as follows,
MainView.java
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package controller;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.layout.AnchorPane;
import javafx.stage.Stage;
public class MainView extends Application {
public static void main(String[] args) {
launch(args);
}
#Override
public void start(Stage primaryStage) throws Exception {
try {
AnchorPane page = FXMLLoader.load(MainView.class.getResource("MainView.fxml"));
Scene scene = new Scene(page);
primaryStage.setScene(scene);
primaryStage.setTitle("Sample Window");
primaryStage.setResizable(false);
primaryStage.show();
} catch (Exception e) {
}
}
}
MainView.fxml
<?xml version="1.0" encoding="UTF-8"?>
<?import java.lang.*?>
<?import java.util.*?>
<?import javafx.scene.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
<AnchorPane id="AnchorPane" prefHeight="400.0" prefWidth="600.0" xmlns:fx="http://javafx.com/fxml" fx:controller="controller.MainViewController">
<children>
<SplitPane dividerPositions="0.535175879396985" focusTraversable="true" orientation="VERTICAL" prefHeight="400.0" prefWidth="600.0" AnchorPane.bottomAnchor="0.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0" AnchorPane.topAnchor="0.0">
<items>
<AnchorPane minHeight="0.0" minWidth="0.0" prefHeight="100.0" prefWidth="160.0">
<children>
<TableView fx:id="tableID" prefHeight="210.0" prefWidth="598.0" tableMenuButtonVisible="true" AnchorPane.bottomAnchor="0.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0" AnchorPane.topAnchor="0.0">
<columns>
<TableColumn minWidth="20.0" prefWidth="40.0" text="ID" fx:id="tID" />
<TableColumn prefWidth="100.0" text="Date" fx:id="tDate" />
<TableColumn prefWidth="200.0" text="Name" fx:id="tName" />
<TableColumn prefWidth="75.0" text="Price" fx:id="tPrice" />
</columns>
</TableView>
</children>
</AnchorPane>
<AnchorPane minHeight="0.0" minWidth="0.0" prefHeight="100.0" prefWidth="160.0" />
</items>
</SplitPane>
</children>
</AnchorPane>
MainViewController.java
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package controller;
import java.net.URL;
import java.util.ResourceBundle;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.PropertyValueFactory;
import model.Table;
/**
* FXML Controller class
*
*/
public class MainViewController implements Initializable {
/**
* Initializes the controller class.
*/
#FXML
TableView<Table> tableID;
#FXML
TableColumn<Table, Integer> tID;
#FXML
TableColumn<Table, String> tName;
#FXML
TableColumn<Table, String> tDate;
#FXML
TableColumn<Table, String> tPrice;
int iNumber = 1;
ObservableList<Table> data =
FXCollections.observableArrayList(
new Table(iNumber++, "Dinesh", "12/02/2013", "20"),
new Table(iNumber++, "Vignesh", "2/02/2013", "40"),
new Table(iNumber++, "Satheesh", "1/02/2013", "100"),
new Table(iNumber++, "Dinesh", "12/02/2013", "16"));
#Override
public void initialize(URL url, ResourceBundle rb) {
// System.out.println("called");
tID.setCellValueFactory(new PropertyValueFactory<Table, Integer>("rID"));
tName.setCellValueFactory(new PropertyValueFactory<Table, String>("rName"));
tDate.setCellValueFactory(new PropertyValueFactory<Table, String>("rDate"));
tPrice.setCellValueFactory(new PropertyValueFactory<Table, String>("rPrice"));
tableID.setItems(data);
}
}
Table.java
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package model;
import javafx.beans.property.SimpleIntegerProperty;
import javafx.beans.property.SimpleStringProperty;
public class Table {
SimpleIntegerProperty rID;
SimpleStringProperty rName;
SimpleStringProperty rDate;
SimpleStringProperty rPrice;
public Table(int rID, String rName, String rDate, String rPrice) {
this.rID = new SimpleIntegerProperty(rID);
this.rName = new SimpleStringProperty(rName);
this.rDate = new SimpleStringProperty(rDate);
this.rPrice = new SimpleStringProperty(rPrice);
System.out.println(rID);
System.out.println(rName);
System.out.println(rDate);
System.out.println(rPrice);
}
public Integer getrID() {
return rID.get();
}
public void setrID(Integer v) {
this.rID.set(v);
}
public String getrDate() {
return rDate.get();
}
public void setrDate(String d) {
this.rDate.set(d);
}
public String getrName() {
return rName.get();
}
public void setrName(String n) {
this.rDate.set(n);
}
public String getrPrice() {
return rPrice.get();
}
public void setrPrice(String p) {
this.rPrice.set(p);
}
}
Thanks in advance.
In a Table.java change all getters and setters names,
change getr* to getR*
change setr* to setR*
Thanks to #Uluk Biy. Whatever he mentioned, that needs to be changed and I found that I missed the <cellValueFactory> and <PropertyValueFactory> tags under the <TableColumn> tag for each columns in the FXML file which is as follows,
<TableColumn minWidth="20.0" prefWidth="40.0" text="ID" fx:id="tID" >
<cellValueFactory>
<PropertyValueFactory property="tID" />
</cellValueFactory>
</TableColumn>
Similar to this, all columns need to be updated like this.
After this change, the code is working fine. I am able to add the values into the row. :)

Android: implementing Checkbox List with ListFragment and ArrayAdapter

I am converting a working application to Fragments. My checkbox list is not displaying the labels, and I am guessing, the id's. I am new to Android/Java and this is my first post to Stackoverflow, so apologies if the question is simple or not following correct protocol.
My ListFragment is as follows:
import java.util.ArrayList;
import java.util.List;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.TextView;
public class DistributionTransFragment extends ListFragment {
protected TextView subheader;
protected Context mContext;
protected DatabaseHandler db;
protected String user_id;
protected String user;
protected String recipients;
protected int number;
protected LayoutInflater inflater;
protected View v;
DistributionArrayAdapter dataAdapter = null;
public DistributionTransFragment(){
super();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
v = inflater.inflate(R.layout.distribution_fragment, container, false);
mContext = getActivity().getApplicationContext();
db = new DatabaseHandler(mContext);
subheader = (TextView)v.findViewById(R.id.textView2);
subheader.setText("Spent On?");
displayListView();
checkButtonClick();
return v;
}
private void displayListView() {
ArrayList<Participant> distributionList = new ArrayList<Participant>();
Participant participant;
List<User> users = db.getAllUsers();
for (User u : users) {
user_id = String.valueOf(u.getID());
user = u.getUser();
participant = new Participant(user_id, user, false);
distributionList.add(participant);
}
//create an ArrayAdaptar from the String Array
dataAdapter = new DistributionArrayAdapter(mContext, R.layout.distributionlist, distributionList);
setListAdapter(dataAdapter);
}
private class DistributionArrayAdapter extends ArrayAdapter<Participant> {
private ArrayList<Participant> distributionList;
public DistributionArrayAdapter(Context context, int textViewResourceId, ArrayList<Participant> distributionList) {
super(context, textViewResourceId, distributionList);
this.distributionList = new ArrayList<Participant>();
this.distributionList.addAll(distributionList);
}
private class ViewHolder {
TextView code;
CheckBox name;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
Log.v("ConvertView", String.valueOf(position));
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.distributionlist, null);
holder = new ViewHolder();
holder.code = (TextView) convertView.findViewById(R.id.code);
holder.name = (CheckBox) convertView.findViewById(R.id.checkBox1);
convertView.setTag(holder);
Log.d("HOLDER CODE", (holder.code).toString());
holder.name.setOnClickListener( new View.OnClickListener() {
public void onClick(View v) {
CheckBox cb = (CheckBox) v ;
Participant participant = (Participant) cb.getTag();
participant.setSelected(cb.isChecked());
}
});
} else {
holder = (ViewHolder) convertView.getTag();
}
Participant participant = distributionList.get(position);
holder.name.setText(participant.getName());
holder.name.setChecked(participant.isSelected());
holder.name.setTag(participant);
return convertView;
}
}
private void checkButtonClick() {
Button myButton = (Button) v.findViewById(R.id.button1);
myButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
final ArrayList<Participant> distributionList = dataAdapter.distributionList;
// Do Stuff
AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
builder.setMessage(tempTransaction);
builder.setCancelable(false);
builder.setPositiveButton("Commit", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// Do More Stuff
Intent intent = new Intent(mContext, Home.class);
startActivity(intent);
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// Do Other Stuff
Intent intent = new Intent(mContext, Home.class);
startActivity(intent);
}
});
AlertDialog alert = builder.create();
alert.show();
}
});
}
}
My XML for the list is as follows:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:background="#color/white"
android:padding="15dip" >
<CheckBox
android:id="#+id/checkBox1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:focusable="false"
android:focusableInTouchMode="false" />
<TextView
android:id="#+id/code"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#+id/checkBox1"
android:layout_alignBottom="#+id/checkBox1"
android:layout_toRightOf="#+id/checkBox1"
android:textSize="15sp" />
</RelativeLayout>
My XML for the fragment is as follows:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/grey">
<RelativeLayout
android:id="#+id/subheader"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="#id/secondheader"
android:orientation="vertical" >
<TextView
android:id="#+id/textView2"
style="#style/subheader" />
<TextView
android:id="#+id/textView3"
style="#style/info" />
</RelativeLayout>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="#id/subheader"
android:layout_above="#+id/footer"
android:orientation="vertical" >
<ListView
android:id="#android:id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
</LinearLayout>
<LinearLayout
android:id="#id/footer"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:background="#color/grey"
android:layout_alignParentBottom="true" >
<Button
android:id="#+id/button1"
style="#style/button.form"
android:text="#string/moneyspent" />
</LinearLayout>
</RelativeLayout>
Any help would be greatly appreciated.
I nutted it out, so thought I would post my answer in case others have the same problem. It was my context. It should have been:
mContext = getActivity();

updateItem's second param have never be false in javafx2

I use javafx2 control TableView to dispay records in the database(I have 20 records now).
And when display the record,I want to add button in each row.
so I search lots of article use google,and write some code below.
the key code is:
protected void updateItem(Long item, boolean empty) {
super.updateItem(item, empty);
if(empty) {
setText(null);
setGraphic(null);
} else {
final Button button = new Button("modifty");
setGraphic(button);
setContentDisplay(ContentDisplay.GRAPHIC_ONLY);
}
}
I debug this code,the param "empty" would never be "false",
so the button would never be display in the table view,
can anyone help me? thanks
below is the complete code(java and fxml):
java:
package com.turbooo.restaurant.interfaces.javafx;
import java.io.IOException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.ResourceBundle;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.ContentDisplay;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.stage.Modality;
import javafx.stage.Stage;
import javafx.util.Callback;
import com.turbooo.restaurant.domain.Customer;
import com.turbooo.restaurant.domain.CustomerRepository;
import com.turbooo.restaurant.interfaces.facade.dto.CustomerDto;
import com.turbooo.restaurant.interfaces.facade.dto.assembler.CustomerDtoAssembler;
import com.turbooo.restaurant.util.ContextHolder;
import com.turbooo.restaurant.util.UTF8Control;
public class CustomerController implements Initializable {
#FXML
private TableView<CustomerDto> customerTableView;
#Override
public void initialize(URL arg0, ResourceBundle arg1) {
TableColumn<CustomerDto, Long> idCol = new TableColumn<CustomerDto, Long>("id");
idCol.setCellValueFactory(
new PropertyValueFactory<CustomerDto,Long>("id")
);
TableColumn<CustomerDto, String> nameCol = new TableColumn<CustomerDto, String>("name");
nameCol.setMinWidth(100);
nameCol.setCellValueFactory(
new PropertyValueFactory<CustomerDto,String>("name")
);
TableColumn<CustomerDto, String> birthdayCol = new TableColumn<CustomerDto, String>("birthday");
birthdayCol.setCellValueFactory(
new Callback<TableColumn.CellDataFeatures<CustomerDto, String>, ObservableValue<String>>() {
#Override
public ObservableValue<String> call(TableColumn.CellDataFeatures<CustomerDto, String> customer) {
if (customer.getValue() != null) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
return new SimpleStringProperty(sdf.format(customer.getValue().getBirthday()));
} else {
return new SimpleStringProperty("");
}
}
});
TableColumn<CustomerDto, Long> actionCol = new TableColumn<CustomerDto, Long>("action");
actionCol.setCellFactory(
new Callback<TableColumn<CustomerDto,Long>, TableCell<CustomerDto,Long>>() {
#Override
public TableCell<CustomerDto, Long> call(TableColumn<CustomerDto, Long> arg0) {
final TableCell<CustomerDto, Long> cell = new TableCell<CustomerDto, Long>() {
#Override
protected void updateItem(Long item, boolean empty) {
super.updateItem(item, empty);
if(empty) {
setText(null);
setGraphic(null);
} else {
final Button button = new Button("modifty");
setGraphic(button);
setContentDisplay(ContentDisplay.GRAPHIC_ONLY);
}
}
};
return cell;
}
});
//TODO add button column
customerTableView.getColumns().addAll(idCol, nameCol, birthdayCol, actionCol);
loadData();
}
public void loadData() {
CustomerRepository cusRepo = (CustomerRepository)ContextHolder.getContext().getBean("customerRepository");
List<Customer> customers = cusRepo.findAll();
CustomerDtoAssembler customerDTOAssembler = new CustomerDtoAssembler();
List<CustomerDto> customerDtos = customerDTOAssembler.toDTOList(customers);
ObservableList<CustomerDto> data = FXCollections.observableArrayList(customerDtos);
customerTableView.setItems(data);
}
public void showNewDialog(ActionEvent event) {
ResourceBundle resourceBundle = ResourceBundle.getBundle(
"com/turbooo/restaurant/interfaces/javafx/customer_holder",
new UTF8Control());
Parent container = null;
try {
container = FXMLLoader.load(
getClass().getResource("customer_holder.fxml"),
resourceBundle);
} catch (IOException e) {
e.printStackTrace();
}
container.setUserData(this); //pass the controller, so can access LoadData function in other place later
Scene scene = new Scene(container, 400, 300);
Stage stage = new Stage();
stage.setScene(scene);
stage.initModality(Modality.APPLICATION_MODAL);
stage.show();
}
}
fxml:
<?xml version="1.0" encoding="UTF-8"?>
<?import java.lang.*?>
<?import java.util.*?>
<?import javafx.scene.control.*?>
<?import javafx.scene.layout.*?>
<?import javafx.scene.paint.*?>
<BorderPane prefHeight="345.0" prefWidth="350.0" xmlns:fx="http://javafx.com/fxml" fx:controller="com.turbooo.restaurant.interfaces.javafx.CustomerController">
<center>
<TableView fx:id="customerTableView" prefHeight="200.0" prefWidth="200.0" />
</center>
<top>
<HBox alignment="CENTER_LEFT" prefHeight="42.0" prefWidth="350.0">
<children>
<Button text="new" onAction="#showNewDialog"/>
<Separator prefHeight="25.0" prefWidth="13.0" visible="false" />
<Button text="modify" />
<Separator prefHeight="25.0" prefWidth="15.0" visible="false" />
<Button text="delete" />
</children>
</HBox>
</top>
</BorderPane>
You haven't set a cellValueFactory for your action column, so it is always empty.
A simple way to do this is just to set the cell value to the id of the record.
actionCol.setCellValueFactory(
new PropertyValueFactory<CustomerDto,Long>("id")
);
Additionally, I created a simple example for creating a table with Add buttons in it, which you could reference if needed.

Resources