List Adapter receives the objects but it does not display them in the List View - arrays

So, here is the case, in the onPostExecute method I have used a ListView and I have adapted a list adapter in it in order to display the objects (events) in a list view. The problem is that the adapter recognizes the objects but it does not display them in the ListView. I have looked of how to populate an Array of Hashmaps with a List adapter and I am prettu sure that I have done it correctly in my code. I think that the problem might be in the xml file. Any ideas that can guide me to the right direction?
This is my xml file:
<?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">
<ListView
android:id="#android:id/list"
android:layout_width="match_parent"
android:layout_height="match_parent">
</ListView>
<TextView
android:id="#+id/id"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingBottom="2dip"
android:paddingTop="6dip"
android:textSize="16sp"/>
<TextView
android:id="#+id/title"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingBottom="2dip" />
<TextView
android:id="#+id/date"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="start"/>
<TextView
android:id="#+id/time"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="start" />
<TextView
android:id="#+id/time_end"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="start" />
</LinearLayout>
And the .java file:
public class EventsJSONActivity extends ListActivity {
private static String url = "http://mob.students.acg.edu/json3.php";
public static final String TAG_EVENT_INFO = "eventsinfo";
public static final String TAG_ID = "id";
public static final String TAG_TITLE = "title";
public static final String TAG_DATE = "date";
public static final String TAG_TIME = "time";
public static final String TAG_TIME_END = "time_end";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_events_json);
new GetEvents().execute();
}
class GetEvents extends AsyncTask<Void,Void,Void> {
ArrayList<HashMap<String,String>> eventList;
ProgressDialog proDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
proDialog = new ProgressDialog(EventsJSONActivity.this);
Log.d("prodialog: ","Setting Message.");
proDialog.setMessage("Please wait...");
Log.d("prodialog: ","Setting cancellable.");
proDialog.setCancelable(false);
Log.d("prodialog: ","Showing...");
proDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
WebRequest webreq = new WebRequest();
String url = "http://mob.students.acg.edu/json3.php";
String jsonStr = webreq.makeWebServiceCall(url,WebRequest.POSTRequest);
Log.d("Response: ", "> " + jsonStr);
eventList = ParseJSON(jsonStr);
Log.d("eventList info: " , eventList.toString());
return null;
}
//!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
#Override
protected void onPostExecute(Void requestresult) {
super.onPostExecute(requestresult);
if (proDialog.isShowing()) {
proDialog.dismiss();
Log.d("prodialog: ","dismissing dialog.");
}
Log.d("Listadapter: ", "eventList: " + eventList.toString());
ListAdapter adapter = new SimpleAdapter(
EventsJSONActivity.this,eventList,
android.R.layout.simple_list_item_1,
new String[] {TAG_ID, TAG_TITLE, TAG_DATE, TAG_TIME, TAG_TIME_END},
new int[] {R.id.id,R.id.title,R.id.date,R.id.time,R.id.time_end});
Log.d("Listadapter: ","data fed");
ListView lv = (ListView)findViewById(android.R.id.list);
lv.setAdapter(adapter);
Log.d("Listadapter: ",adapter.getCount() + " items set");
}//!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
private ArrayList<HashMap<String,String>> ParseJSON(String json) {
if (json != null) {
try {
ArrayList<HashMap<String,String>> eventList = new ArrayList<>();
JSONObject jsonObj = new JSONObject(json);
JSONArray events = jsonObj.getJSONArray(TAG_EVENT_INFO);
for (int i = 0; i < events.length(); i++) {
JSONObject j = events.getJSONObject(i);
String id = j.getString(TAG_ID);
String title = j.getString(TAG_TITLE);
String date = j.getString(TAG_DATE);
String time = j.getString(TAG_TIME);
String time_end = j.getString(TAG_TIME_END);
HashMap<String,String> event = new HashMap<String,String>();
event.put(TAG_ID,id);
event.put(TAG_TITLE,title);
event.put(TAG_DATE,date);
event.put(TAG_TIME,time);
event.put(TAG_TIME_END,time_end);
/*event.put(TAG_ID,"id");
event.put(TAG_TITLE,"title");
event.put(TAG_DATE,"date");
event.put(TAG_TIME,"time");
event.put(TAG_TIME_END,"time_end");*/
eventList.add(event);
}
Log.d("EventList > ", eventList.toString());
return eventList;
} catch (JSONException e) {
e.printStackTrace();
return null;
}
} else {
Log.e("ServiceHandler", "No data received from HTTP Request");
return null;
}
}
}
}

