I have a spinner consisting of the languages in the IBM library. I want the user to select a language and translate the text into the selected language. I got the value from spinner but I don't know how to pass the value to the target language. Please help.
`enter code here`Spinner s = (Spinner) findViewById(R.id.spinner1);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_spinner_item, languages);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
s.setAdapter(adapter);
text = s.getSelectedItem().toString(); // value from spinner
new Hey().execute();
}
class Hey extends AsyncTask<Void, Void, String> {
String text;
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(Void... voids) {
IamAuthenticator authenticator = new IamAuthenticator("nAh_Z_0X2AS1Vun2MI3UR3lYNRivFRkWaNsZyFwELMul"); //key
LanguageTranslator languageTranslator = new LanguageTranslator("2018-05-01", authenticator);
languageTranslator.setServiceUrl("https://api.eu-gb.language-translator.watson.cloud.ibm.com/instances/83f66689-1c94-4a9b-b595-e2d776f10ded"); //url
TranslateOptions translateOptions = new TranslateOptions.Builder()
.addText("Hello")
.source(Language.ENGLISH)
.target(Language.SPANISH) // need to get user to select the target language from the spinner option
.build();
TranslationResult result = languageTranslator.translate(translateOptions) //translation happens
.execute().getResult();
String som = result.toString();
System.out.println(som);
return som;
}
First You need to understand how could you pass the value as a parameter to the AsyncTask. So after taking the value from spinner pass it to AsyncTask parameter.
Your code will look like this:
text = s.getSelectedItem().toString(); // value from spinner
new Hey().execute(text);
Now in the AsyncTask you will retrieve the passed parameter:
class Hey extends AsyncTask<Void, Void, String> {
String text;
#Override
protected String doInBackground(Void... voids) {
String language = (String) params[0]; //can use it further
TranslateOptions translateOptions = new TranslateOptions.Builder()
.addText("Hello")
.source(Language.ENGLISH)
.target(language) // Do check the input format for this and do required conversion
.build();
}
}
Related
I'm aware that this is very simple question but I'm a newbie in Android development so please go easy on me.
Problem that I have is in one of the fragments (AsyncTask specifically) that lays in my main activity.
AsyncTask sends out data to php script which then returns according data in json format. This is then processed and saved to jsonlist array. Up until post execute everything works fine data is downloaded, processed etc. However when program reaches post execute problems start to pop out. And basically i'm unable to list out all the data from jsonlist to listview
//setting up an array
ArrayList<HashMap<String, String>> jsonlist = new ArrayList<HashMap<String, String>>();
//creating list view variable
ListView listview;
//Define work in progress dialog
private ProgressDialog mProgressDialog;
private class ProgressTask extends AsyncTask<String, Void, Boolean> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Create a progressdialog
mProgressDialog = new ProgressDialog(getActivity());
// Set progressdialog title
mProgressDialog.setTitle("Please wait");
// Set progressdialog message
mProgressDialog.setMessage("Fetching data...");
mProgressDialog.setIndeterminate(false);
}
#Override
protected Boolean doInBackground(String... params) {
//To do in the background
//Define variable of JSON parser type
JSONParser jParser = new JSONParser();
//Pass url to json parser class to fetch and save it into array variable
JSONArray json = jParser.getJSONFromUrl(url);
//loop from 0 to length of an array by increasing by 1
for (int i = 0; i < json.length(); i++) {
//Try and catch routine to prevent any crashes
try {
//Get an object defined in { ... } in original json file
JSONObject c = json.getJSONObject(i);
//Separate object by obtaining values for each of the sections
String vtitle = c.getString(title);
String vcontent = c.getString(content);
String vuser = c.getString(user);
HashMap<String, String> map = new HashMap<String, String>();
//Fill up an array with data extracted
map.put(title, vtitle);
map.put(content, vcontent);
map.put(user, vuser);
//Add values into jsonlist
jsonlist.add(map);
} catch (JSONException e)
{
//In case of any error Stack trace will be returned
e.printStackTrace();
}
}
//Once everything has been done return null value
return null;
}
#Override
protected void onPostExecute(Boolean aBoolean) {
//Insert all data downloaded through list adapter
ListAdapter adapter = new SimpleAdapter(getActivity(), jsonlist, R.layout.list_activity, new String[] { title, content, user }, new int[] { R.id.title, R.id.content, R.id.user });
// Locate the listview
//listview = (ListView) findViewById(R.id.list);
// Set the adapter to the ListView
//listview.setAdapter(adapter);
//Get rid off dialog when operation of fetching data has been done
if (mProgressDialog.isShowing()) {
mProgressDialog.dismiss();
}
}
}
As you can see i have tried the commented code but listview = (ListView) findViewById(R.id.list); returns following error:
Cannot resolve method findViewById(int)
which prevents me from executing program. This is very upsetting because I literally have all the data i need in an array but only one line of code stops me from displaying it.
I have also tried:
ListAdapter adapter = new SimpleAdapter(context, jsonlist, R.layout.list_activity, new String[] { title, content, user }, new int[] { R.id.title, R.id.content, R.id.user });
setListAdapter(adapter);
lv = getListView();
But as in previous case error of unresolved method is returned. Which is due to the fact that fragment is extended by fragment and adding anything to it crashes it
public class Fragment2 extends Fragment, ListActivity {...}
Add this to your code in Fragment2 class.
private ListView listview;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.YOUR_FRAGMENT_LAYOUT, container, false);
listview = (ListView) v.findViewById(R.id.R.id.list);
return v;
}
Since you are in a Fragment you have to call getView() before findViewById, like this
//Insert all data downloaded through list adapter
ListAdapter adapter = new SimpleAdapter(getActivity(), jsonlist, R.layout.list_activity, new String[] { title, content, user }, new int[] { R.id.title, R.id.content, R.id.user });
// Locate the listview
listview = (ListView) getView().findViewById(R.id.list);
I am building an mobile app in where a user logs in and it outputs the contents of my database table which is named "announcements".
What I'm trying to do is to filter out these output based on the "department" column from the "accounts" table in which the users are stored.
The "announcements" table has the column named "receiver".
The contents will only show if the "department" column of the user logged in has the same value as the "receiver column" of the "announcements" column or if the value of the receiver is "all".
How do I do this?
My PHP script
<?php
$host="localhost"; //replace with database hostname
$username="root"; //replace with database username
$password=""; //replace with database password
$db_name="sunshinedb"; //replace with database name
$con=mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
$sql = "select * from announcement";
$result = mysql_query($sql);
$json = array();
if(mysql_num_rows($result)){
while($row=mysql_fetch_assoc($result)){
$json['services'][]=$row;
}
}
mysql_close($con);
echo json_encode($json);
?>
Java class
JSONObject jsonobject;
JSONArray jsonarray;
ListView listview;
ArrayList<HashMap<String, String>> arraylist;
ProgressDialog mProgressDialog;
JSONParser jsonParser = new JSONParser();
String email;
String[] services;
private String url = "http://10.0.3.2/sunshine-ems/services.php";
String user_id;
// ALL JSON node names
private static final String TAG_TRANS_ID = "announcement_id";
private static final String TAG_DATE = "date";
private static final String TAG_SERVICES = "title";
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.videos_layout);
// get listview
ListView lv = getListView();
lv.setOnItemClickListener(new android.widget.AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View view, int arg2,
long arg3) {
Intent i = new Intent(getApplicationContext(),
Single_List.class);
String transaction_id = ((TextView) view
.findViewById(R.id.transac_id)).getText().toString();
i.putExtra("announcement_id", transaction_id);
startActivity(i);
}
});
new DownloadJSON().execute();
}
// DownloadJSON AsyncTask
private class DownloadJSON extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Create a progressdialog
mProgressDialog = new ProgressDialog(VideosActivity.this);
// Set progressdialog title
mProgressDialog.setTitle("Loading Services");
// Set progressdialog message
mProgressDialog.setMessage("Loading...");
mProgressDialog.setIndeterminate(false);
// Show progressdialog
mProgressDialog.show();
}
#Override
protected String doInBackground(String... params) {
JSONObject json = JSONfunctions.getJSONfromURL(url);
// Check your log cat for JSON reponse
Log.d("Service history ", json.toString());
// Create the array
arraylist = new ArrayList<HashMap<String, String>>();
try {
// Locate the array name
jsonarray = json.getJSONArray("services");
for (int i = 0; i < jsonarray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
json = jsonarray.getJSONObject(i);
String transac_id = json.getString(TAG_TRANS_ID);
String date = json.getString(TAG_DATE);
String service = json.getString(TAG_SERVICES);
// Retrive JSON Objects
map.put(TAG_SERVICES, service);
map.put(TAG_DATE, date);
map.put(TAG_TRANS_ID, transac_id);
// 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(String file_url) {
mProgressDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
VideosActivity.this, arraylist,
R.layout.listview_services, new String[] {
TAG_TRANS_ID, TAG_SERVICES, TAG_DATE },
new int[] { R.id.transac_id, R.id.txt_service,
R.id.txt_date });
// updating listview
setListAdapter(adapter);
}
});
}
}
You are not making any filtering anywhere in your code...
The steps to do it should be these ones (in this order) :
Android side : Calling your webservice (PHP code) with the user's department (in GET or POST parameter)
WS side : Requesting your database with something like SELECT * FROM announcement WHERE receiver = '<department'> OR receiver = 'ALL' where department is the user's department
WS side : Construct the JSON response
Android side : Process the JSON response to display results
The advantages of making it like this :
Limit the number of data transfered (limit network consumption on the Android device and you limit the load on your PHP server)
Limit the number of data processed Android side (limit the load of the Android app : it's not a desktop app ! Never forgive it !)
PS : reading your post and your comment, I really think you should look into these points before starting to make your app : SQL request, PHP MySQL access (as pointed out by #Jay Blanchard), Web services and HTTP protocol, Android AsyncTask
I was looking at this code while surfing through Stackoverflow
CODE::
public class MainActivity extends Activity {
// Declare Variables
JSONObject jsonobject;
JSONArray jsonarray;
ListView listview;
ListViewAdapter adapter;
ProgressDialog mProgressDialog;
ArrayList<HashMap<String, String>> arraylist;
static String NAME = "rank";
static String TYPE = "country";
static String DISTANCE = "distance";
static String RATING = "rating";
static String FLAG = "flag";
static String PRICE= "price";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Get the view from listview_main.xml
setContentView(R.layout.listview_main);
// Locate the listview in listview_main.xml
listview = (ListView) findViewById(R.id.listview);
// Execute DownloadJSON AsyncTask
new DownloadJSON().execute();
}
// DownloadJSON AsyncTask
private class DownloadJSON extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Create a progressdialog
mProgressDialog = new ProgressDialog(MainActivity.this);
// Set progressdialog title
//mProgressDialog.setTitle("Fetching the information");
// Set progressdialog message
mProgressDialog.setMessage("Loading...");
mProgressDialog.setIndeterminate(false);
// Show progressdialog
mProgressDialog.show();
}
#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("--------------URL----------");
try {
// Locate the array name in JSON
jsonarray = jsonobject.getJSONArray("ARRAY");
for (int i = 0; i < jsonarray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
jsonobject = jsonarray.getJSONObject(i);
// Retrive JSON Objects
map.put(MainActivity.NAME, jsonobject.getString("collegeNAME"));
map.put(MainActivity.TYPE, jsonobject.getString("collegeTYPE"));
map.put(MainActivity.FLAG, jsonobject.getString("collegeIMAGE"));
map.put(MainActivity.DISTANCE, jsonobject.getString("collegeDISTANCE"));
map.put(MainActivity.RATING, jsonobject.getString("collegeRATING"));
map.put(MainActivity.PRICE, jsonobject.getString("collegePrice"));
// 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) {
// Pass the results into ListViewAdapter.java
adapter = new ListViewAdapter(MainActivity.this, arraylist);
// Set the adapter to the ListView
listview.setAdapter(adapter);
// Close the progressdialog
mProgressDialog.dismiss();
}
}
}
My Question is Why we use collection in android ?
What is the use ?
Why a hashmap is added to ArrayList in the above code ?
Can't we directly set views in android without collection,( I tried
it dosent work when dealing with group of key,value pairs)
.
~ I am a newbie so please go easy on with answers to my questions
I'm not sure how to answer your first 2 questions about collections... but I'll give it a shot.
1, 2) Collections are good for keeping groups of information lumped together and accessible through 1 variable. They also make it very easy to iterate over them, which makes them ideal for things like ListView adapters since that is also a list (or a collection).
Consider the following if you dont have an array
String var1 = "hi1";
String var2 = "hi2";
String var3 = "hi3";
String var4 = "hi4";
String var5 = "hi5";
String var6 = "hi6";
String var7 = "hi7";
String var8 = "hi8";
String var9 = "hi9";
// do something with the variables
Toast.makeText(this, var1, Toast.LENGTH_SHORT).show();
Toast.makeText(this, var2, Toast.LENGTH_SHORT).show();
Toast.makeText(this, var3, Toast.LENGTH_SHORT).show();
Toast.makeText(this, var4, Toast.LENGTH_SHORT).show();
Toast.makeText(this, var5, Toast.LENGTH_SHORT).show();
Toast.makeText(this, var6, Toast.LENGTH_SHORT).show();
Toast.makeText(this, var7, Toast.LENGTH_SHORT).show();
Toast.makeText(this, var8, Toast.LENGTH_SHORT).show();
Toast.makeText(this, var9, Toast.LENGTH_SHORT).show();
Now consider this, if you have arrays:
ArrayList<String> vars = new ArrayList<String(9);
for (int i = 1; i <= 9; i++)
{
vars.add("hi" + i);
Toast.makeText(this, vars.get(i), Toast.LENGTH_SHORT).show();
}
Much, much easier to work with.
3) The Hashmap is added to the array because the author wanted to keep a collection of separate name/value pairs. You can't have multiple keys with the same value in a Hashmap, so if you want that then you have to make a new Hashmap. The adding them to an array was to keep it neat, and then allowed the author to pass the array to a ListView adapter for displaying the values to the user using Android's built-in mechanism.
Basically the author created this Hierarchy:
item1
name
type
flag
distance
rating
price
item2
name
type
flag
distance
rating
price
item3
name
type
flag
distance
rating
price
...etc...
So when the ListView iterated over the array, each separate collection of hashmap values will be available to a new listview item for displaying.
4) You can set values directly, but working with adapters in ListViews makes it much less of a chore. You create an array, pass the array to the listview, and bada-bing-bada-boom, there's your list. Otherwise you will be creating ListView items and setting the display text all yourself for each item. In a similar way to why collections are useful when you have many variables of the same type, passing that collection to a ListView makes it much, much easier to code, maintain, and troubleshoot, not to mention that it just works!
I hope this helps! We are all beginners once :)
This piece of code will go populate an ListView, there are several ways to do that. I believe in this case, the coder is SimpleAdapter http://developer.android.com/reference/android/widget/SimpleAdapter.html.
Some think like:
// In This case the value os NAME is shown on android.R.id.text1 (TextView)
// and PRICE is shown on android.R.id.text2 (TextView)
String[] from = new String[]{MainActivity.NAME, MainActivity.PRICE}; // Map keys
int[] to = new int[]{android.R.id.text1, android.R.id.text2}; // List Layout item views
SimpleAdapter adapter = new SimpleAdapter(context, arraylist, android.R.layout.simple_list_item_2, String[] from, int[] to);
listview.setAdapter(adapter);
i want to pass tow values from activity to AsyncTask class and send them from Background process to SOAP web service , but it return my null or wrong , i'm sure there is something wrnog in passing value from LoginActivity to AsyncTask .
here is my LoginActivity code :
final EditText LoginId = (EditText) findViewById(R.id.IDLogin);
final EditText LoginPass = (EditText) findViewById(R.id.LoginPass);
contextOfApplication = getApplicationContext();
mPrefs = getSharedPreferences(PREFS, 0);
boolean rememberMe = mPrefs.getBoolean("rememberMe", false);
final String login1 = LoginId.getText().toString();
final String pass1 = LoginPass.getText().toString();
SharedPreferences prefs = PreferenceManager
.getDefaultSharedPreferences(LoginActivity.this);
prefs.edit().putString("login1", login1).commit();
prefs.edit().putString("password1", pass1).commit();
here is calling and passing activity context to AsyncTask Constractor :
loginBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
ProgressDialog progressDialog = new ProgressDialog(
LoginActivity.this);
progressDialog.setMessage("جاري تسجيل الدخول الرجاء الانتظار");
progressDialog.show();
AsyncTaskWebServiceCaller MyTask = new AsyncTaskWebServiceCaller(
LoginActivity.this, progressDialog,
getApplicationContext());
MyTask.execute();
}
});
my FULL AsyncTask code :
public class AsyncTaskWebServiceCaller extends AsyncTask<Void, Void, String> {
Activity mActivity;
Context context;
LoginActivity MyClass = new LoginActivity();
public static Context contextOfApplication;
ProgressDialog progressDialog;
Context applicationContext = LoginActivity.getContextOfApplication();
// Constractor
public AsyncTaskWebServiceCaller(Activity activity,
ProgressDialog progressDialog, Context context) {
super();
this.progressDialog = progressDialog;
this.mActivity = activity;
this.context = context;
}
// BackGround Process
#Override
protected String doInBackground(Void... voids) {
// this is executed in a background thread.
// the result is returned to the UI thread via onPostExecute
try {
final String NAMESPACE = "http://ws.sams.com";
final String URL = "http://88.198.82.92:8080/sams1/services/LoginActvityWs?WSDL"; // usint
// //
// localhost
final String METHOD_NAME = "login";
final String SOAP_ACTION = "http://ws.sams.com/login";
final SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
SoapEnvelope.VER11);
final HttpTransportSE androidHttpTransport = new HttpTransportSE(
URL);
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(applicationContext);
String user = prefs.getString("login1", null);
String pass = prefs.getString("password2", null);
to pass values to AsyncTask subclass you either :
1- pass them throw a constructor :
class MyTask extends AsyncTask<Void,Void,Void>{
MyObject myObject = null;
public MyTask(MyObject myObject){
this.myObject = myObject;
}
//....
2- pass it in the execute() method parameters :
// your code on the Main thread which will call the execute() method
// ....
new MyTask().execute(myObject); // i dont remember the exact name of this method, any way
and snippets from your AsyncTask subClass will be
class MyTask extends AsyncTask<Void,MyObject,Void>{
#Override
public void doInBackGround(MyObject...params){
MyObject myObject = params[0];
// the rest of your code
}
just put in mind that if you want to do or edit any thing that is running on the UI thread, you
cant do it in the "doInBackground()" method, either on the preExecute() or the postExecute(), or
run it in a Runnable object (inside the doInBackground() method) but by calling runOnUI(myRunnable);
hope this helps, and just i cant remember the methods name for now, just CTRL + SPACE will help on your IDE :D
you are already doing it in your constructor
AsyncTaskWebServiceCaller MyTask = new AsyncTaskWebServiceCaller(
LoginActivity.this, progressDialog,
getApplicationContext());
thats passing values there
also you are passing the context twice LoginActivity.this gives you context and activity so you do not need to use getApplicationContext(). Its recommended that you never use getApplicationContext() really
Edit:
if you want context all you have to do is
public AsyncTaskWebServiceCaller(Context context,ProgressDialog progressDialog) {
super();
this.progressDialog = progressDialog;
this.context = context;
}
you do not need the activity
to use shared preferences all you need to do is
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
I am using a save button in my application. When I click on save button, I want it to validate each field and display an error message like "Please enter this field", "Please enter in correct format in this field" or "Please select this".
I have 8 EditText boxes and 2 spinners and on TextView having ListView. In Android, how to use field validation on every field and after validating each field it save data successfully.
My java code is:
public class non_ticket_task extends Activity implements OnItemSelectedListener{
public static String complain_date;
public static String complain_time;
public static String job_performed;
// public static String time;
public static String next_due_on;
static TelephonyManager tm;
// Progress Dialog
private ProgressDialog pDialog;
JSONParser jsonParser = new JSONParser();
TextView cus_name_txt;
EditText complain_date_txtbx;
EditText complain_time_txtbx;
EditText job_performed_txtbx;
EditText date_txtbx;
EditText lat_txtbx;
EditText lon_txtbx;
EditText next_due_on_txtbx;
Button btnadd;
// url to create new product
private static String url_create_task = "http://192.168.2.1/android_connect/create_product.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.non_ticket_task);
this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
tm = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
// Buttons
btnadd = (Button) findViewById(R.id.addbtn);
// button click event
btnadd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// creating new task in background thread
new CreateNewTask().execute();
}
});
cus_name_txt = (TextView)findViewById(R.id.textView1);
cus_name_txt.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Onclick_click1(cus_name_txt);
}
});
complain_date_txtbx = (EditText) findViewById(R.id.complain_date_txt);
complain_date_txtbx.setText(non_ticket_task.complain_date);
complain_time_txtbx = (EditText) findViewById(R.id.complain_time_txt);
complain_time_txtbx.setText(non_ticket_task.complain_time);
job_performed_txtbx = (EditText) findViewById(R.id.job_performed_txt);
job_performed_txtbx.setText(non_ticket_task.job_performed);
date_txtbx = (EditText) findViewById(R.id.date_txt);
date_txtbx.setText(" "
+ String.valueOf(java.text.DateFormat.getDateTimeInstance()
.format(Calendar.getInstance().getTime())));
MyLocation loc = new MyLocation(this.getApplicationContext());
lon_txtbx = (EditText) findViewById(R.id.lon_txt);
lon_txtbx.setText(String.valueOf(loc.lon));
lat_txtbx = (EditText) findViewById(R.id.lat_txt);
lat_txtbx.setText(String.valueOf(loc.lat));
next_due_on_txtbx = (EditText) findViewById(R.id.next_due_on_txt);
next_due_on_txtbx.setText(non_ticket_task.next_due_on);
Spinner status = (Spinner) findViewById(R.id.status_spinner);
// Create an ArrayAdapter using the string array and a default spinner layout
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this,
R.array.Status_array, android.R.layout.simple_dropdown_item_1line);
// Specify the layout to use when the list of choices appears
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// Apply the adapter to the spinner
status.setAdapter(adapter);
Spinner severity = (Spinner) findViewById(R.id.severity_spinner);
// Create an ArrayAdapter using the string array and a default spinner layout
ArrayAdapter<CharSequence> adapter1 = ArrayAdapter.createFromResource(this,
R.array.Severity_array, android.R.layout.simple_dropdown_item_1line);
// Specify the layout to use when the list of choices appears
adapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
// Apply the adapter to the spinner
severity.setAdapter(adapter1);
}
public void onItemSelected(AdapterView<?> parent, View view,
int pos, long id) {
// An item was selected. You can retrieve the selected item using
// parent.getItemAtPosition(pos)
}
public void onNothingSelected(AdapterView<?> parent) {
// Another interface callback
}
public void Onclick_click1(final TextView cus_name_txt)
{
final TextView txtbx = (TextView) cus_name_txt;
if(cus_name_txt.getId()==R.id.textView1)
{
final CharSequence[] items = {"Ali Asghar","Ali Shah","Tamseel","Bilal","Daniyal","Muzamil","Faraz","Uzair","Mohsin","Mehran","Babar","Ameen","Zeeshan","Maqsood","Hasan","Taqi","Talib","Asif","Mudasir"};
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Customers Name");
//builder.setI
builder.setItems(items, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
//Toast.makeText(getApplicationContext(), con.get(item).getCountrName(), Toast.LENGTH_SHORT).show();
txtbx.setText(items[item]);
System.out.println("Item is: "+items[item]);
/*CONTRY_ID = con.get(item).getCountryId();
stateET.requestFocus();*/
}
});
builder.show();
}
}
/**
* Background Async Task to Create new product
* */
class CreateNewTask extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(non_ticket_task.this);
pDialog.setMessage("Saving Details..");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/**
* Creating task
* */
protected String doInBackground(String... args) {
String cus_name = cus_name_txt.getText().toString();
String complain_date = complain_date_txtbx.getText().toString();
String complain_time = complain_time_txtbx.getText().toString();
String job_performed = job_performed_txtbx.getText().toString();
String date = date_txtbx.getText().toString();
String next_due_on = next_due_on_txtbx.getText().toString();
String lat = lat_txtbx.getText().toString();
String lon = lon_txtbx.getText().toString();
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("cus_name", cus_name));
params.add(new BasicNameValuePair("complain_date", complain_date));
params.add(new BasicNameValuePair("complain_time", complain_time));
params.add(new BasicNameValuePair("job_performed", job_performed));
params.add(new BasicNameValuePair("date", date));
params.add(new BasicNameValuePair("next_due_on", next_due_on));
params.add(new BasicNameValuePair("lat", lat));
// getting JSON Object
// Note that create product url accepts POST method
JSONObject json = jsonParser.makeHttpRequest(url_create_task,
"POST", params);
// check log cat fro response
Log.d("Create Response", json.toString());
// check for success tag
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// successfully created product
Intent i = new Intent(getApplicationContext(), My_Task.class);
startActivity(i);
// closing this screen
finish();
} else {
// failed to create product
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog once done
pDialog.dismiss();
}
}
Frankly speaking the validation process largely depends upon what you want to validate and how. For example if you want to validate the text of an edittext just after leaving the focus or only after clicking the submit button. TextWatchers can serve the purpose for a fast and user friendly validation. However if you want to validate on click of a Button, You can have a function like
boolean void validateInput(){
boolean retStatus=false;
if((textView1.getText().length()==0 || textView1.getText().equals("") && (any other condition )){
retStatus=true;
textView1.setError("You have entered wrong value in textView 1");
}
//similarly for other controls
------
-----
--
return retStatus;
}
If you want to use immediate error detection the error checking (and correction) will be fast instead methods like above can show "all at once" errors. You can decide whichever suits to your users.
For reducing user input errors use text type for edittexts i.e. use numeric for editText for phone number, alphabets for Names or type emailid for emails etc. Use hints to indicate users what they are supposed to do in that EditText i.e. enter your email id here.
Happy Coding!!
Hi if I understand you very well you just want to make sure you give feedback to users to type something in the EditText. If that is what you want, then you only need to check the lenght of the EditText.getText like so:
if (cus_name_txt.getText().Lenght()==0){
//Your message here
}
Hope this helps.
In onPreExecute you do the validations. If a field is empty(or wrong) you set to that field an error message. If there are one or more invalid fields, you cancel the AsyncTask and show the error. After the user fixes the errors, it can press Save again.
You should take the string from the fields in onPreExecute, not in doInBackground, because you cannot make modifications in the Ui from that method.
You can make a function validatefields() like this and call this function in like this
if(validate()){
new CreateNewTask().execute()
}
else{
showErrorMsg(msg);
}
where validate function will be like this
private boolean validate(){
boolean retStatus=false;
if((textView1.getText().length()==0 || textView1.getText().equals("") ){
retStatus=false;
msg = "Please fill TextView 1";
}
else if ( ---check other 9 condition in the same way--)
}
if ( !msg.equals("")){
return false;
}
else {
return true;
}
}