Enabling the Edittext on selecting Item from Spinner - android

hello friends I am trying to enable the edittext depending upon my selection of records.The XML file is as below:
<?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" >
<Spinner
android:id="#+id/per_id"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:spinnerMode="dropdown"
android:gravity="center"
android:layout_marginTop="20dp"/>
<Spinner android:id="#+id/columnToUpdate"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:spinnerMode="dialog"
android:gravity="center"
android:layout_marginTop="20dp"/>
<EditText
android:id="#+id/enterToUpdateString"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:layout_marginTop="20dp"
android:inputType="text"
android:hint="#string/EnterTheTextHere"/>
<EditText
android:id="#+id/enterToUpdateInt"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:layout_marginTop="20dp"
android:inputType="number"
android:hint="#string/EnterTheNumberHere"/>
<Button
android:id="#+id/clickToUpdate"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="#string/clickToUpdate"/>
</LinearLayout>
And the Java Code that I am applying is as below :-
package com.indianic.databaseprac;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.database.Cursor;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
public class UpdateFrom25Table extends Activity {
String id, column, text;
EditText integertext;
EditText stringText;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.update_from_25_table);
stringText = (EditText) findViewById(R.id.enterToUpdateString);
integertext = (EditText) findViewById(R.id.enterToUpdateInt);
stringText.setVisibility(View.GONE);
integertext.setVisibility(View.GONE);
Button updateButton = (Button) findViewById(R.id.clickToUpdate);
// Here I am setting the spinner where I am taking the content of the
// table per_ID having all the unique IDs and setting it to the spinner
Spinner spinnerid = (Spinner) findViewById(R.id.per_id);
final Database25TableHandler db = new Database25TableHandler(
getApplicationContext());
List<String> ids = db.gettingid();
ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, ids);
dataAdapter
.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
spinnerid.setAdapter(dataAdapter);
// Here I am setting all the column names in the second spinner with the
// help of the cursor.
Spinner spinnerColumn = (Spinner) findViewById(R.id.columnToUpdate);
List<String> column = db.getcolumnname();
ArrayAdapter<String> dataAdaptercolumn = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, column);
dataAdaptercolumn
.setDropDownViewResource(android.R.layout.simple_dropdown_item_1line);
spinnerColumn.setAdapter(dataAdaptercolumn);
final String spinnerSelectedID = (String) spinnerid.getSelectedItem();
final String spinnerSelectedcolumn = (String) spinnerColumn
.getSelectedItem();
spinnerColumn.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view,
int pos, long id) {
Log.d("TESTING", parent.getItemAtPosition(pos).toString());
// TODO Auto-generated method stub
if(parent.getItemAtPosition(pos).toString() == "reg_id") {
//integertext.setEnabled(true);
Log.d("TESTING", "LOOOOGGGGG");
integertext.setVisibility(View.VISIBLE);
text = integertext.getText().toString();
} else if (parent.getItemAtPosition(pos).toString() == "first_name") {
//stringText.setEnabled(true);
stringText.setVisibility(View.VISIBLE);
text = stringText.getText().toString();
}
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
// Here I am setting all the Items that are selected in the string in
// order to perform the update process.
updateButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
db.updateRow(spinnerSelectedID, spinnerSelectedcolumn, text);
db.close();
}
});
}
}
Here even when I am selecting the reg_id from spinner it is not entering the first if part as the Log.d("TESTING", "LOOOOGGGGG"); is not printed

Try this..
If you comparing String you should use .equels
if(parent.getItemAtPosition(pos).toString().equels("reg_id")) {
//integertext.setEnabled(true);
Log.d("TESTING", "LOOOOGGGGG");
integertext.setVisibility(View.VISIBLE);
text = integertext.getText().toString();
} else if (parent.getItemAtPosition(pos).toString().equels("first_name")) {
//stringText.setEnabled(true);
stringText.setVisibility(View.VISIBLE);
text = stringText.getText().toString();
}
== always just compares two references (for non-primitives, that is) - i.e. it tests whether the two operands refer to the same object.
However, the equals method can be overridden - so two distinct objects can still be equal
EDIT
if(parent.getItemAtPosition(pos).toString().equalsIgnoreCase("reg_id") || parent.getItemAtPosition(pos).toString().equels("first_name")){
}