Try checking the solution that was posted here ... updating ListView from AsyncTask. The runOnUiThread runnable may be what you are missing since the code you have here looks correct. If that doesn't work, you can try creating class levels variables for the listview and/or adapter and modify them in the onPostExecute of AsyncTask.
Hope this helps!

Related

I'm trying to perform a search on my recycler adapter when onQueryTextChange gives error to make filter as static in adapter

This is my activity_course_details.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".CourseDetails">
<SearchView
android:id="#+id/search"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:iconifiedByDefault="false">
<requestFocus />
</SearchView>
<!--Recycler view for displaying
our data from Firestore-->
<androidx.recyclerview.widget.RecyclerView
android:id="#+id/idRVCourses"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="50dp" />
<!--Progress bar for showing loading screen-->
<ProgressBar
android:id="#+id/idProgressBar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true" />
</RelativeLayout>
CoursesDetails.java
public class CourseDetails extends AppCompatActivity implements
SearchView.OnQueryTextListener{
// creating variables for our recycler view,
// array list, adapter, firebase firestore
// and our progress bar.
private RecyclerView courseRV;
private ArrayList<Courses> coursesArrayList;
private CourseRVAdapter courseRVAdapter;
private FirebaseFirestore db;
ProgressBar loadingPB;
SearchView editsearch;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_course_details);
editsearch = (SearchView) findViewById(R.id.search);
editsearch.setOnQueryTextListener((SearchView.OnQueryTextListener) this);
// initializing our variables.
courseRV = findViewById(R.id.idRVCourses);
loadingPB = findViewById(R.id.idProgressBar);
// initializing our variable for firebase
// firestore and getting its instance.
db = FirebaseFirestore.getInstance();
// creating our new array list
coursesArrayList = new ArrayList<>();
courseRV.setHasFixedSize(true);
courseRV.setLayoutManager(new LinearLayoutManager(this));
// adding our array list to our recycler view adapter class.
courseRVAdapter = new CourseRVAdapter(coursesArrayList, this);
// setting adapter to our recycler view.
courseRV.setAdapter(courseRVAdapter);
// below line is use to get the data from Firebase Firestore.
// previously we were saving data on a reference of Courses
// now we will be getting the data from the same reference.
db.collection("Courses").get()
.addOnSuccessListener(new OnSuccessListener<QuerySnapshot>() {
#SuppressLint("NotifyDataSetChanged")
#Override
public void onSuccess(QuerySnapshot queryDocumentSnapshots) {
// after getting the data we are calling on success method
// and inside this method we are checking if the received
// query snapshot is empty or not.
if (!queryDocumentSnapshots.isEmpty()) {
// if the snapshot is not empty we are
// hiding our progress bar and adding
// our data in a list.
loadingPB.setVisibility(View.GONE);
List<DocumentSnapshot> list = queryDocumentSnapshots.getDocuments();
for (DocumentSnapshot d : list) {
// after getting this list we are passing
// that list to our object class.
Courses c = d.toObject(Courses.class);
// and we will pass this object class
// inside our arraylist which we have
// created for recycler view.
coursesArrayList.add(c);
}
// after adding the data to recycler view.
// we are calling recycler view notifuDataSetChanged
// method to notify that data has been changed in recycler view.
courseRVAdapter.notifyDataSetChanged();
} else {
// if the snapshot is empty we are displaying a toast message.
Toast.makeText(CourseDetails.this, "No data found in Database", Toast.LENGTH_SHORT).show();
}
}
}).addOnFailureListener(new OnFailureListener() {
#Override
public void onFailure(#NonNull Exception e) {
// if we do not get any data or any error we are displaying
// a toast message that we do not get any data
Toast.makeText(CourseDetails.this, "Fail to get the data.", Toast.LENGTH_SHORT).show();
}
});
}
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
String text = newText;
CourseRVAdapter.filter(text);
return false;
}
}
CoursesRVAdapter.java
public class CourseRVAdapter extends RecyclerView.Adapter<CourseRVAdapter.ViewHolder> {
// creating variables for our ArrayList and context
private ArrayList<Courses> coursesArrayList = null;
private Context context;
private ArrayList<Courses> arrayList;
// creating constructor for our adapter class
public CourseRVAdapter(ArrayList<Courses> coursesArrayList, Context context) {
this.coursesArrayList = coursesArrayList;
this.context = context;
this.arrayList = new ArrayList<Courses>();
this.arrayList.addAll(coursesArrayList);
}
#NonNull
#Override
public CourseRVAdapter.ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
// passing our layout file for displaying our card item
return new ViewHolder(LayoutInflater.from(context).inflate(R.layout.course_item, parent, false));
}
#Override
public void onBindViewHolder(#NonNull CourseRVAdapter.ViewHolder holder, int position) {
// setting data to our text views from our modal class.
Courses courses = coursesArrayList.get(position);
holder.courseNameTV.setText(courses.getCourseName());
holder.courseDurationTV.setText(courses.getCourseDuration());
holder.courseDescTV.setText(courses.getCourseDescription());
}
#Override
public int getItemCount() {
// returning the size of our array list.
return coursesArrayList.size();
}
class ViewHolder extends RecyclerView.ViewHolder {
// creating variables for our text views.
private final TextView courseNameTV;
private final TextView courseDurationTV;
private final TextView courseDescTV;
public ViewHolder(#NonNull View itemView) {
super(itemView);
// initializing our text views.
courseNameTV = itemView.findViewById(R.id.idTVCourseName);
courseDurationTV = itemView.findViewById(R.id.idTVCourseDuration);
courseDescTV = itemView.findViewById(R.id.idTVCourseDescription);
}
}
#Override
public long getItemId(int position) {
return position;
}
// Filter Class
public void filter(String charText) {
charText = charText.toLowerCase(Locale.getDefault());
coursesArrayList.clear();
if (charText.length() == 0) {
arrayList.addAll(coursesArrayList);
} else {
for (Courses wp : arrayList) {
if (wp.getCourseName().toLowerCase(Locale.getDefault()).contains(charText)) {
coursesArrayList.add(wp);
}
}
}
notifyDataSetChanged();
}
}
Courses.java
public class Courses {
// variables for storing our data.
private String courseName, courseDescription, courseDuration;
public Courses() {
// empty constructor
// required for Firebase.
}
// Constructor for all variables.
public Courses(String courseName, String courseDescription, String courseDuration) {
this.courseName = courseName;
this.courseDescription = courseDescription;
this.courseDuration = courseDuration;
}
// getter methods for all variables.
public String getCourseName() {
return courseName;
}
public void setCourseName(String courseName) {
this.courseName = courseName;
}
public String getCourseDescription() {
return courseDescription;
}
// setter method for all variables.
public void setCourseDescription(String courseDescription) {
this.courseDescription = courseDescription;
}
public String getCourseDuration() {
return courseDuration;
}
public void setCourseDuration(String courseDuration) {
this.courseDuration = courseDuration;
}
}
i dont want to make this classs as static it give me error to uch so icant to amke search option in my android application i cant resolve this issue please help to resolve this issue.
i getting error in CourseRVAdapter.filter(text);
this to make filter as static this filter is make in CoursesRVAdapter public void filter(String charText) {------}
is the classs so what can do for making search option in recyclerview adapter list in android.
and please if you getting any suggesion for me please give me
i appreciating all of the things that you will says to me
thank you so much

