Problemto Create a Class SQL Query Studio Android - android

My Problem today is that been developing an APP having a Login, A Maintenance Products (For more say), all with the database engine SQL
and create the login all Ok, the procedimeinto a normal login with user and pass ago, also believes maintaining create products, which I take as parameters the name of the product and its respective description, I add, edit, and delete, just not makes the management of search data and show me when access to the corresponding layout, using the onCreate method of my MainMenu but hey that's not the case, the relevant case is that I want to know how to do that through a button, find me the names input on a EditText or are related to the name, and tried to do this using the following code:
package com.sqldata.gst.appsql;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.SimpleAdapter;
import android.widget.Toast;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
/**
* Created by Administrador on 05/10/2016.
*/
public class ConClientes extends MainActivity {
Conexion conexionSQL;
EditText txtCdCliente, txtNomCli;
Button btnBuscar, btnRetornar;
ProgressBar pgrCliente;
ListView lstClientes;
String idCliente;
//ResultSet rs;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.con_clientes);
conexionSQL = new Conexion();
txtCdCliente = (EditText) findViewById(R.id.txtCdCliente);
//txtNomCli = (EditText) findViewById(R.id.txtNomCli);
btnBuscar = (Button) findViewById(R.id.btnBuscar);
btnRetornar = (Button) findViewById(R.id.btnRetornar);
pgrCliente = (ProgressBar) findViewById(R.id.pgrCliente);
lstClientes = (ListView) findViewById(R.id.lstClientes);
pgrCliente.setVisibility(View.GONE);
idCliente = "";
// Evento Ejecutar Boton
btnBuscar.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SelectClientes selectClientes = new SelectClientes();
selectClientes.execute(""); //Cannot resolve method 'execute(java.lang.String)
}
});
}
public class FillList extends AsyncTask<String, String, String>
{
String result = "";
List<Map<String, String>> CliList = new ArrayList<Map<String, String>>();
#Override
protected void onPreExecute(){
pgrCliente.setVisibility(View.VISIBLE);
}
#Override
protected void onPostExecute(String r){
pgrCliente.setVisibility(View.GONE);
Toast.makeText(ConClientes.this, r, Toast.LENGTH_SHORT).show();
String[] from = {"A", "B", "C"};
int[] views = {R.id.lblClienteId, R.id.lblNomCli, R.id.lblCodCli};
final SimpleAdapter ADA = new SimpleAdapter(ConClientes.this, CliList, R.layout.lst_cliente,
from, views);
lstClientes.setAdapter(ADA);
lstClientes.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
HashMap<String, Object> obj = (HashMap<String, Object>) ADA.getItem(arg2);
idCliente = (String) obj.get("A");
//String ClienName = (String) obj.get("B");
String ClienCod = (String) obj.get("C");
//txtNomCli.setText(ClienName);
txtCdCliente.setText(ClienCod);
}
});
}
#Override
protected String doInBackground (String... params){
try{
Connection cnSQL = conexionSQL.CONN();
if (cnSQL == null){
result = "Error en la Conexión SQL Server";
}
else{
String query = "select * from clientes";
PreparedStatement psSQL = cnSQL.prepareStatement(query);
ResultSet rsSQL = psSQL.executeQuery();
ArrayList data1 = new ArrayList();
while (rsSQL.next()){
Map<String, String> dataRec = new HashMap<String, String>();
dataRec.put("A", rsSQL.getString("idcliente"));
dataRec.put("B", rsSQL.getString("nom_cli"));
dataRec.put("C", rsSQL.getString("cod_cli"));
CliList.add(dataRec);
}
result = "Success";
}
} catch (Exception ex){
result = "Error al Buscar Datos de la Tabla Clientes";
}
return result;
}
}
public class SelectClientes extends ArrayList<String>{
String result = "";
Boolean isSuccess = false;
String ClienCod = txtCdCliente.getText().toString();
String NomCli = txtNomCli.getText().toString();
#Override //Method does not override method from its superclass
protected void onPreExecute(){
pgrCliente.setVisibility(View.VISIBLE);
}
//#Override
protected void onPostExecute(String r){
pgrCliente.setVisibility(View.GONE);
Toast.makeText(ConClientes.this, r, Toast.LENGTH_SHORT).show();
if (isSuccess == true){
FillList fillList = new FillList();
fillList.execute("");
}
}
#Override //Method does not override method from its superclass
protected String doInBackground(String... params){
if (ClienCod.trim().equals(""))
result = "Favor de Introducir el Codigo del Cliente";
else {
try{
Connection con = conexionSQL.CONN();
if (con == null){
result = "No Hay Datos para Mostrar";
} else {
String query = "Select * from clientes where idcliente =" + idCliente;
PreparedStatement preparedStatement = con.prepareStatement(query);
preparedStatement.executeUpdate();
result = "Busqueda de Datos Correcta";
isSuccess = true;
}
} catch (Exception ex){
isSuccess = false;
result = "Verifique los Datos";
}
}
return result;
}
}
}
Well as observed that that's my code and attempted but has two factors which are commented code the first is:
selectClientes.execute(""); // Can not resolve method 'execute (java.lang.String)
and the second in the Override
#Override //Method does not override method from its superclass
that's my niggle I do not understand how I can do to make me query consisting of editext = that will be the name or names that seeketh, and the button to execute the action of select * from, you understand me
and I would like to step I make when entering the layout from the menu to load and show me the data, without pressing anything
such as doInBackground method that's what I want to do but I guess it's in the onCreate and you will understand me if you need more details, please say, what I want is to solve that little problem
Thanks to All!!

