In my effort to get a simple address auto complete on android using geocoder, I tried to my patience and finally decided to ask out for help.
original code reference : Geocoder autocomplete in android
So in the below code, all that is happening is trying to auto complete the address as the user types in the autoCompleteTextView. I am calling the function doing the actual work in runOnUiThread,hoping that the UI would not freeze, as the user types in. However the UI freezes after the Threshold (3 characters) and the drop down of the possible addresses appear at it its own pace and not always.
If you guys can tell me where I am going wrong.... thanks in advance
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.location.Address;
import android.location.Geocoder;
import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
public class AlarmActivity extends Activity implements TextWatcher {
private static final int THRESHOLD = 3;
private String latitude, longitude;
private List<Address> autoCompleteSuggestionAddresses;
private ArrayAdapter<String> autoCompleteAdapter;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.hw);
setDefaultKeyMode(DEFAULT_KEYS_SEARCH_LOCAL);
autoCompleteAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_dropdown_item_1line, new ArrayList<String>());
autoCompleteAdapter.setNotifyOnChange(false);
AutoCompleteTextView locationinput = (AutoCompleteTextView) findViewById(R.id.locationInput);
locationinput.addTextChangedListener(this);
locationinput.setOnItemSelectedListener(this);
locationinput.setThreshold(THRESHOLD);
locationinput.setAdapter(autoCompleteAdapter);
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
}
#Override
public void onTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) {
final String value = arg0.toString();
if (!"".equals(value) && value.length() >= THRESHOLD) {
Thread t = new Thread() {
public void run() {
try {
runOnUiThread(new Runnable() {
public void run() {
notifyResult(value);
}
});
} catch (Exception e) {}
}
};
t.start();
} else {
autoCompleteAdapter.clear();
}
}
#Override
public void afterTextChanged(Editable arg0) {
}
private void notifyResult(String value) {
try {
autoCompleteSuggestionAddresses = new Geocoder(getBaseContext()).getFromLocationName(value, 10);
//notifyResult(autoCompleteSuggestionAddresses);
latitude = longitude = null;
autoCompleteAdapter.clear();
for (Address a : autoCompleteSuggestionAddresses) {
Log.v("Nohsib", a.toString());
String temp = ""+ a.getFeatureName()+" "+a.getCountryName()+" "+a.getPostalCode();
autoCompleteAdapter.add(temp);
}
autoCompleteAdapter.notifyDataSetChanged();
} catch (IOException ex) {
// Log.e(GeoCoderAsyncTask.class.getName(), "Failed to get autocomplete suggestions", ex);
}
}
}
I believe the reason the UI is freezing is because even though you are calling notifyResult from a separate thread, it is still being run on the UI thread. What will fix this is to instead use an AsyncTask
Something like:
private class GetSuggestions extends AsyncTask<String, Void, Void> {
protected Long doInBackground(String... search) {
value = search[0];
try {
autoCompleteSuggestionAddresses = new Geocoder(getBaseContext()).getFromLocationName(value, 10);
//notifyResult(autoCompleteSuggestionAddresses);
latitude = longitude = null;
autoCompleteAdapter.clear();
for (Address a : autoCompleteSuggestionAddresses) {
Log.v("Nohsib", a.toString());
String temp = ""+ a.getFeatureName()+" "+a.getCountryName()+" "+a.getPostalCode();
autoCompleteAdapter.add(temp);
}
} catch (IOException ex) {
// Log.e(GeoCoderAsyncTask.class.getName(), "Failed to get autocomplete suggestions", ex);
}
}
protected void onPostExecute(Long result) {
autoCompleteAdapter.notifyDataSetChanged();
}
}
and then you can start the task by calling new GetSuggestions().execute(value);
Related
I am creating an eWallet application like many existing ones. I have lots of classes that do different stuff but i need some advice in a group of them. I have created a listview witch fetches the categories i have created and saved in a phpMyAdmin database. I am displaying this data on a list view successfully. This list view just shows the list of the categories to the user and if he clicks a list item a new activity appers which llows him to edit or delete the list item.
Now i used the same code (i lterally used the same code!) to create a second listview inside a dialog box. Imagine that this listview appears inside the dialog box when i click an edit text which has an on click listener. I successfully display the data in this second list view as well. Now on this dialog box when i click a list item/category (lets say Sports category) i want the name of the edit text to change to the category i chose. But i am confused because i use the same code and methods that open the edit and delete activity on my first list view. I hope i did not confuse you too much.
Here is the code that downloads the data in my list views.
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.widget.ListView;
import android.widget.Toast;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class ExDownloaderActivity extends AsyncTask<Void, Integer, String>
{
Context context;
String address;
ListView expenseListView;
ProgressDialog progressDialog;
public ExDownloaderActivity(Context context, String address, ListView exCategoryListView)
{
this.context = context;
this.address = address;
this.expenseListView = exCategoryListView;
}
//B4 JOB STARTS
#Override
protected void onPreExecute()
{
super.onPreExecute();
progressDialog = new ProgressDialog(context);
progressDialog.setTitle("Fetch Data");
progressDialog.setMessage("Fetching Data...Please wait");
progressDialog.show();
}
#Override
protected String doInBackground(Void... params)
{
String data = downloadData();
return data;
}
#Override
protected void onProgressUpdate(Integer... values)
{
super.onProgressUpdate(values);
}
#Override
protected void onPostExecute(String string)
{
super.onPostExecute(string);
progressDialog.dismiss();
if(string != null)
{
ExParserActivity parser = new ExParserActivity(context, string, expenseListView);
parser.execute();
}
else
{
Toast.makeText(context, "Unable to download data",Toast.LENGTH_LONG).show();
}
}
private String downloadData()
{
//connect and get a stream of data
InputStream inputStream = null;
//to store each line
String line = null;
try
{
URL url = new URL(address);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
inputStream = new BufferedInputStream(httpURLConnection.getInputStream());
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
StringBuffer stringBuffer = new StringBuffer();
if(bufferedReader!= null)
{
while ((line = bufferedReader.readLine()) != null)
{
stringBuffer.append(line + "\n");
}
}
else
{
return null;
}
return stringBuffer.toString();
}
catch (MalformedURLException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
finally
{
if(inputStream != null)
{
try
{
inputStream.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
return null;
}
}
Second Class
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.support.design.widget.Snackbar;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
public class ExParserActivity extends AsyncTask<Void, Integer, Integer>
{
Context context;
ListView exListView;
String data;
ArrayList<String> exCategories = new ArrayList<>();
ProgressDialog progressDialog;
public ExParserActivity(Context context, String data, ListView lv)
{
this.context = context;
this.data = data;
this.exListView = lv;
}
//B4 JOB STARTS
#Override
protected void onPreExecute()
{
super.onPreExecute();
progressDialog = new ProgressDialog(context);
progressDialog.setTitle("Parser");
progressDialog.setMessage("Parsing...Please wait");
progressDialog.show();
}
//Heavy job
#Override
protected Integer doInBackground(Void... params)
{
return this.parse();
}
#Override
protected void onProgressUpdate(Integer... values)
{
super.onProgressUpdate(values);
}
#Override
protected void onPostExecute(Integer integer)
{
super.onPostExecute(integer);
progressDialog.dismiss();
if(integer == 1)
{
//ADAPTER
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(context, android.R.layout.simple_list_item_1, exCategories);
//ADAPT TO LIST VIEW
exListView.setAdapter(arrayAdapter);
//ON CLICK LISTENER
exListView.setOnItemClickListener(new AdapterView.OnItemClickListener()
{
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
context.startActivity(new Intent(context, UpdateDeleteExCategories.class));
//Snackbar.make(view, exCategories.get(position), Snackbar.LENGTH_SHORT).show();
}
});
}
else
{
Toast.makeText(context, "Unable to Parse", Toast.LENGTH_LONG).show();
}
}
//PARSE RECEIVED DATA
private int parse()
{
try
{
//ADD THAT DATA TO JSON ARRAY FIRST
JSONArray jsonArray = new JSONArray(data);
//CREATE JO OBJECT TO HOLD A SINGLE ITEM
JSONObject jsonObject = null;
exCategories.clear();
//LOOP THROUGH THE ARRAY
for(int i = 0; i < jsonArray.length(); i++)
{
jsonObject = jsonArray.getJSONObject(i);
//RETRIEVE NAME
String exCatName = jsonObject.getString("exCatName");
//ADD IT TO ARRAY LIST
exCategories.add(exCatName);
}
//IF ITS SUCCESSFUL RETURN 1
return 1;
}
catch (JSONException e)
{
e.printStackTrace();
}
//IF IT IS NOT SUCCESSFUL RETURN 0
return 0;
}
}
Third Class
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import java.util.Calendar;
public class AddExpenseActivity extends SwipeFunctionActivity
{
private ImageView backImageView;
private TextView setDateTextView;
private EditText categoryEditText, amountEditText;
int year, month, day;
static final int DIALOG_ID = 0; //Initialise the variable to 0.
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_expense);
final Calendar calendar = Calendar.getInstance();
year = calendar.get(Calendar.YEAR);
month = calendar.get(Calendar.MONTH);
day = calendar.get(Calendar.DAY_OF_MONTH);
setDateTextView = (TextView)findViewById(R.id.setDateTextView);
backImageView = (ImageView)findViewById(R.id.backImageView);
categoryEditText = (EditText)findViewById(R.id.categoryEditText);
amountEditText = (EditText)findViewById(R.id.amountEditText);
setDateTextView.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
showDialog(DIALOG_ID);
}
});
categoryEditText.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
pickCategoryMethod();
}
});
backImageView.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
backMethod();
}
});
}
#Override
protected Dialog onCreateDialog(int id)
{
if (id == DIALOG_ID)
{
return new DatePickerDialog(this, dpickerListener, year, month, day);
}
return null;
}
private DatePickerDialog.OnDateSetListener dpickerListener = new DatePickerDialog.OnDateSetListener()
{
#Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth)
{
AddExpenseActivity.this.year = year;
month = monthOfYear + 1;
day = dayOfMonth;
showDate(AddExpenseActivity.this.year, month, day);
//Toast.makeText(AddExpenseActivity.this, "Selected date: " + dayOfMonth + " / " + (monthOfYear+1) + " / " + year, Toast.LENGTH_LONG).show();
}
};
private void showDate(int year, int month, int day)
{
setDateTextView.setText(new StringBuilder().append(day).append("/")
.append(month).append("/").append(year));
}
public void pickCategoryMethod()
{
String url = "http://192.168.0.3/myapp/fexcateg.php";
//
final Dialog dialog = new Dialog(AddExpenseActivity.this);
dialog.setContentView(R.layout.activity_pick_category);
dialog.setTitle(" Pick your Category");
final ListView pickCategoryListView = (ListView)dialog.findViewById(R.id.pickCategoryListView);
final ExDownloaderActivity downloader = new ExDownloaderActivity(this, url, pickCategoryListView);
//Execute download
downloader.execute();
//pickCategoryListView = (ListView)dialog.findViewById(R.id.pickCategoryListView);
//This makes the dialog visible.
dialog.show();
}
public void backMethod()
{
//startActivity(new Intent(getApplicationContext(), BalanceActivity.class));
finish();
}
#Override
public void onSwipeLeft()
{
super.onSwipeLeft();
startActivity(new Intent(getApplicationContext(), AddIncomeActivity.class));
finish();
}
#Override
public void onSwipeRight()
{
super.onSwipeRight();
startActivity(new Intent(getApplicationContext(), AddSavingActivity.class));
finish();
}
}
So for my problem now. I want when i click a category inside the dialog box, the categoryEditText variable i have in the trird class to change in the name of the item i clicked in the listview. First of all where do i have to write this code and secondly how to do it. I am kind of lost becasue is really a big app:/
Many thanks !!!
I started to develop Android recently and I'm having difficulty in solving a thing probably much simpler than what I think.
I am creating a CRUD application that communicates with an online database, I can read and enter data, unfortunately I can't delete and modify the list once it is created.
To manage the data that use JSON and the row in the list that I add is made up of three fields: animal_id, animal_name, animal_type.
The activity data on which I read and on which I want to implement methods to modify and delete via listener is formed by the following code:
import java.sql.Array;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
public class ListAnimalActivity extends ListActivity {
ArrayList<HashMap<String,?>> animalList;
JSONParser jParser = new JSONParser();
JSONArray animals = null;
Button button_add;
private static String url_read = "http://example.com/list_animals.php";
private static String url_delete = "http://example.com/delete_animal.php";
private static final String TAG_SUCCESS = "success";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
load_ListAnimalActivity();
}
public void onResume(){
super.onResume();
load_ListAnimalActivity();
}
private void load_ListAnimalActivity(){
setContentView(R.layout.activity_list_animal);
animalList = new ArrayList<HashMap<String,?>>();
new Read_Object().execute();
final ListView listView = (ListView)findViewById(android.R.id.list);
final ListAdapter adapter = new SimpleAdapter(
ListAnimalActivity.this, animalList,
R.layout.row_list, new String[] { "animal_id",
"animal_name","animal_type"},
new int[] { R.id.animal_id, R.id.animal_name,R.id.animal_type });
listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View view, final int position, long id) {
AlertDialog.Builder adb = new AlertDialog.Builder(ListAnimalActivity.this);
adb.setTitle("Attenzione!");
adb.setMessage("Vuoi eliminare l\'elemento \"" + animalList.get(position)+ "\" ?");
final int posizione = position;
adb.setNegativeButton("Annulla",new AlertDialog.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {}
});
adb.setPositiveButton("Elimina", new AlertDialog.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
new Delete_Object().execute();
}
});
adb.show();
}
});
button_add = (Button)findViewById(R.id.button_add);
button_add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(ListAnimalActivity.this,CRUDAnimalActivity.class));
}
});
}
class Read_Object extends AsyncTask<String, String, String> {
private ProgressDialog progressMessage = new ProgressDialog(ListAnimalActivity.this);
#Override
protected void onPreExecute() {
super.onPreExecute();
progressMessage.setMessage("Loading ...");
progressMessage.setIndeterminate(false);
progressMessage.setCancelable(false);
progressMessage.show();
}
protected String doInBackground(String... args) {
List params = new ArrayList();
JSONObject json = jParser.makeHttpRequest(url_read, "POST", params);
try{
Log.d("Animals: ", json.toString());
} catch (NullPointerException e){
e.printStackTrace();
}
try {
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
animals = json.getJSONArray("animals");
for (int i = 0; i < animals.length(); i++) {
JSONObject c = animals.getJSONObject(i);
String id = c.getString("animal_id");
String name = c.getString("animal_name");
String type = c.getString("animal_type");
HashMap map = new HashMap();
map.put("animal_id", id);
map.put("animal_name", name);
map.put("animal_type", type);
animalList.add(map);
}
}
} catch (JSONException e) {
e.printStackTrace();
} catch (NullPointerException e){
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url) {
progressMessage.dismiss();
runOnUiThread(new Runnable() {
public void run() {
ListAdapter adapter = new SimpleAdapter(
ListAnimalActivity.this, animalList,
R.layout.row_list, new String[] { "animal_id",
"animal_name","animal_type"},
new int[] { R.id.animal_id, R.id.animal_name,R.id.animal_type });
setListAdapter(adapter);
}
});
}
}
class Delete_Object extends AsyncTask<String, String, String>{
private ProgressDialog progressMessage = new ProgressDialog(ListAnimalActivity.this);
#Override
protected void onPreExecute() {
super.onPreExecute();
progressMessage.setMessage("Deleting ...");
progressMessage.setIndeterminate(false);
progressMessage.setCancelable(false);
progressMessage.show();
}
protected String doInBackground(String... args) {
/*
Code to delete
*/
return null;
}
protected void onPostExecute(String file_url){
}
}
}
When i click on a list Item, the listener show me the object in this format:
{animal_type=firstType, animal_name=firstName, animal_id=1}
So my question is:
How can I collect only animal_id from the array animalList > ?
Your animalList is an array list with HashMaps as its elements, so when you call animalList.get(position), it will return a HashMap. To retrieve an animal_id just use :
(animalList.get(position)).get(animal_id).toString();
you have to create a Modelclass/Pojo Class (Private variable and getters and setters) for Animals,
ArrayList<AnimalModel> animalsArrayList = new ArrayList<AnimalModel>();
add the Animals object/data to animalsArrayList and listview.setAdapter(animalsArrayList);
then
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// TODO Auto-generated method stub
Object object = speakerListView.getItemAtPosition(position);
AnimalModel animals_data = (AnimalModel) object;
id = animals_data.getAnimal_id()
// call delete Async with thid Id
}
});
You code looks pretty messy. If I were you I would create a Custom Adapter that extends the base adapter and takes as a parameter either a hashmap or a list that you pass in the constructor. There you can have different listeners. Also if you want to notify the activity you can have the "luxury" to pass an interface as a parameter and notify the activity when something changes.
Regarding the json part, I would create two new classes, one which is a Thread Manager that receives tasks and handles them further and another class where u make the http calls and the json parsing.
I have done a similar application that receives data from a nebula interface and displays them to the user.
I get data from database (id, name) and I display (name) in a ListView. When user clicks I need to get database (id) to perform an action
KoiskesdataActivity.java
package koisk.data;
import java.util.ArrayList;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.os.StrictMode;
import android.text.Editable;
import android.text.TextWatcher;
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.TextView;
import android.widget.Toast;
import android.os.StrictMode;
import android.widget.AdapterView.OnItemClickListener;
public class KoiskesdataActivity extends Activity {
/** Called when the activity is first created. */
ProgressDialog pd;
private ListView koisksListView;
private EditText myfilter;
// private ArrayAdapter <String> koiskarrayAdapter;
String koiskArray[];
Button autocompletekoisksname;
int textlength=0;
private ArrayList<String> array_sort= new ArrayList<String>();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
///
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
///
koisksListView=(ListView) findViewById(R.id.koiskslist);
myfilter=(EditText) findViewById(R.id.myFilter);
///////
pd = new ProgressDialog(this);
pd.setMessage("loading...");
pd.show();
/////
getarrayofnamekoisk namekoisk=new getarrayofnamekoisk();
koiskArray=namekoisk.WW();
ArrayAdapter <String> koiskarrayAdapter=new ArrayAdapter <String>(KoiskesdataActivity.this, android.R.layout.simple_list_item_1,koiskArray);
koisksListView.setAdapter(koiskarrayAdapter);
pd.dismiss();
koisksListView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View view, int arg2,
long arg3) {
// TODO Auto-generated method stub
}
});
myfilter.addTextChangedListener(new TextWatcher() {
#Override
public void afterTextChanged(Editable arg0) {
// TODO Auto-generated method stub
}
#Override
public void beforeTextChanged(CharSequence arg0, int arg1,
int arg2, int arg3) {
// TODO Auto-generated method stub
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count)
{
// TODO Auto-generated method stub
textlength = myfilter.getText().length();
array_sort.clear();
for (int i = 0; i < koiskArray.length; i++)
{
if (textlength <= koiskArray[i].length())
{
//subSequence returns the specified word between the begien and end
//equalsIgnoreCase compares this String to another String, ignoring case considerations. Two strings are considered equal ignoring case if they are of the same length, and corresponding characters in the two strings are equal ignoring case
if (myfilter.getText().toString().equalsIgnoreCase((String)koiskArray[i].subSequence(0, textlength)))
{
array_sort.add(koiskArray[i]);
}
}
}
//KoiskesdataActivity.this.koiskarrayAdapter.getFilter().filter(s);
koisksListView.setAdapter(new ArrayAdapter<String>(KoiskesdataActivity.this,android.R.layout.simple_list_item_1,array_sort));
}
});
}
}
getarrayofnamekoisk.java
package koisk.data;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import javax.xml.transform.Templates;
import android.R.array;
import android.R.integer;
import android.widget.ArrayAdapter;
import android.widget.Toast;
public class getarrayofnamekoisk{
private int i;
private String[] koiskname ;
private int num_rows;
private ArrayAdapter arrayAdapterdata;
List<String[]> names = new ArrayList<String[]>();
ArrayList<String> arr = new ArrayList<String>();
public String[] WW() {
// TODO Auto-generated method stub
connecttodatabase qq=new connecttodatabase();
qq.dbconnect();
if (qq.con !=null)
{
try
{
Statement st = qq.con.createStatement();
ResultSet rs = st.executeQuery("SELECT Name,id FROM Device where DeviceTypeId=4 and IsDeleted =0 and name is not null ");
while(rs.next())
{
arr.add(rs.getString("name"));
}
koiskname= new String [arr.size()];
arr.toArray(koiskname);
}
catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
//Toast.makeText(ConnectbyprocedureActivity.this, e.toString() , Toast.LENGTH_SHORT).show();
}
qq.closeConnection();
}
return koiskname;
}
}
connecttodatabase.java //to connect to sql server
package koisk.data;
import java.sql.DriverManager;
public class connecttodatabase {
public java.sql.Connection con = null;
private final String userName="sa";
private final String pass="123";
/////////
private final String url = "jdbc:jtds:sqlserver://";
private final String serverName= "192.168.1.200";
private final String portNumber = "1433";
private final String databaseName= "loadshedding";
////////////
/**
* #param args
*/
private String getConnectionUrl(){
//jdbc:jtds:sqlserver://192.168.1.200:1433/loadShedding
//return url+serverName+":"+portNumber+";databaseName="+databaseName+";selectMethod="+selectMethod+";";
return url+serverName+":"+portNumber+"/"+databaseName;
}
public java.sql.Connection dbconnect() {
// TODO Auto-generated method stub
try {
//Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Class.forName("net.sourceforge.jtds.jdbc.Driver");
//jdbc:jtds:sqlserver://192.168.1.200:1433/loadShedding
con = DriverManager.getConnection(getConnectionUrl(), userName, pass);
// if(con!=null) System.out.println("Connection Successful!");
}
catch(Exception e) {
e.printStackTrace();
// tv.setText(e.toString());
}
return con ;
}
// public void displayDb(){
// java.sql.DatabaseMetaData dm = null;
// java.sql.ResultSet rs = null;
// try{
// con=this.dbConnect();
// }
// catch(Exception e){
// e.printStackTrace();
// }
// }
public void closeConnection(){
try{
if(con!=null)
con.close();
con=null;
}catch(Exception e){
e.printStackTrace();
}
}
}
please i need help ..... thanks guys
You get the id from the database, but you never store it anywhere.. you first need to store it in an Array or ArrayList (lets say, idList). You have to do it similar to how you store the names in a list. then:
You can get the position of the item which is clicked inside the onItemClick method as
follows:
#Override
public void onItemClick(AdapterView<?> arg0, View view, int arg2, long arg3) {
int position = arg2;
clickedID = idList.get(position);
// do something with the clicked id.
}
I am experiencing a problem I have following code:
public void onCreate(Bundle savedInstanceState) {
MyDialog = ProgressDialog.show(this, "Nalagam kanale" , "Prosimo počakaj ... ", true);
MyDialog.show();
... }
Which should actually start he dialog... But the problem is that dialog is shown when everything is loaded...
How can I do solve that?
Actual code
package com.TVSpored;
import java.util.ArrayList;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ListView;
public class Currently extends Activity{
static final int PROGRESS_DIALOG = 0;
private ArrayList<CurrentlyItem> currentItems;
private CurrentAdapter aa;
private ListView currentListView;
private JSONArray CurrentShows;
private Communicator CommunicatorEPG;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.layout_currently);
CommunicatorEPG = new Communicator();
currentItems = new ArrayList<CurrentlyItem>();
if(currentItems == null)
int resID = R.layout.current_item;
aa = new CurrentAdapter(this, resID, currentItems);
currentListView = (ListView)findViewById(R.id.currentListView);
try {
currentListView.setAdapter(aa);
} catch (Exception e) {
Log.d(" * Napaka", e.toString());
}
try {
populateCurrent();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void populateCurrent() throws JSONException
{
CurrentShows = CommunicatorEPG.getCurrentShows(0);
for (int i = 0; i < CurrentShows.length(); i++)
{
JSONObject jsonObject = CurrentShows.getJSONObject(i);
String start = jsonObject.getString("1");
Integer duration = jsonObject.getInt("2");
String title = jsonObject.getString("3");
String epg_channel = jsonObject.getString("4");
String channel_name = jsonObject.getString("5");
CurrentlyItem newItem = new CurrentlyItem(1, 2, 3, 4, 5);
currentItems.add(i, newItem);
}
}
}
This is actual code... I would like to do populateCurrent(); in AsyncTask and meanwhile I would like a loading screen to be shown... Have been trying for few hours now but no actual success... I have successfully shown loading screen and wen trough JSONArray, but couldn't update listview...
Thanks for support!
Expected behaviour...
Show a dialog is a typical task of UI thread, but until you complete the onCreate method, the UI thread s not free to execute the dialog creation...
Two solution: create a dialog in a separate thread or execute your long task in a separate thread.
Some highlights here:
http://developer.android.com/guide/topics/ui/dialogs.html
You could wait to set the content of the activity until the you're finished with the progress dialog.
Update:
This would run your command in async-task:
new AsyncTask<Void, Void, Void> {
protected Long doInBackground(Void... voids) {
populateCurrent();
}
}.execute()
However, then you probably have to make sure to update the list in the GUI thread again and in some way tell the adapter that the list have been updated (since you've given that list to the adapter):
runOnUiThread(new Runnable() {
public void run() {
currentItems.add(i, newItem);
aa.notifyDataSetChanged();
}
}
It is probably best to create a new list entirely and set the view to view that.
I am trying to implement a dynamic autocomplete widget in android. I am done with the major functionalities and the autocompletion implemented is for youtube video search.
When I start typing a letter or two, the auto-completion is not working. But when I type three letters or more it works prfect. It also works when I type two letters and hit a backspace. I do not know what is wrong with the code.
I have uploaded the code here
Experts, kindly guide me. I would be obliged if you can point out where I have gone wrong with the code.
Any help in this regard is well appreciated.
Looking forward,
Regards,
Rony
import org.json.JSONArray;
import org.json.JSONException;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.widget.ArrayAdapter;
public class YoutubeAutoComplete extends Activity {
Youtube yt = new Youtube();
CustomAutoComplete myAutoComplete;
ArrayAdapter<String> adapter;
private JSONArray js;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
myAutoComplete = (CustomAutoComplete) findViewById(R.id.autocomplete);
adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_dropdown_item_1line);
myAutoComplete.addTextChangedListener(textWatcher);
myAutoComplete.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
TextWatcher textWatcher = new TextWatcher() {
public void onTextChanged(final CharSequence s, int start, int before,
int count) {
Thread t = new Thread() {
public void run() {
try {
js = yt.GetSuggestions(s.toString()).getJSONArray(1);
messageHandler.sendEmptyMessage(0);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
t.start();
}
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
public void afterTextChanged(Editable s) {
}
};
private Handler messageHandler = new Handler() {
public void handleMessage(Message msg) {
adapter.clear();
for (int i = 0; i < js.length(); i++) {
try {
adapter.add(js.getJSONArray(i).getString(0));
System.out.println(js.getJSONArray(i).getString(0));
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
adapter.notifyDataSetChanged();
}
};
}
Take a look at completionThreshold AKA the number of characters the user must type before getting completion suggestions.
http://developer.android.com/reference/android/widget/AutoCompleteTextView.html#attr_android:completionThreshold