Apache databaseConfiguration doesn't work with MapConfiguration

I am trying to combine both mapConfiguration(file with properties) with databaseConfiguration. However only the file properties can be looked up but not the database properties. What am I doing wrong?
public class MapConfigProvider extends ConfigurationProvider {
Map properties = null;
public MapConfigProvider(Map inProps) {
super(MapConfiguration.class);
properties = inProps;
}
#Override
public AbstractConfiguration getConfiguration(ConfigurationDeclaration decl) throws Exception {
MapConfiguration mapConfig = new MapConfiguration(properties);
return mapConfig;
}
}
public class DatabaseConfigurationProvider extends ConfigurationProvider {
private DatabaseConfigDef dbConfigDef;
public DatabaseConfigurationProvider(DatabaseConfigDef databaseConfigDef)
{
super(DatabaseConfiguration.class);
this.dbConfigDef = databaseConfigDef;
}
public DatabaseConfigurationProvider() {
super();
}
#Override
public AbstractConfiguration getConfiguration(ConfigurationDeclaration decl) throws Exception {
DataSource ds = DataSourceFactory.getInstance().getDataSource(DATASOURCE.SEMS);
return new DatabaseConfiguration(ds, "CSW_TABLE", "PROP_COL", "VALUE_COL"); //String values sought from databaseConfigDef
}
}
private static final Map<String, Object> propertiesMap= new HashMap<String, Object>();
DefaultConfigurationBuilder builder = new DefaultConfigurationBuilder(propFileUrl);
builder.addConfigurationProvider("filebased", new MapConfigProvider(propertiesMap));
builder.addConfigurationProvider("ctkdatabase", new DatabaseConfigurationProvider(databaseConfigDef));
CombinedConfiguration combinedConfig = builder.getConfiguration(true);
String prop1 = combinedConfig.getString("WCM_WEBSERVICE_PORT"); //From DB, gets null
String prop2 = combinedConfig.getString("temp"); //From file, fetches good
LOGGER.info(prop1 + prop2);
What am I doing wrong? Please help.
1) In the propFileUrl: mainconfig.xml, I have to specify a
<configuration>
<header>
<result delimiterParsingDisabled="true" forceReloadCheck="false">
<nodeCombiner config-class="org.apache.commons.configuration.tree.OverrideCombiner" />
<expressionEngine config-class="org.apache.commons.configuration.tree.xpath.XPathExpressionEngine" />
</result>
</header>
<system /> <!-- load system properties into config -->
<properties fileName="common/datasources.properties" />
<properties fileName="application.properties" />
<ctkdatabase jndi="jdbc/shaDs" table="TABLE_APPL_PROPERTIES" keyColumn="PROP_NAME" valueColumn="PROP_VALUE"/>
<!-- load host's config file -->
<xml fileName="app/cluster/datasources.xml" />
</configuration>
2) Create a new getter/setter to "jndi" variable in DatabaseConfigDef class.
3) And change getConfiguration() to:
#Override
public AbstractConfiguration getConfiguration(ConfigurationDeclaration decl) throws Exception {
DatabaseConfigDef def = (DatabaseConfigDef)createBean(DatabaseConfigDef.class, decl, null);
Context env = (Context) new InitialContext().lookup("java:comp/env");
DataSource ds = (DataSource)env.lookup((def.getJndi()));
return new DatabaseConfiguration(ds, def.getTable(), def.getKeyColumn(), def.getValueColumn());
}