Of course app can't resolve method execute, because ArrayList doesn't have it.
SelectClientes extends ArrayList
SelectClientes should extend AsyncTask.

Related

Android get attribute value from xml

I am trying to make an app which uses last.fm's web API, sends a query for similar artists and returns all the names of the similar artists. It seems as though I manage to connect and get the xml response properly. However, I cannot extract the value of the name-attribute. I am using artistName = xmlData.getAttributeValue(null, "name"); but all it gives me is null.
import android.app.Activity;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Toast;
import java.util.*;
#SuppressWarnings("FieldCanBeLocal")
public class MainActivity extends Activity implements Observer {
private final String INPUTERROR = "Invalid/missing artist name.";
private NetworkCommunication nc;
private ArrayList<String> list;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
nc = new NetworkCommunication();
nc.register(this);
list = new ArrayList<>();
ListView lv = (ListView)findViewById(R.id.ListView_similarArtistsList);
ArrayAdapter adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, list);
lv.setAdapter(adapter);
}
public void searchButton_Clicked(View v){
EditText inputField = (EditText)findViewById(R.id.editText_artistName);
String searchString = inputField.getText().toString();
searchString = cleanSearchString(searchString);
if(validateSearchString(searchString)){
nc.setSearchString(searchString);
nc.execute();
}
else{
Toast.makeText(MainActivity.this, INPUTERROR, Toast.LENGTH_SHORT).show();
}
}
private String cleanSearchString(String oldSearchString){
String newString = oldSearchString.trim();
newString = newString.replace(" ", "");
return newString;
}
private boolean validateSearchString(String searchString){
boolean rValue = true;
if(TextUtils.isEmpty(searchString)){
rValue = false;
}
return rValue;
}
#Override
public void update(String artistName) {
list.add(artistName);
}
}
Here is my Network Communications class:
import android.os.AsyncTask;
import android.util.Log;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
#SuppressWarnings("FieldCanBeLocal")
class NetworkCommunication extends AsyncTask<Object, String, Integer> implements Subject {
private final String MYAPIKEY = "--------------------------";
private final String ROOT = "http://ws.audioscrobbler.com/2.0/";
private final String METHOD = "?method=artist.getsimilar";
private ArrayList<Observer> observers;
private int amountOfArtists = 0;
private String foundArtistName;
private String searchString;
NetworkCommunication(){
observers = new ArrayList<>();
}
void setSearchString(String newSearchString){
searchString = newSearchString;
}
private XmlPullParser sendRequest(){
try{
URL url = new URL(ROOT + METHOD + "&artist=" + searchString + "&api_key=" + MYAPIKEY);
XmlPullParser receivedData = XmlPullParserFactory.newInstance().newPullParser();
receivedData.setInput(url.openStream(), null);
return receivedData;
}
catch (IOException | XmlPullParserException e){
Log.e("ERROR", e.getMessage(), e);
}
return null;
}
private int tryProcessData(XmlPullParser xmlData){
int artistsFound = 0;
String artistName;
int eventType;
try{
while ((eventType = xmlData.next()) != XmlPullParser.END_DOCUMENT) {
if (eventType == XmlPullParser.START_TAG) {
if(xmlData.getName().equals("name")){
artistName = xmlData.getAttributeValue(null, "name");
publishProgress(artistName);
artistsFound++;
}
}
}
}
catch (IOException | XmlPullParserException e){
Log.e("ERROR", e.getMessage(), e);
}
if (artistsFound == 0) {
publishProgress();
}
return artistsFound;
}
#Override
protected Integer doInBackground(Object... params) {
XmlPullParser data = sendRequest();
if(data != null){
return tryProcessData(data);
}
else{
return null;
}
}
#Override
protected void onProgressUpdate(String... values){
/*
if (values.length == 0) {
//No data found...
}
*/
if (values.length == 1) {
setFoundArtistName(values[0]);
notifyObserver();
}
super.onProgressUpdate(values);
}
private void setFoundArtistName(String newArtistName){
foundArtistName = newArtistName;
}
#Override
public void register(Observer newObserver) {
observers.add(newObserver);
}
#Override
public void unregister(Observer deleteObserver) {
observers.remove(deleteObserver);
}
#Override
public void notifyObserver() {
for (Observer o : observers) {
Log.i("my tag.... ", "name = " + foundArtistName);
o.update(foundArtistName);
}
}
}
Here's a screenshot of the xml response in Google Chrome:
The only thing I am interested in extracting at this moment is the the value of the Name-Element.
I am logging the value of foundArtistName (in the method notifyObserver) it gives me A LOT of "my tag.... name = null my tag.... name = null my tag.... name = null etc.."
EDIT: I tried using getText() instead of getAttributeValue(), but it also gives me null.
I found the solution. I was using: artistName = xmlData.getAttributeValue(null, "name");, when I really should've used: artistName = xmlData.nextText();