You should use the .equals(String) method for string comparison (which performs a simple 'shallow' comparison) rather than the '==' comparison (which performs a 'deep' comparison - verifying if two string objects point to the same instance in memory).
Also, to toggle enabled/disabled state, you need to use the setEnabled(boolean) method. setEnabled(true) will set the edittext to be enabled and setEnabled(false) will disable the edittext.

Related

Unfortunately App has stopped - error in Spinner

I have tried everything but still am not able to figure out what is wrong in this code, whenever I click on the Button 'Get Fare' , a dialog opens showing "Unfortunately app has stopped". Please help ...
Code for MetroFare.java
package com.myapp.anuj;
import com.myapp.anuj.MetroFare;
import com.myapp.anuj.R;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.TextView;
public class MetroFare extends Activity implements OnClickListener, OnItemSelectedListener{
String start[] = {"Shastri Nagar", "Kashmere Gate", "Dwarka Mor"};
String dest[] = {"Pratap Nagar", "Rajiv Chowk", "Kirti Nagar"};
Spinner starting, destination;
Button getfare;
int fare = 0;
int s=0, d=0;
TextView result;
int farearray[][] = {{8,15,14}, {10,12,15}, {21,18,15}};
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.kuchbhi);
getfare = (Button) findViewById(R.id.bGetFare);
result = (TextView) findViewById(R.id.tvShowFare);
getfare.setOnClickListener(this);
ArrayAdapter<String> adapterStart = new ArrayAdapter<String>(MetroFare.this, android.R.layout.simple_spinner_item, start);
ArrayAdapter<String> adapterDest = new ArrayAdapter<String>(MetroFare.this, android.R.layout.simple_spinner_item, dest);
starting = (Spinner) findViewById(R.id.spinnerStart);
destination = (Spinner) findViewById(R.id.spinnerDest);
starting.setAdapter(adapterStart);
destination.setAdapter(adapterDest);
starting.setOnItemSelectedListener(this);
destination.setOnItemSelectedListener(this);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String sfare = getString(fare);
result.setText(sfare);
}
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
s = starting.getSelectedItemPosition();
d = destination.getSelectedItemPosition();
fare = farearray[s][d];
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}
Code for kuchbhi.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<Spinner
android:id="#+id/spinnerStart"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<Spinner
android:id="#+id/spinnerDest"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<Button
android:id="#+id/bGetFare"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Get Fare" />
<TextView
android:id="#+id/tvShowFare"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView" />
</LinearLayout>
As I mentioned, your problem is this call: getString(fare), which is attempting to retrieve a String resource with an id the value of fare. Judging from your code, I'm assuming that you're simply trying to display the String value of fare in a TextView, in which case change that call as follows:
String sfare = String.valueOf(fare);

Set OnItemClickListener for a listItem