SQLite Database: Unable to get specific entry data

I'm following a tutorial about setting up SQLite database with Android Java. I've created a database and a simple table to contain data about food and its calories. I've setup a few buttons with functions to enter data, view, get information about a specific entry, modify and delete it.
All works well except the button to get a specific entry. When I click on the 'Get Information' button, it's supposed to return with the food name and its calories value, according to the row ID I put.
Can anyone help to look at my code here, to check what's wrong or missing?
Here is the code for the classes. I've excluded some parts which are not related.
Creating the database:
public class FormDatabase
{
public static final String KEY_ROWID = "_id";
public static final String KEY_FOOD = "food_name";
public static final String KEY_CALORIE = "food_calories";
private static final String DATABASE_NAME = "Calories";
private static final String DATABASE_TABLE = "FoodTable";
private static final int DATABASE_VERSION = 2;
private DbHelper ourHelper;
private final Context ourContext;
private SQLiteDatabase ourDatabase;
private static class DbHelper extends SQLiteOpenHelper
{
public DbHelper(Context context)
{
super(context, DATABASE_NAME, null, DATABASE_VERSION);
// TODO Auto-generated constructor stub
}
#Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL("CREATE TABLE " + DATABASE_TABLE + " (" +
KEY_ROWID + " INTEGER PRIMARY KEY AUTOINCREMENT , " +
KEY_FOOD + " TEXT NOT NULL , " +
KEY_CALORIE + " TEXT NOT NULL);"
);
}
public String getFood(long l) throws SQLException{
// get data of food name
String[] columns = new String[]{ KEY_ROWID, KEY_FOOD, KEY_CALORIE};
Cursor c = ourDatabase.query(DATABASE_TABLE, columns, KEY_ROWID + "=" + l, null, null, null, null);
if (c != null){
c.moveToFirst();
String food = c.getString(1);
return food;
}
return null;
}
public String getCalorie(long l) throws SQLException{
// get data of food calorie
String[] columns = new String[]{ KEY_ROWID, KEY_FOOD, KEY_CALORIE};
Cursor c = ourDatabase.query(DATABASE_TABLE, columns, KEY_ROWID + "=" +
l, null, null, null, null);
if (c != null){
c.moveToFirst();
String calorie = c.getString(2);
return calorie;
}
return null;
}
Another class for setting the main page:
public class DatabaseMain extends Activity implements OnClickListener{
Button sqlUpdate, sqlView, sqlModify, sqlGetInfo, sqlDelete;
EditText sqlFood, sqlCalorie, sqlRow;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.database_main);
sqlUpdate = (Button) findViewById(R.id.bSQLUpdate);
sqlFood = (EditText) findViewById(R.id.etSQLFood);
sqlCalorie = (EditText) findViewById(R.id.etSQLCalorie);
sqlView = (Button) findViewById (R.id.bSQLopenView);
sqlView.setOnClickListener(this);
sqlUpdate.setOnClickListener(this);
sqlRow = (EditText) findViewById(R.id.etSQLrowInfo);
sqlModify = (Button) findViewById(R.id.bSQLmodify);
sqlGetInfo = (Button) findViewById(R.id.bgetInfo);
sqlDelete = (Button) findViewById(R.id.bSQLdelete);
sqlDelete.setOnClickListener(this);
sqlModify.setOnClickListener(this);
sqlDelete.setOnClickListener(this);
}
public void onClick(View arg0)
{
// When click on buttons, data entry into database, view, modify and
delete row
switch (arg0.getId())
{
case R.id.bgetInfo:
try {
String s = sqlRow.getText().toString();
long l = Long.parseLong(s);
FormDatabase foodcal = new FormDatabase(this);
foodcal.open();
String returnedFood = foodcal.getFood(l);
String returnedCalories = foodcal.getCalorie(l);
foodcal.close();
sqlFood.setText(returnedFood);
sqlCalorie.setText(returnedCalories);
}catch (Exception e)
{
String error = e.toString();
Dialog d = new Dialog(this);
d.setTitle("This is an error!");
TextView tv = new TextView(this);
tv.setText(error);
d.setContentView(tv);
d.show();
}
break;
}
}
The database_main 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">
<TextView
android:id="#+id/textView1"
android:text="Food"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceSmall"/>
<EditText
android:id="#+id/etSQLFood"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="text" >
</EditText>
<TextView
android:id="#+id/textView3"
android:text="Food Calorie"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</TextView>
<EditText
android:id="#+id/etSQLCalorie"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="number" >
</EditText>
<Button
android:text="Update SQLite Database"
android:id="#+id/bSQLUpdate"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</Button>
<Button
android:text="View"
android:id="#+id/bSQLopenView"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</Button>
<TextView
android:id="#+id/textView2"
android:text="Enter Row ID"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</TextView>
<EditText
android:id="#+id/etSQLrowInfo"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:inputType="number" >
<requestFocus></requestFocus>
</EditText>
<Button
android:text="Get Information"
android:id="#+id/bgetInfo"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</Button>
<Button
android:text="Edit Entry"
android:id="#+id/bSQLmodify"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</Button>
<Button
android:text="Delete Entry"
android:id="#+id/bSQLdelete"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</Button>
</LinearLayout>
to add a check to your switch statement, add a default case:
switch (arg0.getId())
{
case R.id.bgetInfo:
... do something...
break;
default:
//this will handle everything else
// write out the argument for debugging, eg:
Console.WriteLine(arg0.getId().ToString());
break;
}
this will tell you what is coming through. if arg0.getId() is not R.id.bgetInfo, the event won't fire...
Cursor c = ourDatabase.query(DATABASE_TABLE, columns, KEY_ROWID + "=" +
l, null, null, null, null);
instead using above statement use this one
Cursor c = ourDatabase.query(DATABASE_TABLE, columns, KEY_ROWID + "=?",
new String[] { String.valueOf(l) }, null, null, null, null);