How to update ProgressBar with respect to downloaded data while downloading text data from web using Asynctask in android

I want to show progressbar wrt to downloaded data from the web. Whether I have to create dynamically or have to reference by Id by creating it in xml.I am a little bit confused. Here is my code. Could you please tell me how?
package com.example.telugumovies;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.Toast;
public class MainActivity extends ListActivity {
String category ="";
String[] cat = {"Upcoming","Telugu"};
private List<String> categories ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
categories = new ArrayList<String>();
int i=0;
for(i=0;i<2;i++)
{
categories.add(cat[i]+" Movies");
}
ArrayAdapter<String> myAdapter = new ArrayAdapter <String>(this,
R.layout.listview_rowlayout, R.id.tv, categories);
// assign the list adapter
setListAdapter(myAdapter);
}
// when an item of the list is clicked
#Override
protected void onListItemClick(ListView list, View view, int position, long id) {
super.onListItemClick(list, view, position, id);
Bundle giveCategory = new Bundle();
if(position == 0)
{
try {
new GetData().execute();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally
{
}
}
else if(position == 1)
{
giveCategory.putString("cate", cat[position]);
Intent a = new Intent(MainActivity.this,Show_Years.class);
a.putExtras(giveCategory);
startActivity(a);
}
else
{
Toast.makeText(getApplicationContext(), "Sorry This option is not Available for Now ",
Toast.LENGTH_SHORT).show();
}
//String selectedItem = (String) getListView().getItemAtPosition(position);
}
class GetData extends AsyncTask<String,Integer,String>
{
ProgressBar pb ;
protected void onPreExecute()
{
pb = new ProgressBar(MainActivity.this);
pb.setVisibility(View.VISIBLE);
}
#Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
String alldata = "";
int flag=1;
String data = "";
URL url = null;
int i=0,j=0,count=0,c=0;
URLConnection con = null;
InputStream is = null;
String line = null;
try
{
url = new URL("http://www.filmibeat.com/telugu/upcoming-movies.html");
con = url.openConnection();
is = con.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
while ((line = br.readLine()) != null) {
//System.out.println(line);
alldata = "";
flag=0;
if(line.contains("<h3"))
{j=0;
flag=1;
for(i=0;i<line.length();i++)
{
if(line.charAt(i)=='<')
{
j=1;
}
else if(j==1 && line.charAt(i)=='>')
{
j=0;
}
else if(j==0)
{
alldata = alldata + (line.charAt(i));
}
}
}
data=data+alldata;
if(flag==1)
{
data=data+"$";
}
}
System.out.println(data);
return data;
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally
{
return data;
}
}
protected void onPostExecute(String someting)
{
Bundle givedata = new Bundle();
givedata.putString("moviedata",someting);
Intent a = new Intent(MainActivity.this,Show_upcomingmovies.class);
a.putExtras(givedata);
pb.setVisibility(View.INVISIBLE);
startActivity(a);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
Using dynamically created progress bar or referencing it from an id, are both fine.
Using a reference from XML allows you to have more control on the progress bars appearance, as you would have designed it sepcifically for your need (like appearance, where it has to appear, etc..). But if that is not the case, you can use a dynamically created one as in your current code as well.
There is a lot of ways. One is to define ProgressDiaolog as a field in your AsyncTask, then add it to your onPreExecuted():
pDialog = new ProgressDialog(this);
pDialog.setMessage("some downloading massage");
pDialog.setIndeterminate(false);
pDialog.setMax(100); //you can adjust this
pDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
pDialog.setCancelable(false);
pDialog.show();
Then you can update the progress by override updateProgress() in your AsyncTask and call pDialog.setProgress();

Check box sending value to next activity even after deselcting it

I used a listview to display the check boxes in my activity. I also put a check to see atleast one check box is checked otherwise it will toast a message asking the user to please select atleast one value. Below are my two classes. Problem which i am having is that when i press the submit button without selecting a check box then i get a message to select atleast one checkbox. But when i select and deselect the check box and then submit it then it goes to the next activity with value of the check box which i dont want. It should not go to the other activity till i select one checkbox. Please help me with this problem.
ConnectAdapter.java
package com.arcadian.adapter;
import java.util.ArrayList;
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.Toast;
import android.widget.CompoundButton.OnCheckedChangeListener;
import com.arcadian.genconian.R;
public class ConnectAdapter extends ArrayAdapter<ConnectModel> {
public ArrayList<ConnectModel> stateList;
Context cntx;
public static ConnectModel connect;
CheckBox cb;
public ConnectAdapter(Context context, int textViewResourceId,
ArrayList<ConnectModel> stateList) {
super(context, textViewResourceId, stateList);
this.cntx = context;
this.stateList = new ArrayList<ConnectModel>();
this.stateList.addAll(stateList);
}
public class ViewHolder {
CheckBox connect_CB;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
Log.v("ConvertView", String.valueOf(position));
if (convertView == null) {
LayoutInflater vi = (LayoutInflater) cntx
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = vi.inflate(R.layout.list_connect_row, null);
holder = new ViewHolder();
holder.connect_CB = (CheckBox) convertView
.findViewById(R.id.connect_CB);
convertView.setTag(holder);
holder.connect_CB
.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton v,
boolean isChecked) {
// TODO Auto-generated method stub
cb = (CheckBox) v;
if (v.isChecked()) {
connect = (ConnectModel) cb.getTag();
/*
* Toast.makeText( cntx.getApplicationContext(),
* "Checkbox: " + cb.getText() + " -> " +
* cb.isChecked(), Toast.LENGTH_LONG).show();
*/
connect.setSelected(cb.isChecked());
}
// else{
// Toast.makeText(getContext(), "Select aleast one.", Toast.LENGTH_LONG).show();
// String select = null;
// }
}
});
}
else {
holder = (ViewHolder) convertView.getTag();
}
ConnectModel state = stateList.get(position);
holder.connect_CB.setText(state.getName());
holder.connect_CB.setChecked(state.isSelected());
holder.connect_CB.setTag(state);
return convertView;
}
}
**ConnectActivity.java**
package com.arcadian.genconian;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
import com.arcadian.adapter.ConnectAdapter;
import com.arcadian.adapter.ConnectModel;
import com.arcadian.utils.CommonActivity;
import com.arcadian.utils.Constants;
import com.arcadian.utils.JSONParser;
public class ConnectActivity extends CommonActivity implements OnClickListener {
ConnectAdapter dataAdapter = null;
ArrayList<ConnectModel> stateList;
private ProgressDialog pDialog;
String to_connect;
String response;
private StringBuffer responseText;
int success;
String email, type;
private String status;
String select;
ConnectModel _ConnectModel;
ConnectModel selstate;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_connect);
// Generate list View from ArrayList
displayListView();
responseText = new StringBuffer();
Button submit_BT = (Button) findViewById(R.id.submit_BT);
submit_BT.setOnClickListener(this);
Intent i = getIntent();
email = i.getStringExtra("user_email");
type = i.getStringExtra("type");
}
private void displayListView() {
// Array list of countries
stateList = new ArrayList<ConnectModel>();
_ConnectModel = new ConnectModel("All", false);
stateList.add(_ConnectModel);
_ConnectModel = new ConnectModel("Stream", false);
stateList.add(_ConnectModel);
_ConnectModel = new ConnectModel("Industry", false);
stateList.add(_ConnectModel);
_ConnectModel = new ConnectModel("Field", false);
stateList.add(_ConnectModel);
_ConnectModel = new ConnectModel("Batchmates", false);
stateList.add(_ConnectModel);
// create an ArrayAdaptar from the String Array
dataAdapter = new ConnectAdapter(this, android.R.layout.simple_list_item_multiple_choice,
stateList);
ListView to_connect_LV = (ListView) findViewById(R.id.to_connect_LV);
// Assign adapter to ListView
to_connect_LV.setAdapter(dataAdapter);
}
#Override
public void onClick(View v) {
int id = v.getId();
// openRequest.setCallback(statusCallback);
// session.openForRead(openRequest);
// loginProgress.setVisibility(View.VISIBLE);
switch (id) {
case R.id.submit_BT:
ArrayList<ConnectModel> stateList = dataAdapter.stateList;
response = "";
for (int i = 0; i < stateList.size(); i++) {
ConnectModel state = stateList.get(i);
selstate = ConnectAdapter.connect;
if(selstate!=null)
if (selstate.equals(state)) {
select = "abc";
if ((stateList.size() - 1) >= i) {
responseText.append(state.getName() + ",");
String text = state.getName();
response = responseText.toString();
loge("response", "response text is" + responseText);
}
else {
responseText.append(state.getName());
}
}
}
if (select == null) {
Toast.makeText(getApplicationContext(), "Select at least one.",
Toast.LENGTH_SHORT).show();
} else {
new Connect().execute();
}
/*
* if(response.length()>1) {
* if(response.substring(response.length()-1).equals(",") ) {
* response
* =response.replace(response.substring(response.length()-1), "" );
*
* }
*
* }
*
* if (response.length() <= 1) { response =
* "batch,stream,field,industry"; }
*/
break;
default:
break;
}
}
public class Connect extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(ConnectActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected String doInBackground(String... params) {
to_connect = responseText.toString();
String connect_url = Constants.REMOTE_URL + "/GenconianApi/reg2";
log("to", "connect url is:" + connect_url);
try {
JSONParser jsonParser = new JSONParser();
List<NameValuePair> Params = new ArrayList<NameValuePair>();
String res;
Intent email_Intent = getIntent();
email = email_Intent.getStringExtra("user_email");
type = email_Intent.getStringExtra("type");
loge("email in", "connectactivity is:" + email);
int len = response.length();
StringBuilder builder = new StringBuilder();
for (int i = 0; i < len - 1; i++) {
builder.append(Character.toLowerCase(response.charAt(i)));
}
Params.add(new BasicNameValuePair("email", email));
Params.add(new BasicNameValuePair("connected", builder
.toString()));
Log.e("responce", builder.toString());
JSONObject json = jsonParser.makeHttpRequest(connect_url,
"POST", Params);
loge("in reg2", json.toString());
JSONObject obj = json.getJSONObject("Status");
loge("obj is", obj.toString());
status = obj.getString("status");
loge("user", "status is:" + status);
success = Integer.parseInt(status);
loge("chk", "rslt code is:" + success);
if (success == 1) {
Intent k = new Intent(ConnectActivity.this,
FindFriends.class);
loge("chk", "inside success:" + success);
k.putExtra("user_email", email);
k.putExtra("type", type);
overridePendingTransition(R.anim.slide_in, R.anim.slide_out);
startActivity(k);
loge("email", "" + email);
return json.getString(Constants.TAG_MESSAGE);
} else {
Log.e("Login Failure!",
json.getString(Constants.TAG_MESSAGE));
return json.getString(Constants.TAG_MESSAGE);
}
}
catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
pDialog.dismiss();
}
}
#Override
public void onBackPressed() {
// TODO Auto-generated method stub
super.onBackPressed();
Intent i = new Intent(ConnectActivity.this, More.class);
i.putExtra("user-email", email);
i.putExtra("type", type);
startActivity(i);
}
}
You can put all the checkboxes in a Collection of checkboxes.
Upon clicking submit button, loop through all checkboxes to see anyone of them is checked at that moment
Collection<CheckBox> boxes=new Vector<CheckBox>();
...
public void onClick(View v){
boolean anyoneChecked=false;
for(CheckBox b: boxes){
if(b.isChecked()){
anyoneChecked=true;
}
}
if(!anyoneChecked){
return;
}
// go to next activity
}