I get how to do this for a simple ListView, something like:
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
But whenever I do it in my activity I get a nullpointerexception.
Could someone please show me how it is supposed to be? Thanks!
EDIT: I'm sorry! Didn't want to fill up an entire question only with code, I think it's necessary in this case, so I'm putting my entire java code below:
import android.app.ListActivity;
import android.content.Context;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.List;
public class Save extends ListActivity {
String FileName;
EditText et;
String listItem[]={};
ListView listView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(R.layout.activity_save);
Button save = (Button) findViewById(R.id.SAVE); //this is my button
final EditText title = (EditText) findViewById(R.id.save_filename); //This is unused
final EditText maintext = (EditText) findViewById(R.id.test);
getActionBar().setDisplayUseLogoEnabled(false);
getActionBar().setDisplayHomeAsUpEnabled(true);
et = (EditText) findViewById(R.id.save_filename);
listView = (ListView) findViewById(R.id.list); //I've specified this listView only for the OnItemClickListener action
List values = new ArrayList();
for (int i = 0; i < listItem.length; i++) {
values.add(listItem[i]);
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, values);
setListAdapter(adapter);
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try {
FileName = et.getText().toString() + ".txt";
FileOutputStream fout = openFileOutput(FileName, Context.MODE_PRIVATE);
OutputStreamWriter outsw = new OutputStreamWriter(fout);
try {
outsw.write(String.valueOf(maintext));
outsw.flush();
outsw.close();
Toast.makeText(getBaseContext(), "Your file has been saved", Toast.LENGTH_LONG).show();
} catch (IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
ArrayAdapter<String> adapter = (ArrayAdapter<String>) getListAdapter();
String device;
switch (view.getId()) {
case R.id.SAVE:
List myList = new ArrayList();
device = et.getText().toString();
myList.add(device);
adapter.add(device);
et.setText("");
break;
}
adapter.notifyDataSetChanged();
}
});
//I think this is wrong, I get no error in Java by the way. How could this work if there's a specific extension for my activity that define the listview? **That's my question**.
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// ListView Clicked item index
int itemPosition = position;
// ListView Clicked item value
String itemValue = (String) listView.getItemAtPosition(position);
// Show Alert
Toast.makeText(getApplicationContext(),
"Position :"+itemPosition+" ListItem : " +itemValue , Toast.LENGTH_LONG)
.show();
}
});
}
And the xml:
<Button
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:id="#+id/SAVE"
android:text="#string/save_button" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/save_filename"
android:layout_alignRight="#+id/linearLayout"
android:hint="#string/save_hint"
android:layout_alignEnd="#+id/linearLayout"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_marginBottom="5dp" />
<ListView
android:id="#android:id/list"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:layout_above="#+id/linearLayout"
android:layout_below="#+id/save_filename">
</ListView>
Sorry again for the cunfusion!!
The problem here comes from the fact that you are using ListActivity instead of Activity. For this reason the ListView's ID is not added to the R file so it is not callable by the findById call. This would not happen if Activity were used. When using ListActivity you can use the built in getListView() method to get the ListView object.
Also when I ran your given code I got an error that a listView had to be defined by the ID list. This comes from an error in your XML file when you defined the ID.
Below I posted two sections from your given XML
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/save_filename"
<ListView
android:id="#android:id/list"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:layout_above="#+id/linearLayout"
android:layout_below="#+id/save_filename">
</ListView>
Notice when defining the id, the top one says android:id="#+id/save_filename" while the bottom says android:id="#android:id/list". Also when you use save_file_name it is done like thisandroid:layout_below="#+id/save_filename"This is incorrect. To define an id you use#+id`. This should be done the first time an element is referenced. It tells android to generate a value for it in R.java. Errors like this in your XML can cause your R.java file to not be generated and lead to different problems but I think the extra pluses on the ids are forgivable.
I was getting the error because of how you defined the id for layout. Instead it should look more like this
android:id="#+id/android:list"
Notice the + to create a new id and because I am using ListActivity I also must define it as android:list instead of just list.
I changed your XML to this:
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/save_filename"
android:layout_alignRight="#+id/linearLayout"
android:hint="save here"
android:layout_alignEnd="#id/linearLayout"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_marginBottom="5dp" />
<ListView
android:id="#+id/android:list"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:layout_above="#id/linearLayout"
android:layout_below="#id/save_filename">
</ListView>
Here is some corrected code, I noted what I changed.
package com.example.sosandbox;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.List;
import android.app.ListActivity;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
public class Save extends ListActivity {
String FileName;
EditText et;
//Added some test values
String listItem[]={"1","2","3","4","5"};
ListView listView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(R.layout.activity_save);
Button save = (Button) findViewById(R.id.SAVE); //this is my button
// This is unused so I commented it out
// final EditText title = (EditText) findViewById(R.id.save_filename); //This is unused
final EditText maintext = (EditText) findViewById(R.id.save_filename);
getActionBar().setDisplayUseLogoEnabled(false);
getActionBar().setDisplayHomeAsUpEnabled(true);
et = (EditText) findViewById(R.id.save_filename);
// This is your issue.
// listView = (ListView) findViewById(R.id.list);
// Change it to this because you are using a listActivity
listView = getListView();//I've specified this listView only for the OnItemClickListener action
List values = new ArrayList();
// This won't run because you initilize listItem to an empty array or 0 so 0 < 0 evaluates to false and the loop doesn't run
for (int i = 0; i < listItem.length; i++) {
values.add(listItem[i]);
}
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, values);
setListAdapter(adapter);
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try {
FileName = et.getText().toString() + ".txt";
FileOutputStream fout = openFileOutput(FileName, Context.MODE_PRIVATE);
OutputStreamWriter outsw = new OutputStreamWriter(fout);
try {
outsw.write(String.valueOf(maintext));
outsw.flush();
outsw.close();
Toast.makeText(getBaseContext(), "Your file has been saved", Toast.LENGTH_LONG).show();
} catch (IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
ArrayAdapter<String> adapter = (ArrayAdapter<String>) getListAdapter();
String device;
switch (view.getId()) {
case R.id.SAVE:
List myList = new ArrayList();
device = et.getText().toString();
myList.add(device);
adapter.add(device);
et.setText("");
break;
}
adapter.notifyDataSetChanged();
}
});
//I think this is wrong, I get no error in Java by the way. How could this work if there's a specific extension for my activity that define the listview? **That's my question**.
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// ListView Clicked item index
int itemPosition = position;
// ListView Clicked item value
String itemValue = (String) listView.getItemAtPosition(position);
// Show Alert
Toast.makeText(getApplicationContext(),
"Position :"+itemPosition+" ListItem : " +itemValue , Toast.LENGTH_LONG)
.show();
}
});
}
}