Two Spinner and Array

I'm studing android and the excercise I'll do is this one:
You have the Five Continental with relative state/capital.
Create an Activity with two spinner and une button .
When you select Continent from the first spinner the second spinner should display only the state of the relative continent. When you click on the button a dialog box should show:
Continental: Selected Contiental;
State:Selected State;
StateCapital: the capital of the state.
I don't want to use any db (I'm a dummy at the moment) can you help me ?
I think is more simple to use arrays.
I Create my string xml
<string name="Select_continent">Select Continent</string>
<string-array name="continent">
<item>Usa</item>
<item>Europe</item>
<item>Australia</item>
<item>Asia</item>
<item>Africa</item>
</string-array>
<string name="Select_state_usa">Select State</string>
<string-array name="Usa">
<item>Alabama</item>
<item>Ohio</item>
<item>Florida</item>
<item>...</item>
<string name="Select_state_eu">Select State</string>
<string-array name="Europe">
<item>Germany</item>
<item>Italy</item>
<item>England</item>
<item>...</item>
Then I create my main.xml
<Spinner
android:id="#+id/spinner1"
android:layout_width="300dp"
android:layout_height="50dp"
android:entries="#array/continent"
android:prompt="#string/Select_continent"
android:gravity="center"
/>
<TextView
android:id="#+id/TextView01"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text=" Select continent:"
android:textColor="#000" />
<Spinner
android:id="#+id/spinner2"
android:layout_width="297dp"
android:layout_height="50dp"
/>
And then I create MyActivity.java
public class MyActivity extends Activity {
private Spinner spinner1, spinner2;
private Button btnSubmit;
final Context context = this;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.Myactivity);
addItemsOnSpinner2();
addListenerOnButton();
addListenerOnSpinnerItemSelection();
}
//add items into spinner dynamically
public void addItemsOnSpinner2() {
spinner2 = (Spinner) findViewById(R.id.spinner2);
List<String> list = new ArrayList<String>();
list.add("Austria");
list.add("Italy");
list.add("Germany");
list.add("France");
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>
this,android.R.layout.simple_spinner_item,list);dataAdapter.setDropDownViewResource
android.R.layout.simple_spinner_dropdown_item);spinner2.setAdapter(dataAdapter);
}
public void addListenerOnSpinnerItemSelection(){
spinner1 = (Spinner) findViewById(R.id.spinner1);
}
//get the selected dropdown list value
public void addListenerOnButton() {
spinner1 = (Spinner) findViewById(R.id.spinner1);
spinner2 = (Spinner) findViewById(R.id.spinner2);
btnSubmit = (Button) findViewById(R.id.btnSubmit);
btnSubmit.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {AlertDialog.Builder alertDialogBuilder3 = new AlertDialog.Builder
(context);
alertDialogBuilder3
.setTitle("Continent")
.setIcon(R.drawable.info)
.setMessage("Continent " + "\n " + String.valueOf (spinner1.getSelectedItem()) +
"\n " + String.valueOf(spinner2.getSelectedItem()) +
"\nCapital : " )
.setNeutralButton("Ok",null)
.create() // create one
.show();
}
});
}}
Can you help me to add the relative state to the continent?
Initialize both spinners, populate the continent spinner and set OnItemSelected() listener, switch-case on the selected item, populate the second spinner according to the case.
EDITED:
Sure! Please note, however that I am currently on my tablet so I will not be able to test out the code before handing it out to you.
public class MyClass extends Activity
{
ArrayList<String> continents;
ArrayList<String> statesOfContA;
ArrayList<String> statesOfContB;
Spinner conts;
Spinner states;
Button btnShowToast;
String continentValue;
String stateValue;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
btnShowToast = (Button)findViewById(R.id.btnShow);
continents = new ArrayList<String>();
statesOfContA = new ArrayList<String>();
statesOfContB = new ArrayList<String>();
continents.add("Continent A");
continents.add("Continent B");
statesOfContA.add("State A");
statesOfContA.add("State B");
statesOfContB.add("State A");
statesOfContB.add("State B");
conts = (Spinner)findViewById(R.id.spConts);
states = (Spinner)findViewById(R.id.spStates);
ArrayAdapter<String> contAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, continents);
conts.setAdapter(contAdapter);
conts.setOnItemClickListener(new OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> parent, View v, int pos,
long arg3)
{
ArrayAdapter<String> stateAdapter;
String choice = parent.getItemAtPosition(pos).toString();
continentValue = continents.getSelectedItem().toString();
switch(choice)
{
case "Continent A":
stateAdapter = new ArrayAdapter<String>(MyClass.this, android.R.layout.simple_spinner_item, statesOfContA);
states.setAdapter(stateAdapter);
break;
case "Continent B":
stateAdapter = new ArrayAdapter<String>(MyClass.this, android.R.layout.simple_spinner_item, statesOfContB);
states.setAdapter(stateAdapter);
break;
}
Toast t = Toast.makeText(getApplicationContext(), "Continent: " + continentValue + " State: " + stateValue, Toast.LENGTH_LONG;
t.show();
}
});
btnShowToast.setOnClickListener(new View.setOnClickListener()
{
#Override
public void onClick(View v)
{
Toast t = Toast.makeText(getApplicationContext(), "Continent: " continentValue + " State: " + stateValue, Toast.LENGTH_LONG;
t.show();
}
}
}
}
Watch out for any spelling mistakes as well! If this doesn't work, kindly let me know so we can find another solution :)
Good luck!