sending data from edit text with single button

![here there are 3 edit text box. where i am using json to check the login id and password details and another text box is for the selection of the server address. the only criteria is that all these should be done with a single button ie the login button.
can any one help me with the code]1
the code is as follows
package com.example.catxam;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONException;
import org.json.JSONObject;
import com.example.catxam.JSONParser;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.EditText;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;
public class Login extends Activity {
private EditText inputUserid, inputPassword, server;
TextView forgotPassword;
private Button b1;
public String serve;
// Progress Dialog
private ProgressDialog pDialog;
// JSON parser class
JSONParser jsonParser = new JSONParser();
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String Flag = "flag";
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.login);
inputUserid = (EditText) findViewById(R.id.Username_edit);
inputPassword = (EditText) findViewById(R.id.User_password);
server = (EditText) findViewById(R.id.serverSelection);
forgotPassword = (TextView) findViewById(R.id.forgotPassword);
forgotPassword.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent passForget = new Intent(getApplicationContext(),
ForgotPassword.class);
startActivity(passForget);
}
});
b1 = (Button) findViewById(R.id.loginbutton); // login button
b1.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
new CreateNewUser().execute();
new SelectServerAddress().execute();
}
});
}
// this class is for selection of the server address
class SelectServerAddress extends AsyncTask<String, String, String>{
#Override
protected String doInBackground(String... arg0) {
return null;
}
}
// this class is for the checking of the user login and password
//i.e. of first login and the next consecutive logins
class CreateNewUser extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Login.this);
pDialog.setMessage("Checking..");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/**
* Checking creditenials
* */
protected String doInBackground(String... args) {
String user = inputUserid.getText().toString();
String pswrd = inputPassword.getText().toString();
//if (serve == "")
//{
//serve = "192.168.0.101/gly_prov_V1";
//}
//else
//{
//serve = "glydenlewis.esy.es";
//}
// URL to check username & password
final String url_check_user = "http://" + serve +"/gly_prov_V1/android_check.php";
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("uname", user));
params.add(new BasicNameValuePair("psd", pswrd));
params.add(new BasicNameValuePair("server",serve));
// getting JSON Object
// Note that create product url accepts POST method
JSONObject json = jsonParser.makeHttpRequest(url_check_user,
"POST", params);
// check log cat from response
Log.d("Create Response", json.toString());
// check for success tag
try {
int success = json.getInt(TAG_SUCCESS);
int flag_ck = json.getInt(Flag);
if (success == 1) {
if (flag_ck == 0)
{
//First Time Login By User
Intent i = new Intent(getApplicationContext(), UpdateDetails.class);
startActivity(i);
finish(); // closing this screen
}
else
{
// successfully login
Intent i = new Intent(getApplicationContext(), MainActivity.class);
startActivity(i);
finish(); // closing this screen
}
} else {
Toast.makeText(getApplicationContext(), "Wrong Credentials", Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
}
}
You can execute tasks in serial manner. Take the output of first task as input to the second task.
But you have to implement a cancel mechanism if the activity is destroyed while your tasks is actually running. a simple approach is to make tasks references as a class member and cancel it when activity's onStop() method is called.
class static SelectServerAddress extends AsyncTask<String, String, String>{
#Override
protected String doInBackground(String... urls) {
return getAddress(urls[0]);
}
#Override
protected void onPostExecute(String serverAddress) {
// Call login service
mLoginTask = new CreateNewUser(serverAddress);
mLoginTask.execute();
}
}
Edit:
Update button click listener code to this:
b1.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
new SelectServerAdress().execute();
}
});
Then update SelectServerAdress class and add this method:
#Override
protected void onPostExecute(String serverAddress) {
serve = serverAddress;
new SelectServerAddress().execute();
}

