So I have a dialog box, where EditText is enabled, and when someone keys in something, and clicks on the add button, their text gets added into the database. Here are my "mainactivity" which is named IndivItem.java, codes.
public class IndivItem extends Activity {
TextView name, price;
Button descB, revB;
ImageView converse;
ImageButton fav, buy, compare;
TableLayout table_layout;
ReviewController revcon;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_indiv_item);
revcon = new ReviewController(this);
price = (TextView) findViewById(R.id.picPrice1);
name = (TextView) findViewById(R.id.text1);
descB = (Button) findViewById(R.id.desc);
revB = (Button) findViewById(R.id.review);
converse = (ImageView) findViewById(R.id.shoee1);
fav = (ImageButton) findViewById(R.id.fv1);
buy = (ImageButton) findViewById(R.id.co1);
compare = (ImageButton) findViewById(R.id.cp1);
table_layout = (TableLayout) findViewById(R.id.tableLayout1);
BuildTable();
revB.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(final View arg0) {
// TODO Auto-generated method stub
AlertDialog.Builder alertDialog = new AlertDialog.Builder(
IndivItem.this);
// Setting Dialog Title
alertDialog.setTitle("Review");
// Setting Dialog Message
alertDialog.setMessage("Add a Review");
final EditText input = new EditText(IndivItem.this);
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.MATCH_PARENT);
input.setLayoutParams(lp);
alertDialog
.setView(input)
.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
// if this button is clicked, just close
// the dialog box and do nothing
dialog.cancel();
}
})
.setCancelable(false)
.setPositiveButton("Add",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
new MyAsync().execute();
// toast saying review added
Toast.makeText(getApplicationContext(),
"Review Added!",
Toast.LENGTH_SHORT).show();
Intent home = new Intent(
getApplicationContext(),
IndivItem.class);
startActivity(home);
}
// close dialog
});
// show alert
alertDialog.show();
}
});
fav.setOnHoverListener(new OnHoverListener() {
#Override
public boolean onHover(View arg0, MotionEvent arg1) {
// TODO Auto-generated method stub
Toast.makeText(IndivItem.this, "Add to Favorites",
Toast.LENGTH_SHORT).show();
return false;
}
});
compare.setOnHoverListener(new OnHoverListener() {
#Override
public boolean onHover(View arg0, MotionEvent arg1) {
// TODO Auto-generated method stub
Toast.makeText(IndivItem.this, "Add to Compare List",
Toast.LENGTH_SHORT).show();
return false;
}
});
}
private void BuildTable() {
// TODO Auto-generated method stub
revcon.open();
Cursor c = revcon.readEntry();
int rows = c.getCount();
int cols = c.getColumnCount();
c.moveToFirst();
// outer for loop
for (int i = 0; i < rows; i++) {
TableRow row = new TableRow(IndivItem.this);
row.setLayoutParams(new LayoutParams(
LayoutParams.MATCH_PARENT,
LayoutParams.WRAP_CONTENT));
// inner for loop
for (int j = 0; j < cols; j++) {
TextView tv = new TextView(IndivItem.this);
tv.setGravity(Gravity.CENTER);
tv.setTextSize(18);
tv.setPadding(0, 5, 0, 5);
tv.setText(c.getString(j));
row.addView(tv);
}
c.moveToNext();
table_layout.addView(row);
}
revcon.close();
}
private class MyAsync extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... arg0) {
// TODO Auto-generated method stub
String review = input.getText().toString();
return null;
revcon.open();
revcon.createEntry(review);
// BuildTable();
return null;
}}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu, menu);
return true;
}
}
And what happens is this line : String review = input.getText().toString();,
Gives me an error, that says error cannot resolved. I have no clue how to link the codes ): or what I'm doing wrong, please enlighten me,thanks!
Related
Like the title says. I have coded onClickListener to my AlertDialog but i don't know how to put there onLongClickListener.
This is my code:
private void addRecipeMethod() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Title");
adapter = new ArrayAdapter<>(getBaseContext(), android.R.layout.simple_list_item_1, getArrayList("ListOfRecipes"));
builder.setAdapter(adapter, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
List<String> list = new ArrayList<>(getArrayList("ListOfRecipes"));
getArrayListRecipes(list.get(which));
List<String> listMain = new ArrayList<>(getArrayList("ListMain"));
listMain.addAll(getArrayListRecipes(list.get(which)));
saveList(listMain, "ListMain");
adapter = new ArrayAdapter<>(getBaseContext(), android.R.layout.simple_list_item_1, getArrayList("ListMain"));
listView.setAdapter(adapter);
//Toast.makeText(getApplicationContext(), "you have clicked " + list.get(which) , Toast.LENGTH_SHORT).show();
}
});
builder.show();
}
PS. void addRecipeMethod is called when Menu Item is clicked
Create AlertDialog with custom layout like this
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(this);
// ...Irrelevant code for customizing the buttons and title
LayoutInflater inflater = this.getLayoutInflater();
View dialogView = inflater.inflate(R.layout.alert_label_editor, null);
dialogBuilder.setView(dialogView);
Button button = (Button)dialogBuilder.findViewById(R.id.btnName);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//Commond here......
}
});
button.setOnLongClickListener(new OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
// TODO Auto-generated method stub
return false;
}
});
AlertDialog alertDialog = dialogBuilder.create();
alertDialog.show();
Add Button in alert_label_editor xml and add setOnLongClickListener for that Button
Button button = (Button)dialogBuilder.findViewById(R.id.btnName);
button.setOnLongClickListener(new OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
// TODO Auto-generated method stub
return false;
}
});
I want to add search functionality in my apps. Mainly it's retrieve json data into a List.
Here is my code
MainActivity main;
Context context;
LayoutInflater inflater;
ArrayList<HashMap<String, String>> data;
ImageLoader imageLoader;
HashMap<String, String> resultp = new HashMap<String, String>();
private ArrayList<WorldPopulation> arrayList;
public ListViewAdapter(Context context,
ArrayList<HashMap<String, String>> arraylist) {
this.context = context;
data = arraylist;
imageLoader = new ImageLoader(context);
}
public class ViewHolder {
TextView rank;
TextView country;
TextView population;
ImageView flag;
}
#Override
public int getCount() {
return data.size();
}
#Override
public Object getItem(int position) {
return data.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
public View getView(final int position, View view, ViewGroup parent) {
// Declare Variables
TextView rank;
TextView country;
TextView population;
ImageView flag;
inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View itemView = inflater.inflate(R.layout.listview_item, parent, false);
// Get the position
resultp = data.get(position);
// Locate the TextViews in listview_item.xml
//rank = (TextView) itemView.findViewById(R.id.rank);
country = (TextView) itemView.findViewById(R.id.country);
// population = (TextView) itemView.findViewById(R.id.population);
// Locate the ImageView in listview_item.xml
flag = (ImageView) itemView.findViewById(R.id.flag);
// Capture position and set results to the TextViews
// rank.setText(resultp.get(MainActivity.VIDEO_ID));
country.setText(resultp.get(MainActivity.TITLE));
// population.setText(resultp.get(MainActivity.DESCRIPTION));
// Capture position and set results to the ImageView
// Passes flag images URL into ImageLoader.class
imageLoader.DisplayImage(resultp.get(MainActivity.imgURL), flag);
// Capture ListView item click
mPublisherInterstitialAd = new PublisherInterstitialAd(context);
mPublisherInterstitialAd.setAdUnitId("ca-app-pub-7500090319214897/8263070161");
mPublisherInterstitialAd.setAdListener(new AdListener() {
#Override
public void onAdClosed() {
requestNewInterstitial();
}
});
requestNewInterstitial();
itemView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// Get the position
resultp = data.get(position);
Intent intent = new Intent(context, PlayerViewDemoActivity.class);
intent.putExtra("videoId", resultp.get(MainActivity.VIDEO_ID));
context.startActivity(intent);
}
});
return itemView;
}
// Filter Class
public void filter(String charText) {
charText = charText.toLowerCase(Locale.getDefault());
data.clear();
if (charText.length() == 0) {
data.addAll((Collection<? extends HashMap<String, String>>) resultp);
} else {
for (HashMap<String, String> wp : (Collection<? extends HashMap<String, String>>) resultp) {
if (wp.get(MainActivity.TITLE).toLowerCase(Locale.getDefault())
.contains(charText)) {
data.add(wp);
}
}
}
notifyDataSetChanged();
}
I got some error in this code.how can i solve it?
i am stack more than 15days. Help me out.
here is my error
java.lang.ClassCastException: java.util.HashMap cannot be cast to java.util.Collection
at com.sextech.noui.ListViewAdapter.filter(ListViewAdapter.java:154)
at com.sextech.noui.MainActivity$DownloadJSON$1.afterTextChanged(MainActivity.java:230)
at android.widget.TextView.sendAfterTextChanged(TextView.java:7822)
at android.widget.TextView$ChangeWatcher.afterTextChanged(TextView.java:9635)
at android.text.SpannableStringBuilder.sendAfterTextChanged(SpannableStringBuilder.java:976)
at android.text.SpannableStringBuilder.replace(SpannableStringBuilder.java:520)
at android.text.SpannableStringBuilder.replace(SpannableStringBuilder.java:454)
at android.text.SpannableStringBuilder.replace(SpannableStringBuilder.java:33)
at android.view.inputmethod.BaseInputConnection.replaceText(BaseInputConnection.java:690)
at android.view.inputmethod.BaseInputConnection.setComposingText(BaseInputConnection.java:450)
at com.android.internal.view.IInputConnectionWrapper.executeMessage(IInputConnectionWrapper.java:349)
at com.android.internal.view.IInputConnectionWrapper$MyHandler.handleMessage(IInputConnectionWrapper.java:82)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:135)
at android.app.ActivityThread.main(ActivityThread.java:5593)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:960)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
Main Activity
// Declare Variables
JSONObject jsonobject;
JSONArray jsonarray;
ListView listview;
ListViewAdapter adapter;
private ProgressBar spinner;
ArrayList<HashMap<String, String>> arraylist;
private AdView mAdView;
private InterstitialAd interstitial;
private long lastPressedTime;
public static String imgURL = "url";
public static String VIDEO_ID = "videoId";
public static String TITLE = "title";
EditText editsearch;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final WifiManager wifiManager = (WifiManager) this.getSystemService(Context.WIFI_SERVICE);
final boolean b=wifiManager.isWifiEnabled();
ConnectivityManager cManager=(ConnectivityManager)getSystemService(this.CONNECTIVITY_SERVICE);
final NetworkInfo nInfo=cManager.getActiveNetworkInfo();
if(nInfo!=null&& nInfo.isConnected()) {
Toast.makeText(this, "You are Connected to the Internet", Toast.LENGTH_LONG).show();
setContentView(R.layout.listview_main);
spinner = (ProgressBar)findViewById(R.id.progressBar1);
new DownloadJSON().execute();
AdView mAdView = new AdView(this);
mAdView.setAdSize(AdSize.SMART_BANNER);
// Gets the ad view defined in layout/ad_fragment.xml with ad unit ID set in
// values/strings.xml.
mAdView = (AdView) findViewById(R.id.ad_view);
// Create an ad request. Check logcat output for the hashed device ID to
// get test ads on a physical device. e.g.
// "Use AdRequest.Builder.addTestDevice("ABCDEF012345") to get test ads on this device."
AdRequest adRequest = new AdRequest.Builder()
.addTestDevice("")
.build();
// Start loading the ad in the background.
mAdView.loadAd(adRequest);
}
else {
new AlertDialog.Builder(this)
.setIcon(android.R.drawable.ic_dialog_alert)
.setTitle("Your DATA Connection is Currently Unreachable")
.setMessage("Connect your WiFi or 2G/3G DATA Connection")
.setPositiveButton("WiFi ", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
try {
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
final Intent mainIntent = new Intent(MainActivity.this, MainActivity.class);
MainActivity.this.startActivity(mainIntent);
MainActivity.this.finish();
}
}, 5000);
wifiManager.setWifiEnabled(true);
Toast.makeText(MainActivity.this, "WiFi Enabling in 5sec Please Wait", Toast.LENGTH_LONG).show();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
})
.setNegativeButton("3G/2G ", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//use here tablayout to work when 3G/2G connecion is available
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
final Intent mainIntent = new Intent(MainActivity.this, MainActivity.class);
MainActivity.this.startActivity(mainIntent);
MainActivity.this.finish();
}
}, 5000);
Intent myints = new Intent(Settings.ACTION_DATA_ROAMING_SETTINGS);
Toast.makeText(MainActivity.this, "Your DATA Connection is NOW Connected", Toast.LENGTH_LONG).show();
startActivity(myints);
}
})
.setNeutralButton("Exit", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(MainActivity.this, "To use this Application you have to Connected to the Internet", Toast.LENGTH_LONG).show();
finish();
}
})
.setCancelable(false)
.show();
}
}
public class DownloadJSON extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
spinner.setVisibility(View.VISIBLE);
}
#Override
protected Void doInBackground(Void... params) {
// Create an array
arraylist = new ArrayList<HashMap<String, String>>();
// Retrieve JSON Objects from the given URL address
jsonobject = JSONfunctions.getJSONfromURL("https://www.googleapis.com/youtube/v3/search?part=id%2Csnippet&q=bangla+video+song&maxResults=50&key=AIzaSyAFfA9cCFpmsyK5byKaRWE_oQKjjsABuxI");
try {
// Locate the array name in JSON
JSONArray jsonarray = jsonobject.getJSONArray("items");
for (int i = 0; i < jsonarray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
jsonobject = jsonarray.getJSONObject(i);
// Retrive JSON Objects
JSONObject jsonObjId = jsonobject.getJSONObject("id");
map.put("videoId", jsonObjId.getString("videoId"));
JSONObject jsonObjSnippet = jsonobject.getJSONObject("snippet");
map.put("title", jsonObjSnippet.getString("title"));
//map.put("description", jsonObjSnippet.getString("description"));
// map.put("flag", jsonobject.getString("flag"));
JSONObject jsonObjThumbnail = jsonObjSnippet.getJSONObject("thumbnails");
String imgURL = jsonObjThumbnail.getJSONObject("high").getString("url");
map.put("url",imgURL);
// Set the JSON Objects into the array
arraylist.add(map);
}
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void args) {
// Locate the listview in listview_main.xml
listview = (ListView) findViewById(R.id.listview);
// Pass the results into ListViewAdapter.java
adapter = new ListViewAdapter(MainActivity.this, arraylist);
// Set the adapter to the ListView
listview.setAdapter(adapter);
// Close the progressdialog
spinner.setVisibility(View.GONE);
editsearch = (EditText) findViewById(R.id.search);
// Capture Text in EditText
editsearch.addTextChangedListener(new TextWatcher() {
#Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
String text = editsearch.getText().toString().toLowerCase(Locale.getDefault());
adapter.filter(text);
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1,
int arg2, int arg3) {
// TODO Auto-generated method stub
}
#Override
public void onTextChanged(CharSequence arg0, int arg1, int arg2,
int arg3) {
// TODO Auto-generated method stub
}
});
}
}
// Dialouge Box
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
//Handle the back button
if (keyCode == KeyEvent.KEYCODE_BACK) {
//Ask the user if they want to quit
new android.support.v7.app.AlertDialog.Builder (this)
.setIcon(android.R.drawable.ic_dialog_alert)
.setTitle(R.string.quit)
.setMessage(R.string.really_quit)
.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//Stop the activity
MainActivity.this.finish();
}
})
.setNeutralButton(R.string.neutral, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(getApplicationContext(), "Rate This App", Toast.LENGTH_SHORT).show();
startActivity(new Intent("android.intent.action.VIEW", Uri.parse("https://play.google.com/store/apps/details?id=com.vdoapps.banglatube")));
}
})
.setNegativeButton(R.string.no, null)
.show();
return true;
} else {
return super.onKeyDown(keyCode, event);
}
}
}
HashMap does not implement Collection. So you cannot type cast HashMap into a Collection.
In your case, the type cast is not needed. The resultp object of of type HashMap, and the data object is of type ArrayList<HashMap>, so you can simply do data.add(resultp)
For the loop, you don't need the loop at all.
if (resultp.get(MainActivity.TITLE).toLowerCase(Locale.getDefault()) .contains(charText)) {
data.add(resultp);
}
The main purpose of this Android app is to learn how to use spinners and parse data. I have tried a lot of things and it still is not working. I don't get the output of the resultFuel on the screen.
Here's the code in my MainActivity:
public class MainActivity extends Activity implements OnItemSelectedListener {
Spinner spinFrom,spinTo;
String[] paths ={"liters/100km","liters/100 miles","(US)gallons/100 miles","(US)gallons/100km","(UK)gallons/100miles",
"(UK)gallons/100km","kilometers/liter","miles/liter", "miles/gallon", "kilometers/gallon"
};
EditText etfrom;
TextView textview;
double fromFuel,resultFuel;
Button clik;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
spinFrom = (Spinner) findViewById(R.id.fromSpinner);
spinTo = (Spinner) findViewById(R.id.toSpinner);
etfrom = (EditText) findViewById(R.id.fromET);
textview = (TextView) findViewById(R.id.Results);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(MainActivity.this,android.R.layout.simple_spinner_item,paths);
spinFrom.setAdapter(adapter);
spinTo.setAdapter(adapter);
spinFrom.setOnItemSelectedListener(this);
spinTo.setOnItemSelectedListener(this);
if( etfrom.length() == 0 || etfrom.equals("") || etfrom == null){
}
clik = (Button) findViewById(R.id.button1);
clik.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(selectedFrom.equals(selectedTo)){
//Do nothing
}else if(selectedFrom.equals("liters/100km")&& selectedTo.equals("liters/100 miles")){
fromFuel= Double.parseDouble(etfrom.getText().toString());
resultFuel = fromFuel* 1.61;
// String result = String.valueOf(resultFuel);
textview.setText("" +resultFuel );
}else{
}
}
});
}
String selectedFrom;
String selectedTo;
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
selectedFrom = spinFrom.getItemAtPosition(arg2).toString();
selectedTo = spinTo.getItemAtPosition(arg2).toString();
Toast.makeText(getBaseContext(),"From: " + selectedTo, Toast.LENGTH_LONG).show();
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}
Please try :
textview.setText(Double.toString(resultFuel) );
I am using ListView that get data from Database.
when i call update and delete i refresh the activity by call Intent.
it shows updated list but when i click on it it not shows changes in text view on which i am showing list details.
i am using Custom Adapter.Below is my code,
public class Mainmenu extends Activity{
ListView list;
DBHandler db= new DBHandler(this);
int ID;
String strname,strlastname,strdob,strcell,strcnic,straddress;
String pppath,cfpath,cbpath,fppath;
TextView tvname,tvlastname,tvdob,tvcnic,tvcell,tvaddress;
ImageView pp,cf,cb;
public static ArrayList<String> customers = new ArrayList<String>();
SearchResults sr1;
ArrayList<SearchResults> searchResults= new ArrayList<SearchResults>();
MyCustomBaseAdapter adaptor;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.mainmenulist);
list= (ListView) findViewById(R.id.listMM);
tvname=(TextView)findViewById(R.id.textView3);
tvlastname=(TextView)findViewById(R.id.textView4);
tvdob=(TextView)findViewById(R.id.textView5);
tvcnic=(TextView)findViewById(R.id.textView10);
tvcell=(TextView)findViewById(R.id.textView7);
tvaddress=(TextView)findViewById(R.id.textView8);
pp=(ImageView)findViewById(R.id.ImageView02);
cf=(ImageView)findViewById(R.id.imageView2);
cb=(ImageView)findViewById(R.id.ImageView03);
Context c =getApplicationContext();
if(db.getAllcustomers2().toString()==null){
db.getWritableDatabase();
db.init();
}else{
List<Customers_GS> gtEdu = db.getAllcustomers2();
customers.clear();
for (Customers_GS ed : gtEdu) {
sr1 = new SearchResults();
ID=ed.getCID();
sr1.setId(ID);
customers.add(ed.getCustomer_Name());
strname=ed.getCustomer_Name().toString();
sr1.setName(strname);
customers.add(ed.getCustomer_DOB());
strdob=ed.getCustomer_DOB().toString();
sr1.setDOB(strdob);
customers.add(ed.getCustomer_CNIC());
strcnic=ed.getCustomer_CNIC().toString();
sr1.setCNIC(strcnic);
customers.add(ed.getCustomer_Cell());
strcell=ed.getCustomer_Cell().toString();
sr1.setPhone(strcell);
customers.add(straddress);
straddress=ed.getCustomer_Address().toString();
sr1.setAddress(straddress);
customers.add(ed.getCustomer_PP());
pppath=ed.getCustomer_PP().toString();
customers.add(ed.getCustomer_CNICf());
cfpath=ed.getCustomer_CNICf().toString();
customers.add(ed.getCustomer_CNICb());
cbpath=ed.getCustomer_CNICb().toString();
customers.add(ed.getCustomer_Thumb());
sr1.setImageNumber(1);
searchResults.add(sr1);
}
}
adaptor= new MyCustomBaseAdapter(c, searchResults);
list.setAdapter(adaptor);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
int height= 146;
int width=146;
//parent.getItemAtPosition(position);
//
Log.d("PP", ""+pppath);
Log.d("cP", ""+cbpath);
Log.d("fP", ""+cfpath);
// Bitmap ppbitmap = BitmapFactory.decodeFile(pppath );
// Bitmap cbbitmap = BitmapFactory.decodeFile(cbpath );
// Bitmap cfbitmap = BitmapFactory.decodeFile(cfpath );
// ppbitmap=Bitmap.createScaledBitmap(ppbitmap, width,height, true);
// cbbitmap=Bitmap.createScaledBitmap(cbbitmap, width,height, true);
// cfbitmap=Bitmap.createScaledBitmap(cfbitmap, width,height, true);
//
// pp.setImageBitmap(ppbitmap);
// cb.setImageBitmap(cbbitmap);
// cf.setImageBitmap(cfbitmap);
String[] result =strname.split(" ");
strname= result[0];
strlastname=result[1];
tvname.setText(strname);
tvlastname.setText(strlastname);
tvcell.setText(strcell);
tvaddress.setText(straddress);
tvcnic.setText(strcnic);
tvdob.setText(strdob);
adaptor.notifyDataSetChanged();
}
});
list.setOnItemLongClickListener(new OnItemLongClickListener() {
public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
int pos, long id) {
// // TODO Auto-generated method stub
//
//
db.getWritableDatabase();
// db.delete(ID);
// db.update(17);
// // TODO Auto-generated method stub
//
// Intent gonext= new Intent("com.example.ibex.MAINMENU");
// startActivity(gonext);
//
AlertDialog.Builder builder = new AlertDialog.Builder(Mainmenu.this);
builder.setMessage("Chose any one!");
builder.setCancelable(false);
builder.setPositiveButton("Edit", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
db.update(ID);
Intent reload = new Intent(getApplicationContext(), Mainmenu.class);
startActivity(reload);
}
});
builder.setNegativeButton("Delete", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
db.delete(ID);
Intent reload = new Intent(getApplicationContext(), Mainmenu.class);
startActivity(reload);
}
});
AlertDialog alert = builder.create();
alert.show();
return true;
}
});
}
////### ## ##### ### ### ### ### #### ### ### ### ### ### ## ////
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater=getMenuInflater();
inflater.inflate(R.menu.optionmenu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if(item.getItemId()==R.id.Addmenu){
Intent openstngs=new Intent("com.example.ibex.REGISTRATION");
startActivity(openstngs);
}else if(item.getItemId()==R.id.Edithmenu){
Bundle contan= new Bundle();
contan.putInt("key", ID );
Intent web =new Intent(Mainmenu.this, Edit.class);
web.putExtras(contan);
startActivity(web);
}else if(item.getItemId()==R.id.Dltmenu){
db.delete(ID);
Intent reload = new Intent(getApplicationContext(), Mainmenu.class);
startActivity(reload);
}else{
AlertDialog.Builder builder = new AlertDialog.Builder(Mainmenu.this);
builder.setMessage("Are u sure to want to Logout ?");
builder.setCancelable(false);
builder.setPositiveButton("yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent reload = new Intent(getApplicationContext(), Login.class);
startActivity(reload);
}
});
builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
return super.onOptionsItemSelected(item);
};
}
I'm not clear about your question since you haven't provided the code of your adapter. I think You haven't called notifyDataSetChanged() method on your Adapter instance to get your changes reflected on ListView.
So I made an Activity with textViews, editTexts, date dialog and time dialog picker. plus a button.
I used this to get the Date/Time dialogs to work:
public class RainbowBookActivity extends Activity {
private static final int DATE_DIALOG_ID=1; // for date
private static final int TIME_DIALOG_ID=2; // for month
private int d,mo,y,h,m; // for date & month variables
Button b1,b2; // button objects
TextView e1,e2; // textview objects
// execution starts from here
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_rainbowbook); // calling activity_rainbowbook.xml
e1=(TextView)findViewById(R.id.textview1); // getting textview1 id from activity_rainbowbook.xml
b1=(Button)findViewById(R.id.button1); // getting button id from activity_rainbowbook.xml
b1.setOnClickListener(new OnClickListener() // setting listener for button one
{
public void onClick(View arg0) {
// TODO Auto-generated method stub
showDialog(DATE_DIALOG_ID); // generating dialog box
}
});
final Calendar cal=Calendar.getInstance(); // allocating memory for calendar instance
d=cal.get(Calendar.DAY_OF_MONTH); // present date
mo=cal.get(Calendar.MONTH); // present month
y=cal.get(Calendar.YEAR); // present year
updateDate(); // update date
b2=(Button)findViewById(R.id.button2); // getting listener for button2
e2=(TextView)findViewById(R.id.textview2);
b2.setOnClickListener(new OnClickListener() // setting listener for button2
{
public void onClick(View arg0) {
// TODO Auto-generated method stub
showDialog(TIME_DIALOG_ID);
}
});
h=Calendar.getInstance().get(Calendar.HOUR); // getting present hour & minute
m=Calendar.getInstance().get(Calendar.MINUTE);
updateTime(); // updating time
}
public void updateTime()
{
e2.setText(new StringBuilder().append(h).append(':').append(m));
}
public void updateDate()
{
e1.setText(new StringBuilder().append(d).append('/').append(mo+1).append('/').append(y));
}
private DatePickerDialog.OnDateSetListener datelistener=new DatePickerDialog.OnDateSetListener()
{
public void onDateSet(DatePicker view,int year, int monthofyear, int day)
{
y=year;
mo=monthofyear;
d=day;
updateDate();
}
};
private TimePickerDialog.OnTimeSetListener timelistener=new TimePickerDialog.OnTimeSetListener()
{
public void onTimeSet(TimePicker view, int hourofday, int minute)
{
// TODO Auto-generated method stub
h=hourofday;
m=minute;
updateTime();
}
};
protected Dialog onCreateDialog(int id)
{
switch(id)
{
case DATE_DIALOG_ID:
return new DatePickerDialog(this,datelistener , y, mo, d);
case TIME_DIALOG_ID:
return new TimePickerDialog(this,timelistener,h,m,false);
}
return null;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_rainbowbook, menu);
return true;
}
}
Now I would some how like to get this in there so I can have a button that transferes info from the editTexts:
EditText inputName;
EditText inputRoom;
public void onCreate1(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_rainbowbook);
inputName = (EditText) findViewById(R.id.editText1);
inputRoom = (EditText) findViewById(R.id.editText2);
Button btnNextScreen = (Button) findViewById(R.id.button3);
//Listening to button event
btnNextScreen.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
//Starting a new Intent
Intent nextScreen = new Intent(getApplicationContext(), BookingsActivity.class);
//Sending data to another Activity
nextScreen.putExtra("name", inputName.getText().toString());
nextScreen.putExtra("room", inputRoom.getText().toString());
Log.e("n", inputName.getText()+"."+ inputRoom.getText());
startActivity(nextScreen);
}
});
}
I cant seem to figure this out and am hoping someone can help me. Thanks.
*
BookingsActivity:
public class BookingsActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bookings);
TextView Name = (TextView) findViewById(R.id.textView2);
TextView Room = (TextView) findViewById(R.id.textView3);
Button btnClose = (Button) findViewById(R.id.btnClose);
Intent i = getIntent();
// Receiving the Data
String name = i.getStringExtra("name");
String room = i.getStringExtra("room");
Log.e("Bookings", name + "." + room);
// Displaying Received data
Name.setText(name);
Room.setText(room);
// Binding Click event to Button
btnClose.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
//Closing SecondScreen Activity
finish();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_bookings, menu);
return true;
}
}
maybe this in your BookingActivity
Bundle b = i.getExtras();
String name = b.getString("name", "default name");
String room = b.getString("room", "default room");
edit:
also, launche BookingActivity with startActivityForResult() so you can get data back from it later when you're done with it.
EDIT:
examples of startActivityForResult can be found How to return a result (startActivityForResult) from a TabHost Activity? and http://android.rahulblogs.com/android-startactivityforresult-example/