How to call another method in the pojo class setter method [session file uploading application] of Hibernate and struts 2

Hi Friends i am developing an web application which uses hibernate and struts2. i am creating photo album i successfully done that with out using hibernate but, with hibernate it is having problem while inserting to the database. the module works like this as soon as the file uploaded it will insert the FileName, Contenttype,id and it suppose to insert the Image File(byte[]) Content also but it is showing Null in table value.. my code goes like this...
#Entity
#Table(name="PHOTOALBUM")
public class User implements Serializable {
#Id
#GeneratedValue
#Column(name="PHOTO_ID")
private Long id;
#Column(name="IMAGE")
private byte[] Image;
#Column(name="CONTENT_TYPE")
private String userImageContentType;
#Column(name="PHOTO_NAME")
private String userImageFileName;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getUserImageFileName() {
return userImageFileName;
}
public void setUserImageFileName(String userImageFileName) {
this.userImageFileName = userImageFileName;
}
public String getUserImageContentType() {
return userImageContentType;
}
public void setUserImageContentType(String userImageContentType) {
this.userImageContentType = userImageContentType;
}
public byte[] getImage() {
return Image;
}
public void setImage(byte[] Image) {
Image=Change(this.getUserImage());
this.Image = Image;
}
#Transient
private File userImage;
public File getUserImage() {
return userImage;
}
public void setUserImage(File userImage) {
this.userImage = userImage;
}
public byte[] Change(File userImage)
{
// userImage=this.getUserImage();
// String name=userImage.getName();
// long len=userImage.length();
byte[] bFile = new byte[(int) userImage.length()];
try {
FileInputStream fileInputStream = new FileInputStream(userImage);
fileInputStream.read(bFile);
fileInputStream.close();
}
catch(Exception e)
{
e.printStackTrace();
}
// System.out.println("The Name Of File In Pojo Class Is:="+ name);
//System.out.println("The Length Of File In Pojo Class Is:="+ len);
//System.out.println("The Content Of File In Pojo Class Is:="+ bFile);
return bFile;
}
}
and i am saving the values like this
public class UserDAOImpl implements UserDAO {
#SessionTarget
Session session;
#TransactionTarget
Transaction transaction;
/**
* Used to save or update a user.
*/
#Override
public void saveOrUpdateUser(User user) {
try {
session.saveOrUpdate(user);
} catch (Exception e) {
transaction.rollback();
e.printStackTrace();
}
}
/**
* Used to delete a user.
*/
#Override
public void deleteUser(Long userId) {
try {
User user = (User) session.get(User.class, userId);
session.delete(user);
} catch (Exception e) {
transaction.rollback();
e.printStackTrace();
}
}
/**
* Used to list all the users.
*/
#SuppressWarnings("unchecked")
#Override
public List<User> listUser() {
List<User> courses = null;
try {
courses = session.createQuery("from User").list();
} catch (Exception e) {
e.printStackTrace();
}
return courses;
}
/**
* Used to list a single user by Id.
*/
#Override
public User listUserById(Long userId) {
User user = null;
try {
user = (User) session.get(User.class, userId);
} catch (Exception e) {
e.printStackTrace();
}
return user;
}
}
the struts action mapping goes like this...
\<package name="default" extends="hibernate-default">
<action name="saveOrUpdateUser"method="saveOrUpdate"class="com.srikanth.web.UserAction">
<result name="success" type="redirect">listUser</result>
</action>
<action name="listUser" method="list" class="com.srikanth.web.UserAction">
<result name="success">/register.jsp</result>
</action>
<action name="editUser" method="edit" class="com.srikanth.web.UserAction">
<result name="success">/register.jsp</result>
</action>
<action name="deleteUser" method="delete" class="com.srikanth.web.UserAction">
<result name="success" type="redirect">listUser</result>
</action>
</package>
and my jsp goes like this
\<s:form action="saveOrUpdateUser">
<s:push value="user">
<s:hidden name="id" />
<s:file name="userImage" label="User Image" />
<s:submit />
</s:push>
</s:form>
<s:iterator value="userList" status="userStatus">
<s:property value="id" />
<s:property value="userImageFileName" />
<s:property value="userImageContentType" />
<img src='<s:property value="userImage" />' alt"" />
<s:url id="deleteURL" action="deleteUser">
<s:param name="id" value="%{id}"></s:param>
</s:url> <s:a href="%{deleteURL}">Delete</s:a>
</s:iterator>
I am trying to call the Change Method so that it convert the file to byte[] and stored it in byte[] Image variable using setter but it is not working....
So please help me with this one .....
thanks in advance
As per my understand of question the problem is only inserting file into table. Copy & paste the Change() method into com.srikanth.web.UserAction class as you are using this action for every DB transaction. use Change() method before going to insert/update in DB.
For example:
public class UserAction extends ActionSupport{
//variable to get file from jsp
private File uploadedImage;
.....
//setters & getters for uploadedImage
#Override
public String gsexecute() throws Exception {
User user = new User();
//set image value as byteArray
user.setImage(Change(uploadedImage));
//insert or update DB here
return SUCCESS;
}
public byte[] Change(File userImage)
{
// userImage=this.getUserImage();
// String name=userImage.getName();
// long len=userImage.length();
byte[] bFile = new byte[(int) userImage.length()];
try {
FileInputStream fileInputStream = new FileInputStream(userImage);
fileInputStream.read(bFile);
fileInputStream.close();
}
catch(Exception e)
{
e.printStackTrace();
}
// System.out.println("The Name Of File In Pojo Class Is:="+ name);
//System.out.println("The Length Of File In Pojo Class Is:="+ len);
//System.out.println("The Content Of File In Pojo Class Is:="+ bFile);
return bFile;
}
}
And make sure that the table column should support the byte array insert. Ex: use BLOB column type for MYSQL.

Resources