Doing multiple overlay dynamically in Android and parsed XML latitude and longitude

I am writing an Android application that essentially parses XML data using Fwix's API. The parsing part is working fine. Here's my class, Parser:
package com.magadistudio_student_connect_2011.com;
import java.net.URL;
import java.util.ArrayList;
import org.xmlpull.v1.XmlPullParser;
import android.content.res.XmlResourceParser;
import android.util.Xml;
public class Parser {
//Feed Parsing Method
public ArrayList<Bakery> parse(String url) {
//Array of Episode Objects
ArrayList<Bakery> bakeries = null;
try {
//Encode the URL into a URL Object
URL bakery_feed_url = new URL(url);
//Open a Connection to the feed
XmlPullParser parser = Xml.newPullParser();
try {
parser.setInput(bakery_feed_url.openConnection().getInputStream(), null);
}
finally {
}
int event_type = parser.getEventType();
Bakery current_bakery = null;
boolean done = false;
//Parse the feed, start reading throughout the feed from top to bottom
while (event_type != XmlResourceParser.END_DOCUMENT && !done) {
String tag_name = null;
switch (event_type) {
//Found the start of the feed
case XmlResourceParser.START_DOCUMENT:
bakeries = new ArrayList<Bakery>();
break;
//Found a start tag
case XmlResourceParser.START_TAG:
//apply the data to our Episode object based on the tag name
tag_name = parser.getName();
if (tag_name.equalsIgnoreCase("place")) {
current_bakery = new Bakery();
}
else if(current_bakery != null) {
if (tag_name.equalsIgnoreCase("phone_number")){
current_bakery.setPhone(parser.nextText());
}else if(tag_name.equalsIgnoreCase("city")){
current_bakery.setCity(parser.nextText());
}else if(tag_name.equalsIgnoreCase("province")){
current_bakery.setState(parser.nextText());
}else if(tag_name.equalsIgnoreCase("address")){
current_bakery.setAddress(parser.nextText());
}else if(tag_name.equalsIgnoreCase("lat")){
current_bakery.setLatitude(parser.nextText());
//lat = Integer.parseInt(parser.getAttributeValue(null,"lat"));
}else if(tag_name.equalsIgnoreCase("postal_code")){
current_bakery.setZip(parser.nextText());
}else if(tag_name.equalsIgnoreCase("lng")){
current_bakery.setLongitude(parser.nextText());
//lon = Integer.parseInt(parser.getAttributeValue(null,"lng"));
}else if(tag_name.equalsIgnoreCase("name")){
current_bakery.setPlace_name(parser.nextText());
}
}
break;
//An end tag has been reached
case XmlResourceParser.END_TAG:
tag_name = parser.getName();
//End of an Episode Item
if (tag_name.equalsIgnoreCase("place") && current_bakery != null) {
bakeries.add(current_bakery);
//Reached the end of all bakeries, no more data to collect
}
else if (tag_name.equalsIgnoreCase("places")){
done = true;
}
break;
}
event_type = parser.next();
}
}
catch (Exception e) {
throw new RuntimeException(e);
}
//Return the Episode Array
return bakeries;
}
}
And here is my overlay class, Overlay:
package com.magadistudio_student_connect_2011.com;
import java.util.ArrayList;
import android.app.AlertDialog;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.widget.Toast;
import com.google.android.maps.ItemizedOverlay;
import com.google.android.maps.OverlayItem;
public class StudentItemizedOverlay extends ItemizedOverlay<OverlayItem> {
private ArrayList<OverlayItem> mOverlays = new ArrayList<OverlayItem>();
private Context mContext;
public StudentItemizedOverlay(Drawable defaultMarker) {
super(boundCenterBottom(defaultMarker));
// TODO Auto-generated constructor stub
}
public void addOverlay(OverlayItem overlay) {
mOverlays.add(overlay);
populate();
}
#Override
protected OverlayItem createItem(int i) {
return mOverlays.get(i);
}
#Override
public int size() {
// TODO Auto-generated method stub
return mOverlays.size();
}
public StudentItemizedOverlay(Drawable defaultMarker, Context context){
super(boundCenterBottom(defaultMarker));
mContext = context;
}
#Override
protected boolean onTap(int index) {
OverlayItem item = mOverlays.get(index);
// Toast.makeText(StudentItemizedOverlay.this, "Hello", Toast.LENGTH_LONG).show();
AlertDialog.Builder dialog = new AlertDialog.Builder(mContext);
dialog.setTitle(item.getTitle());
dialog.setMessage(item.getSnippet());
dialog.show();
return true;
}
}
And here is class BakeryActivity:
package com.magadistudio_student_connect_2011.com;
import java.util.ArrayList;
import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.Toast;
public class BakeryActivity extends Activity implements OnItemClickListener {
//RSS Feed URL
private final String CGR_FEED_URL = "http://www.codinggreenrobots.com/episodes/rss.xml";
//xml new feed
private final String SCHOOLS_URL = "http://www.fizber.com/xml_data/xml_school_data.xml?state=wa&city=spokane";
private final String BAKERY_RSS = "apigoeshere";
//XML Widgets
private ListView listview_bakery;
private ProgressBar progress_bar;
//Arrays of Episode Data
private ArrayList<String> bakery_name;
private ArrayList<String> bakery_address;
private ArrayList<String> bakery_phone;
private ArrayList<String> bakery_latitude;
private ArrayList<String> bakery_longitude;
private ArrayList<String> bakery_state;
private ArrayList<String> bakery_zip;
private ArrayList<String> bakery_city;
/*private ArrayList<String> school_latitude;
private ArrayList<String> school_longitude;
*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.bakery_view);
//XML Widgets by ID
listview_bakery = (ListView) findViewById(R.id.listview_bakeries);
listview_bakery.setOnItemClickListener(this);
/* ColorDrawable sage = new ColorDrawable(this.getResources().getColor(R.drawable.colors));
listview_bakery.setDivider(sage);
listview_bakery.setDividerHeight(1);*/
progress_bar = (ProgressBar) findViewById(R.id.progress_bar_bakery);
//Make Progress Bar Invisible
progress_bar.setVisibility(ProgressBar.INVISIBLE);
//Initialize Arrays
bakery_name = new ArrayList<String>();
bakery_address = new ArrayList<String>();
bakery_phone = new ArrayList<String>();
bakery_latitude = new ArrayList<String>();
bakery_longitude = new ArrayList<String>();
bakery_state = new ArrayList<String>();
bakery_zip = new ArrayList<String>();
bakery_city = new ArrayList<String>();
//school_latitude = new ArrayList<String>();
//school_longitude = new ArrayList<String>();
downloadBakeries(BAKERY_RSS);
}
private void downloadBakeries(String Url) {
//Make Progress Bar Visible While Downloading Feed
progress_bar.setVisibility(ProgressBar.VISIBLE);
Log.d("CGRParser", "Downloading Feed");
//Start an ASync Thread to take care of Downloading Feed
new DownloadBakeries().execute(Url);
}
private class DownloadBakeries extends AsyncTask<String, Integer, ArrayList<Bakery>> {
#Override
protected ArrayList<Bakery> doInBackground(String... url) {
//Download and Parse Feed
Parser parser = new Parser();
ArrayList<Bakery> bakeries = new ArrayList<Bakery>();
bakeries = parser.parse(url[0]);
return bakeries;
}
#Override
protected void onPostExecute(ArrayList<Bakery> result) {
//Feed has been Downloaded and Parsed, Display Data to User
Log.d("CGRParser", "Feed Download Complete");
//Toast.makeText(BakeryActivity.this, "onPost", Toast.LENGTH_SHORT).show();
displayBakeries(result);
}
}
private void displayBakeries(ArrayList<Bakery> bakeries) {
//Create String Arrays to seperate titles and dates
Log.d("CGRParser", "Displaying Episode Titles To User");
ArrayList<String> bakery_name = new ArrayList<String>();
ArrayList<String> bakery_address = new ArrayList<String>();
ArrayList<String> bakery_phone = new ArrayList<String>();
ArrayList<String> bakery_latitude = new ArrayList<String>();
ArrayList<String> bakery_longitude = new ArrayList<String>();
ArrayList<String> bakery_state = new ArrayList<String>();
ArrayList<String> bakery_zip = new ArrayList<String>();
ArrayList<String> bakery_city = new ArrayList<String>();
//ArrayList<String> school_longitude = new ArrayList<String>();
for (Bakery bakery : bakeries) {
//Log.d("CGRParser", "Episode Title: " + episode.getTitle());
bakery_phone.add(bakery.getPhone());
bakery_name.add(bakery.getPlace_name());
bakery_address.add(bakery.getAddress());
bakery_latitude.add(bakery.getLatitude());
bakery_longitude.add(bakery.getLongitude());
bakery_state.add(bakery.getState());
bakery_zip.add(bakery.getZip());
bakery_city.add(bakery.getCity());
//school_longitude.add(episode.getLongitude());
}
//Toast.makeText(BakeryActivity.this, "DisplayBakeries", Toast.LENGTH_SHORT).show();
this.bakery_phone = bakery_phone;
this.bakery_name = bakery_name;
this.bakery_address = bakery_address;
this.bakery_latitude = bakery_latitude;
this.bakery_longitude = bakery_longitude;
this.bakery_state = bakery_state;
this.bakery_zip = bakery_zip;
this.bakery_city = bakery_city;
//int myNum = 0; try { myNum = Integer.parseInt(bakery_latitude.getText().toString()); } catch(NumberFormatException nfe) { System.out.println("Could not parse " + nfe); }
//Create a ListAdapter to Display the Titles in the ListView
ListAdapter adapter = new ArrayAdapter<String>(this, R.layout.bakery_row, R.id.title, bakery_name);
listview_bakery.setAdapter(adapter);
//Set Progress Bar Invisible since we are done with it
progress_bar.setVisibility(ProgressBar.INVISIBLE);
}
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
startActivity(new Intent(BakeryActivity.this, Map.class));
//Display the Title and Date to the user when they click on an episode
Toast.makeText(this, "Name:" + bakery_name.get(position) + "\nphone: " + bakery_phone.get(position)+
"\nState: "+ bakery_state.get(position) + "\nAddress: "+ bakery_address.get(position)
+ "\nZip: "+ bakery_zip.get(position)+ "\nLat: " +bakery_latitude.get(position)+ "\nlon: "+ bakery_longitude.get(position), Toast.LENGTH_LONG).show();
}
}
I am able to do the XML parsing work fine, but THE PROBLEM is I can't figure out how to get the "lat" and "lng" that I have parsed (and put then into an ArrayList of Strings) and convert them into integers so I can show markers of the respective latitude and longitude location on the map.
OK, so Android's Google Maps native location API uses integers with 6 digits following the decimal point. Therefore, you want to remove the "." from the strings of integers you parsed out. Then, simply do a parseInt to attain the coordinates. With that, drop them into GeoPoints and add them to the overlay. It should be no problem.
Unless I'm missing something here, which is possible.

Categories

Resources