How to make ListView Clickable and delete data from mysql database?

package com.yiqiexample.cc;
import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
//import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
public class Food extends ListActivity
implements OnClickListener {
// Progress Dialog
private ProgressDialog pDialog;
//testing on Emulator:
private static final String READ_COMMENTS_URL = "http://10.0.2.2/pbda2/foodordered.php";
// my ip add 192.168.43.176
//private CheckBox chkFood, chkDrinks, chkServices;
//private Button btnDisplay, chkClear, deliever, chkClearFood, fooddeliever, drinksdeliever, servicesdeliever, chkClearDrinks, chkClearServices;
//private TextView clearThis,orderdisplay, clearThisFood, foodorderdisplay, drinksorderdisplay, servicesorderdisplay, clearThisDrinks, clearThisServices;
private static final String TAG_SUCCESS = "success";
private static final String TAG_POSTS = "posts";
private static final String TAG_SEATNUMBER = "seatnumber";
private static final String TAG_FOODORDERED = "foodordered";
//it's important to note that the message is both in the parent branch of
//our JSON tree that displays a "Post Available" or a "No Post Available" message,
//and there is also a message for each individual post, listed under the "posts"
//category, that displays what the user typed as their message.
//An array of all of our comments
private JSONArray mComments = null;
//manages all of our comments in a list.
private ArrayList<HashMap<String, String>> mCommentList;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(R.layout.food);
View v = findViewById(R.id.backmain);
//set event listener
v.setOnClickListener(this);
View z = findViewById(R.id.drinksbtn);
//set event listener
z.setOnClickListener(this);
View x = findViewById(R.id.servicebtn);
//set event listener
x.setOnClickListener(this);
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
//loading the comments via AsyncTask
new LoadComments().execute();
}
/**
* Retrieves recent post data from the server.
*/
public void updateJSONdata() {
// Instantiate the arraylist to contain all the JSON data.
// we are going to use a bunch of key-value pairs, referring
// to the json element name, and the content, for example,
// message it the tag, and "I'm awesome" as the content..
mCommentList = new ArrayList<HashMap<String, String>>();
// Bro, it's time to power up the J parser
JSONParser jParser = new JSONParser();
// Feed the beast our comments url, and it spits us
//back a JSON object. Boo-yeah Jerome.
JSONObject json = jParser.getJSONFromUrl(READ_COMMENTS_URL);
//when parsing JSON stuff, we should probably
//try to catch any exceptions:
try {
//I know I said we would check if "Posts were Avail." (success==1)
//before we tried to read the individual posts, but I lied...
//mComments will tell us how many "posts" or comments are
//available
mComments = json.getJSONArray(TAG_POSTS);
// looping through all posts according to the json object returned
for (int i = 0; i < mComments.length(); i++) {
JSONObject c = mComments.getJSONObject(i);
//gets the content of each tag
String seatnumber = c.getString(TAG_SEATNUMBER);
String foodordered = c.getString(TAG_FOODORDERED);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_SEATNUMBER, seatnumber);
map.put(TAG_FOODORDERED, foodordered);
// adding HashList to ArrayList
mCommentList.add(map);
//annndddd, our JSON data is up to date same with our array list
}
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public void onClick(View arg0) {
if(arg0.getId() == R.id.backmain){
//define a new Intent for the second Activity
Intent intent = new Intent(this,MainActivity.class);
//start the second Activity
this.startActivity(intent);
}
if(arg0.getId() == R.id.drinksbtn){
//define a new Intent for the second Activity
Intent intent = new Intent(this,Drinks.class);
//start the second Activity
this.startActivity(intent);
}
if(arg0.getId() == R.id.servicebtn){
//define a new Intent for the second Activity
Intent intent = new Intent(this,Services.class);
//start the second Activity
this.startActivity(intent);
}
}
/**
* Inserts the parsed data into the listview.
*/
private void updateList() {
// For a ListActivity we need to set the List Adapter, and in order to do
//that, we need to create a ListAdapter. This SimpleAdapter,
//will utilize our updated Hashmapped ArrayList,
//use our single_post xml template for each item in our list,
//and place the appropriate info from the list to the
//correct GUI id. Order is important here.
ListAdapter adapter = new SimpleAdapter(this, mCommentList,
R.layout.single_comment, new String[] { TAG_SEATNUMBER, TAG_FOODORDERED
//TAG_DRINKSORDERED, TAG_SERVICES
}, new int[] { R.id.seatnumber, R.id.orders
//R.id.drinkstv, R.id.servicestv,
});
// I shouldn't have to comment on this one:
setListAdapter(adapter);
// Optional: when the user clicks a list item we
//could do something. However, we will choose
//to do nothing...
ListView lv = getListView();
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// This method is triggered if an item is click within our
// list. For our example we won't be using this, but
// it is useful to know in real life applications.
//new!
// selected item
String product = ((TextView) view).getText().toString();
// Launching new Activity on selecting single List Item
Intent i = new Intent(getApplicationContext(), SingleListItem.class);
// sending data to new activity
i.putExtra("product", product);
startActivity(i);
//end new lines!!
}
});
}
public class LoadComments extends AsyncTask<Void, Void, Boolean> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Food.this);
pDialog.setMessage("Loading orders...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected Boolean doInBackground(Void... arg0) {
//we will develop this method in version 2
updateJSONdata();
return null;
}
#Override
protected void onPostExecute(Boolean result) {
super.onPostExecute(result);
pDialog.dismiss();
//we will develop this method in version 2
updateList();
}
}
}
single_item.java
package com.yiqiexample.cc;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.TextView;
public class SingleListItem extends Activity{
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.setContentView(R.layout.single_list_item_view);
TextView txtProduct = (TextView) findViewById(R.id.product_label);
Intent i = getIntent();
// getting attached intent data
String product = i.getStringExtra("product");
// displaying selected product name
txtProduct.setText(product);
}
}
single_list_item_view.xml
<?xml version="1.0" encoding="utf-8"?>
<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/product_label"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:textSize="25dip"
android:textStyle="bold"
android:padding="10dip"
android:textColor="#ffffff"/>
</LinearLayout>
food.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:android1="http://schemas.android.com/apk/res/android"
android1:id="#+id/bg2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android1:background="#E0FFFF" >
<Button
android1:id="#+id/btnDelete"
android1:layout_width="wrap_content"
android1:layout_height="wrap_content"
android1:layout_alignParentBottom="true"
android1:layout_alignParentRight="true"
android1:text="#string/delete" />
<Button
android:id="#+id/servicebtn"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_marginLeft="358dp"
android:layout_toRightOf="#+id/foodbutton"
android:text="SERVICES" />
<Button
android1:id="#+id/drinksbtn"
android1:layout_width="wrap_content"
android1:layout_height="wrap_content"
android1:layout_alignParentBottom="true"
android1:layout_marginBottom="23dp"
android1:layout_marginRight="24dp"
android1:text="DRINKS ORDERS" />
<LinearLayout
android:id="#+id/top_layover"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:orientation="horizontal" >
<TextView
android1:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:gravity="center"
android:text="#string/foodtitle"
android:textAppearance="?android:attr/textAppearanceLarge" />
</LinearLayout>
<ListView
android:id="#android:id/list"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/top_layover"
android1:layout_alignBottom="#+id/servicesdelivered"
android:background="#fff"
android:divider="#android:color/transparent"
android:scrollbars="none"
android1:clickable="true" />
<LinearLayout
android:id="#+id/bottom_layover"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:orientation="horizontal"
android:weightSum="2" >
<LinearLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:orientation="vertical" >
</LinearLayout>
<LinearLayout
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:orientation="vertical" >
<Button
android1:id="#+id/backmain"
android1:layout_width="wrap_content"
android1:layout_height="wrap_content"
android1:text="#string/backtomain" />
</LinearLayout>
</LinearLayout>
<Button
android1:id="#+id/servicesdelivered"
android1:layout_width="wrap_content"
android1:layout_height="wrap_content"
android1:layout_above="#+id/drinksbtn"
android1:layout_alignParentLeft="true"
android1:layout_marginLeft="111dp"
android1:text="#string/servicesdelivered"
android1:visibility="invisible" />
</RelativeLayout>
When I tried to click on the listview,
it appears an error -
error opening trace file: No such file or directory (2)
I need help with making the listview clickable and it will intent into a page where I can delete specific data.
define Listview and Myadapter,DatabaseConnection class globaly
adapter
private ListView listview;
private Myadapter adapter;
private DatabaseConnection databaseconnection;
and in oncreate
listview = (ListView) findViewById(R.id.list);
databaseconnection=new DatabaseConnection(this);
adapter=new Myadapter(this,list); // list means pass record as list and create
custom adapter thats best way
listview.setAdapter(adapter);
listview.setOnItemClickListener(new OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> arg0, View arg1,int position, long arg3)
{
//do something here like-
here get the id of record from list using listview position and
detete record from database using dis id
databaseconnection.open(); //create the database object first
deleteRecord(int id); //pass id for delete that record
databaseconnection.close();
}
});
In your code you still not use the list view.First define it globally like
private ListView mList;
Then initialize inside onCreate() like:
mList = (ListView) findViewById(R.id.list);
mList.setAdapter(your_adapter) //this adapter contains the mCommentList arraylist
mList.setOnItemClickListener(new OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> arg0, View arg1,int position, long arg3)
{
//do something here
}
});
Its good if you use an adapter class to set value in your custom layout.
Check this example
Thank you

Android Listview Search filter

I am trying to make a list view search for Android. I have found many tutorials that do just that where
a search-bar is placed at the top and if you type in the box the results get filtered.
In my app I want to click on given items after filtering has been completed, I have implemented setOnItemClickListener. The issue is that after filtering the position of each class that I want to open changes and the incorrect pages open. I was unable to find a solution....
Here is the jave code:
package com.equations.search;
import java.util.ArrayList;
import java.util.HashMap;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
public class EquationsSearch extends Activity {
// List view
private ListView lv;
// Listview Adapter
ArrayAdapter<String> adapter;
// Search EditText
EditText inputSearch;
// ArrayList for Listview
ArrayList<HashMap<String, String>> productList;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.equations_search);
// Listview Data
final String products[] = { "Dell Inspiron", "HTC One X",
"HTC Wildfire S", "HTC Sense", "HTC Sensation XE" };
lv = (ListView) findViewById(R.id.list_view);
inputSearch = (EditText) findViewById(R.id.inputSearch);
// Adding items to listview
adapter = new ArrayAdapter<String>(this,
R.layout.equations_search_list, R.id.product_name, products);
lv.setAdapter(adapter);
/**
* Enabling Search Filter
* */
inputSearch.addTextChangedListener(new TextWatcher() {
public void onTextChanged(CharSequence cs, int arg1, int arg2,
int arg3) {
// When user changed the Text
EquationsSearch.this.adapter.getFilter().filter(cs);
}
public void beforeTextChanged(CharSequence arg0, int arg1,
int arg2, int arg3) {
// TODO Auto-generated method stub
}
public void afterTextChange(Editable arg0) {
// TODO Auto-generated method stub
}
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
}
});
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// if(position == 1)
String openClass = products[position];
if (openClass.equals("HTC Wildfire S")) {
// code specific to first list item
Intent myIntent = new Intent(view.getContext(), A6262.class);
startActivityForResult(myIntent, 0);
}
}
});
}
}
and here is the xml equations_search.xml
<?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="fill_parent"
android:orientation="vertical" >
<!-- Editext for Search -->
<EditText android:id="#+id/inputSearch"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:hint="Search products.."
android:inputType="textVisiblePassword"/>
<!-- List View -->
<ListView
android:id="#+id/list_view"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
</LinearLayout>
and equations_search_list.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<!-- Single ListItem -->
<!-- Product Name -->
<TextView android:id="#+id/product_name"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="10dip"
android:textSize="16dip"
android:textStyle="bold"/>
</LinearLayout>
Thank you in advance.
Rather than products[position], use adapter.getItem(position). When the ListView is not in filter mode, those two things will be the same. But, in filter mode, getItem() will take the filtering into account.
The ListAdapter will change the relative position of the items it currently shows due to the filtering. You should always use getItem(position) to retrieve the correct item.

Cannot read EditText in fragment class

I have two tabs and each tab is a Fragment. In one of the fragments (Afragment.claas) I have a dialog box to insert some data, and I want to save them in a database. When I fill the text fields and press OK, the application stops.
I think when I initialize the edittext there is something wrong.
name = (EditText) activity.findViewById(R.id.etProviderName);
The above statement is returning null
Here is my code:
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ListFragment;
import android.content.DialogInterface;
import android.database.Cursor;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.CursorAdapter;
import android.widget.EditText;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.Toast;
public class Afragment extends ListFragment {
DBAdapter db;
Activity activity;
private static final String fields[] = { "provider._providerName", "_providerMobile" };
#Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
initAdapter();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_add:
add();
return (true);
case R.id.menu_reset:
initAdapter();
return (true);
case R.id.menu_info:
Toast.makeText(activity, "Developed By Omar Al-Shammary", Toast.LENGTH_LONG)
.show();
return (true);
}
return (super.onOptionsItemSelected(item));
}
private void add() {
// TODO Auto-generated method stub
System.out.println("insider Add Method");
final View addView = activity.getLayoutInflater().inflate(R.layout.add_provider, null);
new AlertDialog.Builder(activity).setTitle("Add a Provider").setView(addView)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
System.out.println("Befor calling insert in providers");
insertInProviders();
System.out.println("after calling insert in providers");
}
}).setNegativeButton("Cancel", null).show();
initAdapter();
}
private void initAdapter() {
activity = getActivity();
db = new DBAdapter(activity);
fillTheList();
}
public void fillTheList()
{
db.open();
Cursor data = db.getAllProviders();
CursorAdapter dataSource = new SimpleCursorAdapter(activity,
R.layout.row, data, fields,
new int[] { R.id.first, R.id.last });
setListAdapter(dataSource);
db.close();
setListAdapter(dataSource);
}
public void insertInProviders()
{
EditText name,location,number;
name = (EditText) activity.findViewById(R.id.etProviderName);
location = (EditText) activity.findViewById(R.id.etProviderName);
number = (EditText) activity.findViewById(R.id.etProviderName);
if(name == null)
System.out.println("EditeText name is null");
String provName = name.getText().toString();
if(location == null)
System.out.println("location is null");
String provLocation = location.getText().toString();
String provNumber = number.getText().toString();
System.out.println("Before Open");
db.open();
System.out.println("Before DB.Insert");
db.insertProvider(provName, provLocation, provNumber);
System.out.println("Before Close");
db.close();
}
}
add_provider.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/tvProviderName"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Name" />
<EditText
android:id="#+id/etProviderName"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="textPersonName" >
<requestFocus />
</EditText>
<TextView
android:id="#+id/tvProvLocation"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Location" />
<EditText
android:id="#+id/etProvLocation"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="textPersonName" />
<TextView
android:id="#+id/tvProvNumber"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Number" />
<EditText
android:id="#+id/etProvNumber"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="number" />
</LinearLayout>
This is the code I use for declaring buttons in Fragments - maybe it can help you.
What I would do is access the inflated layout and then you should be able to access items underneath it. Let me know if that makes sense.
LinearLayout theLayout = (LinearLayout)inflater.inflate(R.layout.tab_frag1_layout, container, false);
// Register for the Button.OnClick event
Button b = (Button)theLayout.findViewById(R.id.frag1_button);
#Override
public void onClick(View v) {
Toast.makeText(Tab1Fragment.this.getActivity(), "OnClickMe button clicked", Toast.LENGTH_LONG).show();
}
});
return theLayout;
So maybe you should try this since you inflate your View as "addView"
name = (EditText) addView.findViewById(R.id.etProviderName);
The findViewById should not be called by the activity but by the enclosing view. You should have something like:
In the class
View aView;
In the method:
LayoutInflater inflater = getActivity().getLayoutInflater();
aView = inflater.inflate(R.layout.add_provider, null);
...
EditText name = (EditText) aView.findViewById(R.id.etProviderName);
I hope it helps.

Categories

Resources