Spinner string not retrieved and passed to volleyrequest - java

I am wanting to get the string value from the spinner. I am currently using Volley in passing data but then it wasn't successful then. This is my RegisterActivity class:
public class RegUserPassClient extends AppCompatActivity implements AdapterView.OnItemSelectedListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_reg_user_pass_client);
final Spinner spinner = findViewById(R.id.genderSpinner);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.genderString, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(this);
final EditText regUserClient= (EditText) findViewById(R.id.regUserClient);
final EditText regPassClient= (EditText) findViewById(R.id.regPassClient);
final EditText regClientName = (EditText) findViewById(R.id.registerClientName);
final EditText regClientNumber = (EditText) findViewById(R.id.registerClientNumber);
final EditText regClientAddress = (EditText) findViewById(R.id.registerClientAddress);
final EditText regClientOccupation = (EditText) findViewById(R.id.registerClientOccupation);
final EditText regClientGender = (EditText) findViewById(R.id.registerClientGender);
final EditText regClientBirthDate = (EditText) findViewById(R.id.registerClientBirthDate);
final TextView clientUser = (TextView) findViewById(R.id.clientUserType);
final Button regClientBtn = (Button) findViewById(R.id.regClient);
final CheckBox toggle = (CheckBox) findViewById(R.id.checkBoxLog);
toggle.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
if(b){
regPassClient.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
}else{
regPassClient.setTransformationMethod(PasswordTransformationMethod.getInstance());
}
}
});
regClientBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final String username = regUserClient.getText().toString();
final String password = regPassClient.getText().toString();
final String name = regClientName.getText().toString();
final String number = regClientNumber.getText().toString();
final String gender = spinner.toString();
final String address = regClientAddress.getText().toString();
final String occupation = regClientOccupation.getText().toString();
final String birthDate = regClientBirthDate.getText().toString();
final String userType = clientUser.getText().toString();
if(!username.isEmpty() && !password.isEmpty() &&
!name.isEmpty() && !address.isEmpty() &&
!occupation.isEmpty() && !gender.isEmpty() &&
!birthDate.isEmpty() && !number.isEmpty()) {
Response.Listener<String> responseListener = new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject jsonResponse = new JSONObject(response);
boolean success = jsonResponse.getBoolean("success");
if (success) {
Intent intent = new Intent(RegUserPassClient.this, LoginRegister.class);
RegUserPassClient.this.startActivity(intent);
Toast.makeText(RegUserPassClient.this,"SuccessFully Registered! Log in your details now!",Toast.LENGTH_LONG).show();
} else {
AlertDialog.Builder builder = new AlertDialog.Builder(RegUserPassClient.this);
builder.setMessage("Username Has already been taken!")
.setNegativeButton("Retry", null)
.create()
.show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
};
RegUserPassClientRequest registerRequest = new RegUserPassClientRequest(username, password, name, number, gender, address, occupation, birthDate, userType, responseListener);
RequestQueue queue = Volley.newRequestQueue(RegUserPassClient.this);
queue.add(registerRequest);
}else if(username.isEmpty()){
regUserClient.setError("Please insert a username");
}else if(password.isEmpty()){
regPassClient.setError("Please put your password");
}else if(name.isEmpty()){
regClientName.setError("Please input your name");
}else if(number.isEmpty()){
regClientNumber.setError("Put your phone number please");
}else if(address.isEmpty()){
regClientGender.setError("Please state your gender");
}else if(occupation.isEmpty()){
regClientAddress.setError("Please put your address");
}else if(gender.isEmpty()){
regClientOccupation.setError("Please state occupation");
}else if(birthDate.isEmpty()){
regClientBirthDate.setError("Please select your Birth Date");
}
}
});
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int i, long l) {
final String text = parent.getItemAtPosition(i).toString();
Toast.makeText(parent.getContext(), text, Toast.LENGTH_SHORT).show();
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
}
My functions for getting the spinner value are under the volleyrequest. I guess that is where my code is wrong but I don't really know what to put and where is the wrong thing.

It was just
final String gender = spinner.getSelectedItem().toString();
after all! Thanks anyways for viewing guys!

Related

Not able to access global variables across activity

In this code, I want the strings sh1, shg2 and shg3 to be displayed according to the users input in text edit. I have created a saver class to set and retrieve the variables. But although they are global variables, shg1 ,sh2 and sh3 do not store the values and don't display anything. Thanks for your help
Saver class:
public class Saver extends Application {
public String shg1,shg2,shg3;
public String getShg1() {
return shg1;
}
public void setShg1(String s1) {
shg1= s1;
}
public String getShg2() {
return shg2;
}
public void setShg2(String s1) {
shg2= s1;
}
public String getShg3() {
return shg3;
}
public void setShg3(String s1) {
shg3= s1;
}
}
SHGDetails class:
public class SHGDetails extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_shgdetails);
final EditText e1 = (EditText) findViewById(R.id.shg1);
final EditText e2 = (EditText) findViewById(R.id.shg2);
final EditText e3 = (EditText) findViewById(R.id.shg3);
final Button b1 = (Button) findViewById(R.id.b3);
final LinearLayout l = findViewById(R.id.linearl);
final TextView t1 = findViewById(R.id.textView2);
final TextView t2 = findViewById(R.id.textView3);
final TextView t3 = findViewById(R.id.textView4);
b1.setVisibility(View.INVISIBLE);
e1.setVisibility(View.INVISIBLE);
e2.setVisibility(View.INVISIBLE);
e3.setVisibility(View.INVISIBLE);
Boolean isFirstRun = getSharedPreferences("PREFERENCE", MODE_PRIVATE)
.getBoolean("isFirstRun", true);
Saver s = new Saver();
if (isFirstRun) {
//show start activity
b1.setVisibility(View.VISIBLE);
e1.setVisibility(View.VISIBLE);
e2.setVisibility(View.VISIBLE);
e3.setVisibility(View.VISIBLE);
String text = e1.getText().toString();
String text2 = e2.getText().toString();
String text3 = e3.getText().toString();
((Saver) this.getApplication()).setShg1(text);
((Saver) this.getApplication()).setShg2(text2);
((Saver) this.getApplication()).setShg3(text3);
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
l.removeView(e1);
l.removeView(e2);
l.removeView(e3);
l.removeView(b1);
getSharedPreferences("PREFERENCE", MODE_PRIVATE).edit()
.putBoolean("isFirstRun", false).commit();
}
});
}
else {
Toast.makeText(getApplicationContext(), s.getShg1(),Toast.LENGTH_LONG).show();
t1.setText(((Saver) this.getApplication()).getShg1());
t2.setText(((Saver) this.getApplication()).getShg2());
t3.setText(((Saver) this.getApplication()).getShg3());
}
}
}
You need to fetch data and set when user press the button so there's no values before button click so do this
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//
String text = e1.getText().toString();
String text2 = e2.getText().toString();
String text3 = e3.getText().toString();
((Saver) SHGDetails.this.getApplication()).setShg1(text);
((Saver) SHGDetails.this.getApplication()).setShg2(text2);
((Saver) SHGDetails.this.getApplication()).setShg3(text3);
l.removeView(e1);
l.removeView(e2);
l.removeView(e3);
l.removeView(b1);
getSharedPreferences("PREFERENCE", MODE_PRIVATE).edit()
.putBoolean("isFirstRun", false).commit();
}
});
and seems like you already have registered your application in manifest.

JSON Parsing error at the runtime

I am the student and i'm learning android, i got following error and i can't find out the solution of that error, plz help me to solve that error. Thank you...
java.lang.RuntimeException: Unable to start activity
ComponentInfo{com.sumit.json1/com.sumit.json1.ParseJSON}:
java.lang.NullPointerException: Attempt to invoke virtual method
'org.json.JSONObject org.json.JSONArray.getJSONObject(int)' on a null object
reference.
There is no issue of connectivity to database. My php code is which is hosted on hostinger.in
<?
//these are the server details
//the username is root by default in case of xampp
//password is nothing by default
//and lastly we have the database named android. if your database name is
different you have to change it
$servername = "mysql.hostinger.in";
$username = "username";
$password = "*********";
$database = "database_name";
//creating a new connection object using mysqli
$conn = new mysqli($servername, $username, $password, $database);
//if there is some error connecting to the database
//with die we will stop the further execution by displaying a message
causing the error
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
//if everything is fine
//creating an array for storing the data
$heroes = array();
//this is our sql query
$sql = "SELECT id, name, email, username, password, gender, lat, lon FROM
appusers;";
//creating an statment with the query
$stmt = $conn->prepare($sql);
//executing that statment
$stmt->execute();
//binding results for that statment
$stmt->bind_result($id, $name, $email, $username, $password, $gender, $lat,
$lon);
//looping through all the records
while($stmt->fetch()){
//pushing fetched data in an array
$temp = [
'id'=>$id,
'name'=>$name,
'email'=>$email,
'username'=>$username,
'password'=>$password,
'gender'=>$gender,
'lat'=>$lat,
'lon'=>$lon
];
//pushing the array inside the hero array
array_push($heroes, $temp);
}
//displaying the data in json format
echo json_encode($heroes);
For parsing json my android code is i.e. ParseJSON.java
public class ParseJSON extends ActionBarActivity implements
View.OnClickListener{
private String myJSONString;
private static final String JSON_ARRAY ="heroes";
private static final String ID = "id";
private static final String NAME= "name";
private static final String EMAIL = "email";
private static final String USERNAME= "username";
private static final String PASSWORD = "password";
private static final String GENDER = "gender";
private static final String LAT = "lat";
private static final String LON = "lon";
private JSONArray users = null;
private int TRACK = 0;
private EditText editTextId;
private EditText editTextName;
private EditText editTextEmail;
private EditText editTextUserName;
private EditText editTextPassword;
private EditText editTextGender;
private EditText editTextLat;
private EditText editTextLon;
Button btnPrev;
Button btnNext;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_parse_json);
Intent intent = getIntent();
myJSONString = intent.getStringExtra(MainActivity.MY_JSON);
editTextId = (EditText) findViewById(R.id.editTextID);
editTextName = (EditText) findViewById(R.id.editTextName);
editTextEmail = (EditText) findViewById(R.id.editTextEmail);
editTextUserName = (EditText) findViewById(R.id.editTextUsername);
editTextPassword = (EditText) findViewById(R.id.editTextPassword);
editTextGender = (EditText) findViewById(R.id.editTextGender);
editTextLat = (EditText) findViewById(R.id.editTextLat);
editTextLon = (EditText) findViewById(R.id.editTextLon);
btnPrev = (Button) findViewById(R.id.buttonPrev);
btnNext = (Button) findViewById(R.id.buttonNext);
btnPrev.setOnClickListener(this);
btnNext.setOnClickListener(this);
extractJSON();
showData();
}
private void extractJSON(){
try {
JSONObject jsonObject = new JSONObject(myJSONString);
users = jsonObject.getJSONArray(JSON_ARRAY);
} catch (JSONException e) {
e.printStackTrace();
}
}
private void moveNext(){
if(TRACK<users.length()){
TRACK++;
}
showData();
}
private void movePrev(){
if(TRACK>0){
TRACK--;
}
showData();
}
private void showData(){
try {
JSONObject jsonObject = users.getJSONObject(TRACK);
editTextId.setText(jsonObject.getString(ID));
editTextName.setText(jsonObject.getString(NAME));
editTextEmail.setText(jsonObject.getString(EMAIL));
editTextUserName.setText(jsonObject.getString(USERNAME));
editTextPassword.setText(jsonObject.getString(PASSWORD));
editTextGender.setText(jsonObject.getString(GENDER));
editTextLat.setText(jsonObject.getString(LAT));
editTextLon.setText(jsonObject.getString(LON));
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_parse_json, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onClick(View v) {
if(v == btnNext){
moveNext();
}
if(v == btnPrev){
movePrev();
}
}
}
In my android project MainActivity.java is given bellow if any error find out plz help me to resove
public class MainActivity extends ActionBarActivity implements View.OnClickListener {
private TextView textViewJSON;
private Button buttonGet;
private Button buttonParse;
public static final String MY_JSON ="MY_JSON";
private static final String JSON_URL = "http://mydatabasedb.16mb.com/JSON1/send-data1.php";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textViewJSON = (TextView) findViewById(R.id.textViewJSON);
textViewJSON.setMovementMethod(new ScrollingMovementMethod());
buttonGet = (Button) findViewById(R.id.buttonGet);
buttonParse = (Button) findViewById(R.id.buttonParse);
buttonGet.setOnClickListener(this);
buttonParse.setOnClickListener(this);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onClick(View v) {
if(v==buttonGet){
getJSON(JSON_URL);
}
if(v==buttonParse){
showParseActivity();
}
}
private void showParseActivity() {
Intent intent = new Intent(this, ParseJSON.class);
intent.putExtra(MY_JSON,textViewJSON.getText().toString());
startActivity(intent);
}
private void getJSON(String url) {
class GetJSON extends AsyncTask<String, Void, String>{
ProgressDialog loading;
#Override
protected void onPreExecute() {
super.onPreExecute();
loading = ProgressDialog.show(MainActivity.this, "Please Wait...",null,true,true);
}
#Override
protected String doInBackground(String... params) {
String uri = params[0];
BufferedReader bufferedReader = null;
try {
URL url = new URL(uri);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
StringBuilder sb = new StringBuilder();
bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));
String json;
while((json = bufferedReader.readLine())!= null){
sb.append(json+"\n");
}
return sb.toString().trim();
}catch(Exception e){
return null;
}
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
loading.dismiss();
textViewJSON.setText(s);
}
}
GetJSON gj = new GetJSON();
gj.execute(url);
}
}
users = jsonObject.getJSONArray(JSON_ARRAY);
This attempts to parse a list at the "heroes" key, but there is no "heroes" key the JSON document. You are encoding a list, not an object.
Open the URL that returns the JSON in a browser, and the problem should be apparent.

API Not Searching Food Database When Clicking The Search Button get error Permission denied

Hey Guys I'm working on a calorie app where the user clicks the search button and it supposed to retrieve information from the USDA Food Composition Databases API. For some reason it doesnt do anything and I noticed I get an error in the Logcat.
Im new to Android and to API. Thanks again in advance..
logcat :
Here is the logcat Error I'm Getting
AddEntry.java
public class AddEntry extends Fragment implements View.OnClickListener {
EditText FoodET,CalorieET;
ImageButton Savebtn, Cancelbtn;
Button searchbutton;
String foodET,calorieET;
//database
private DatabaseHandler dba;
public AddEntry() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View myView = inflater.inflate(R.layout.fragment_add_entry, container,
false);
Savebtn = (ImageButton) myView.findViewById(R.id.SaveBtn);
Savebtn.setBackgroundColor(Color.TRANSPARENT);
Savebtn.setOnClickListener(this);
searchbutton = (Button) myView.findViewById(R.id.SearchButton);
searchbutton.setOnClickListener(this);
Cancelbtn = (ImageButton) myView.findViewById(R.id.CancelBtn);
Cancelbtn.setBackgroundColor(Color.TRANSPARENT);
Cancelbtn.setOnClickListener(this);
return myView;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
FoodET= (EditText)view.findViewById(R.id.foodEditText);
FoodET.setInputType(InputType.TYPE_CLASS_TEXT);
CalorieET=(EditText)view.findViewById(R.id.caloriesEditText);
CalorieET.setInputType(InputType.TYPE_CLASS_NUMBER);
foodET = ((EditText)
view.findViewById(R.id.foodEditText)).getText().toString();
calorieET = ((EditText)
view.findViewById(R.id.caloriesEditText)).getText().toString();
}
public void saveDataToDB (){
Food food = new Food();
String FoodName = FoodET.getText().toString().trim();
String calString = CalorieET.getText().toString().trim();
//convert the claories numbers to text
if (!calString.equals("")) {
int cal = Integer.parseInt(calString);
food.setFoodName(FoodName);
food.setCalories(cal);
//call addFood method from the DatabaseHandler
dba.addFood(food);
dba.close();
//clear the editTexts
FoodET.setText("");
CalorieET.setText("");
//take the user to the next screen
//
((appMain) getActivity()).loadSelection(0);
;
}
else
{
Toast.makeText(getActivity(), "Please enter information",
Toast.LENGTH_LONG).show();
}
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.SearchButton:
InputMethodManager inputManager = (InputMethodManager)
getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(
getActivity().getCurrentFocus().getWindowToken(),
InputMethodManager.HIDE_NOT_ALWAYS);
FoodSearch search = new FoodSearch(foodET,CalorieET );
search.execute();
break;
case R.id.SaveBtn:
foodET = FoodET.getText().toString();
calorieET=CalorieET.getText().toString();
if (FoodET.getText().toString().equals(null) ||
CalorieET.getText().toString().equals(null)||
CalorieET.getText().toString().equals("")){
Toast.makeText(getActivity(), "Please enter information",
Toast.LENGTH_LONG).show();
}
((appMain) getActivity()).loadSelection(0);
break;
case R.id.CancelBtn:
// EditText descriptionET=
(EditText)getView().findViewById(R.id.foodEditText);
//descriptionET.setText("");
//EditText calorieET=
(EditText)getView().findViewById(R.id.caloriesEditText);
//calorieET.setText("");
((appMain) getActivity()).loadSelection(0);
break;
}
}
#Override
public void onDestroy() {
super.onDestroy();
}
#Override
public void onDetach() {
super.onDetach();
}
private class FoodSearch extends AsyncTask<Void, Void, String> {
String food;
EditText calories;
FoodSearch(String food, EditText calories){
this.food = food;
this.calories = calories;
}
#Override
protected String doInBackground(Void... params) {
try {
food = food.replaceAll(" ", "%20");
URL url = new URL("http://api.nal.usda.gov/ndb/search/?
format=JSON&q=" + food
+"&max=1&offset=0&sort=r&api_
key=2PmoCzLAhkNUeJcwq2VfOaSNY66UgFVDEcco2qMP");
HttpURLConnection urlConnection = (HttpURLConnection)
url.openConnection();
try {
BufferedReader bufferedReader = new BufferedReader(new
InputStreamReader(urlConnection.getInputStream()));
StringBuilder stringBuilder = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
stringBuilder.append(line).append("\n");
}
bufferedReader.close();
String result = stringBuilder.toString();
if(result.contains("zero results")) {
String s = "empty";
return s;
}
JSONObject object = (JSONObject) new
JSONTokener(result).nextValue();
JSONObject list = object.getJSONObject("list");
JSONArray items = list.getJSONArray("item");
String item = items.get(0).toString();
int i = item.indexOf("ndbno\":\"") + 8;
int f = item.indexOf("\"", i);
String ndbno = item.substring(i,f);
Log.d("DEBUG", ndbno);
URL url2 = new URL("http://api.nal.usda.gov/ndb/reports/?
ndbno="+ ndbno +"&type=b&format=JSON&api_
key=2PmoCzLAhkNUeJcwq2VfOaSNY66UgFVDEcco2qMP");
HttpURLConnection urlConnection2 = (HttpURLConnection)
url2.openConnection();
BufferedReader bufferedReader2 = new BufferedReader(new
InputStreamReader(urlConnection2.getInputStream()));
StringBuilder stringBuilder2 = new StringBuilder();
String line2;
while ((line2 = bufferedReader2.readLine()) != null) {
stringBuilder2.append(line2).append("\n");
}
bufferedReader2.close();
String res = stringBuilder2.toString();
int index = res.indexOf("\"unit\": \"kcal\",") + 46;
int index2 = res.indexOf("\"", index);
String calories = res.substring(index,index2);
urlConnection2.disconnect();
return calories;
}
finally{
urlConnection.disconnect();
}
}
catch(Exception e) {
Log.e("ERROR", e.getMessage(), e);
String s = "empty";
return s;
}
}
protected void onPostExecute(String response) {
if(!response.isEmpty() && !response.equals("empty")) {
calories.setText(response);
} else {
AlertDialog foodNotFound = new
AlertDialog.Builder(getContext()).create();
foodNotFound.setTitle("Error");
foodNotFound.setMessage("Food not found :(");
foodNotFound.setButton(AlertDialog.BUTTON_NEUTRAL, "OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int
which) {
dialog.dismiss();
}
});
}
}
}
}
You Can call the Async task within the same class and SHow alert dialog in the onPost execute section
public class AddEntry extends Fragment implements View.OnClickListener {
EditText DescriptionET,CalorieET; ImageButton Savebtn, Cancelbtn; Button searchbutton; String description , calorieAmt; //database
private DatabaseHandler dba;
public AddEntry() {
// Required empty public constructor
}
#Override public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) { // Inflate the layout for this fragment View myView = inflater.inflate(R.layout.fragment_add_entry, container, false);
Savebtn = (ImageButton) myView.findViewById(R.id.SaveBtn);
Savebtn.setBackgroundColor(Color.TRANSPARENT);
Savebtn.setOnClickListener(this);
searchbutton = (Button) myView.findViewById(R.id.SearchButton);
searchbutton.setOnClickListener(this);
Cancelbtn = (ImageButton) myView.findViewById(R.id.CancelBtn);
Cancelbtn.setBackgroundColor(Color.TRANSPARENT);
Cancelbtn.setOnClickListener(this);
return myView;
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
DescriptionET= (EditText)view.findViewById(R.id.foodEditText);
DescriptionET.setInputType(InputType.TYPE_CLASS_TEXT);
CalorieET=(EditText)view.findViewById(R.id.caloriesEditText);
CalorieET.setInputType(InputType.TYPE_CLASS_NUMBER);
//save to database:
}
public void saveDataToDB (){
Food food = new Food();
String name = DescriptionET.getText().toString().trim();
String calString = CalorieET.getText().toString().trim();
//convert the claories numbers to text
if (!calString.equals("")) {
int cal = Integer.parseInt(calString);
food.setFoodName(name);
food.setCalories(cal);
//call addFood method from the DatabaseHandler
dba.addFood(food);
dba.close();
//clear the editTexts
DescriptionET.setText("");
CalorieET.setText("");
//take the user to the next screen
//
((appMain) getActivity()).loadSelection(0);
;
}
else
{
Toast.makeText(getActivity(), "Please enter information",
Toast.LENGTH_LONG).show();
}
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.SearchButton:
InputMethodManager inputManager = (InputMethodManager)
getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(
getActivity().getCurrentFocus().getWindowToken(),
InputMethodManager.HIDE_NOT_ALWAYS);
FoodSearch search = new FoodSearch(description,CalorieET);
search.execute();
break;
case R.id.SaveBtn:
description = DescriptionET.getText().toString();
calorieAmt=CalorieET.getText().toString();
if (DescriptionET.getText().toString().equals(null) ||
CalorieET.getText().toString().equals(null)||
CalorieET.getText().toString().equals("")){
Toast.makeText(getActivity(), "Please enter information",
Toast.LENGTH_LONG).show();
}
((appMain) getActivity()).loadSelection(0);
break;
case R.id.CancelBtn:
// EditText descriptionET=
(EditText)getView().findViewById(R.id.foodEditText);
//descriptionET.setText("");
//EditText calorieET=
(EditText)getView().findViewById(R.id.caloriesEditText);
//calorieET.setText("");
((appMain) getActivity()).loadSelection(0);
break;
}
}
#Override
public void onDestroy() {
super.onDestroy();
}
#Override
public void onDetach() {
super.onDetach();
}
}
private class FoodSearch extends AsyncTask<Void, Void, String>{
String food;
EditText calories;
FoodSearch(String food, EditText calories){
this.food = food;
this.calories = calories;
}
#Override
protected String doInBackground(Void... params) {
try {
food = food.replaceAll(" ", "%20");
URL url = new URL("http://api.nal.usda.gov/ndb/search/?
format=JSON&q=" + food +"&max=1&offset=0&sort=r&api_key=2PmoCzLAhkNUeJcwq2VfOaSNY66UgFVDEcco2qMP");
HttpURLConnection urlConnection = (HttpURLConnection)
url.openConnection();
try {
BufferedReader bufferedReader = new BufferedReader(new
InputStreamReader(urlConnection.getInputStream()));
StringBuilder stringBuilder = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
stringBuilder.append(line).append("\n");
}
bufferedReader.close();
String result = stringBuilder.toString();
if(result.contains("zero results")) {
String s = "empty";
return s;
}
JSONObject object = (JSONObject) new
JSONTokener(result).nextValue();
JSONObject list = object.getJSONObject("list");
JSONArray items = list.getJSONArray("item");
String item = items.get(0).toString();
int i = item.indexOf("ndbno\":\"") + 8;
int f = item.indexOf("\"", i);
String ndbno = item.substring(i,f);
Log.d("DEBUG", ndbno);
URL url2 = new URL("http://api.nal.usda.gov/ndb/reports/?ndbno="+ ndbno +"&type=b&format=JSON&api_key=2PmoCzLAhkNUeJcwq2VfOaSNY66UgFVDEcco2qMP");
HttpURLConnection urlConnection2 = (HttpURLConnection)
url2.openConnection();
BufferedReader bufferedReader2 = new BufferedReader(new
InputStreamReader(urlConnection2.getInputStream()));
StringBuilder stringBuilder2 = new StringBuilder();
String line2;
while ((line2 = bufferedReader2.readLine()) != null) {
stringBuilder2.append(line2).append("\n");
}
bufferedReader2.close();
String res = stringBuilder2.toString();
int index = res.indexOf("\"unit\": \"kcal\",") + 46;
int index2 = res.indexOf("\"", index);
String calories = res.substring(index,index2);
urlConnection2.disconnect();
return calories;
}
finally{
urlConnection.disconnect();
}
}
catch(Exception e) {
Log.e("ERROR", e.getMessage(), e);
String s = "empty";
return s;
}
}
protected void onPostExecute(String response) {
if(!response.isEmpty() && !response.equals("empty")) {
calories.setText(response);
} else {
AlertDialog foodNotFound = new
AlertDialog.Builder(getContext()).create();
foodNotFound.setTitle("Error");
foodNotFound.setMessage("Food not found :(");
foodNotFound.setButton(AlertDialog.BUTTON_NEUTRAL, "OK",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
}
}
}

Android list app using GSON

I am making a FuelLog app keep a log of fuel fill-ups at gas stations. I am having troubles using GSON to save things into the list as strings. The reason why I am saving an object is because each object (FuelLog) has many attributes including: "Gas Type", "Odometer Reading". etc. I would like to show those attributes on the list rather than "com.example.arshadhusain.fuelTracker.FuelLog#b1a33588" for example. Soon I would also like to edit these list items as well.
Here's how the list looks like so far.
Here's the class for the FuelLog:
public class FuelLog {
public String date;
public String station;
public String odometer;
public String fuelGrade;
public String fuelAmount;
public String fuelUnitCost;
public String fuelCost;
public FuelLog (String date, String station, String odometer, String fuelGrade, String fuelAmount, String fuelUnitCost, String fuelCost) {
this.date = date;
this.station = station;
this.odometer = odometer;
this.fuelGrade = fuelGrade;
this.fuelAmount = fuelAmount;
this.fuelUnitCost = fuelUnitCost;
this.fuelCost = fuelCost;
}
}
Here's the class that saves each log and updates the list (a prompt open for the user to add the attributes).
public class MainActivity extends Activity implements AdapterView.OnItemClickListener {
private Button button;
private EditText editTextMainScreen;
private ListView oldTweetsList;
private static final String FILENAME = "FuelTracker.sav";
private ArrayList<FuelLog> FuelLogs = new ArrayList<FuelLog>();
ArrayAdapter<FuelLog> adapter;
final Context context = this;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// components from main.xml
button = (Button) findViewById(R.id.button);
//editTextMainScreen = (EditText) findViewById(R.id.editTextResult);
oldTweetsList = (ListView) findViewById(R.id.oldTweetsList);
loadFromFile();
adapter = new ArrayAdapter<FuelLog>(this,
R.layout.list_item, FuelLogs);
oldTweetsList.setAdapter(adapter);
oldTweetsList.setOnItemClickListener(this);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
// get prompts.xml view
LayoutInflater layoutInflater = LayoutInflater.from(context);
View promptView = layoutInflater.inflate(R.layout.prompts, null);
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context);
// set prompts.xml to be the layout file of the alertdialog builder
alertDialogBuilder.setView(promptView);
final EditText input = (EditText) promptView.findViewById(R.id.userInput);
final EditText input1 = (EditText) promptView.findViewById(R.id.userInput1);
final EditText input2 = (EditText) promptView.findViewById(R.id.userInput2);
final EditText input3 = (EditText) promptView.findViewById(R.id.userInput3);
final EditText input4 = (EditText) promptView.findViewById(R.id.userInput4);
final EditText input5 = (EditText) promptView.findViewById(R.id.userInput5);
final EditText input6 = (EditText) promptView.findViewById(R.id.userInput6);
// setup a dialog window
alertDialogBuilder
.setCancelable(false)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// get user input and set it to result
//editTextMainScreen.setText(input.getText());
setResult(RESULT_OK);
String station = input.getText().toString();
String odometer = input1.getText().toString();
String fuelGrade = input2.getText().toString();
String fuelAmount = input3.getText().toString();
String fuelUnitCost = input4.getText().toString();
String fuelCost = input5.getText().toString();
String date = input6.getText().toString(); //Date
FuelLog log = new FuelLog(date, station, odometer, fuelGrade, fuelAmount, fuelUnitCost, fuelCost);
FuelLogs.add(log);
adapter.notifyDataSetChanged();
saveInFile();
finish();
}
})
.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
// create an alert dialog
AlertDialog alertD = alertDialogBuilder.create();
alertD.show();
}
});
}
You can just Override toString() method in your FuelLog class like this:
#Override
public String toString() {
return "date = " + date + " station = " + station; // ...etc
}
or
Create custom adapter and in getView() method set you fields;
You can get rid off the problem by just overriding the ToString method of the class FuelLog, if you dont do that, the the list is printing out the hashcode of every FuelLog object added to your list.

database query returning all values instead matching the entered column detail

I am developing a android application where user can search his details by filling any of the column in multiple field form, no need to fill all the field, just has to enter any one column. But the Problem is instead of matching the entered field column it is displaying whole database.i tried filling 1 field , 2 field whatever i fill or even just click submit without entering anything it return whole database! where am i wrong?
Search.java
public class Search extends Activity {
SqlHandler sqlHandler;
EditText txtname, txt_relative_type, txt_father, txt_id, txt_part, txt_sl,
txt_age, txt_house, txt_poling, txt_section, txt_ac_name,
txt_ac_no;
ImageButton reset_btn, submit_btn;
RadioButton RdioBtn_male,RdioBtn_female;
ListView lvCustomList;
String intentname,intentacno,intentpartno,intentpoll,intentsl,intenthouse,intentAc_name,intentRelative,intentfather,intentage,intentsection;
String name1,acno,part,poll,sl,house,Ac_name,Relative,father,age,id,section,intentid;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_search);
txtname = (EditText) findViewById(R.id.editText);
txt_relative_type = (EditText) findViewById(R.id.editText3);
txt_father = (EditText) findViewById(R.id.editText1);
txt_id = (EditText) findViewById(R.id.editText4);
txt_part = (EditText) findViewById(R.id.editText5);
txt_sl = (EditText) findViewById(R.id.editText6);
txt_age = (EditText) findViewById(R.id.editText7);
txt_house = (EditText) findViewById(R.id.editText8);
txt_poling = (EditText) findViewById(R.id.editText9);
txt_section = (EditText) findViewById(R.id.editText10);
txt_ac_name = (EditText) findViewById(R.id.editText11);
txt_ac_no = (EditText) findViewById(R.id.editText12);
reset_btn = (ImageButton) findViewById(R.id.imageButton1);
submit_btn = (ImageButton) findViewById(R.id.imageButton2);
submit_btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
name1 = txtname.getText().toString();
acno = txt_ac_no.getText().toString();
part = txt_part.getText().toString();
poll = txt_poling.getText().toString();
sl = txt_sl.getText().toString();
house = txt_house.getText().toString();
Ac_name = txt_ac_name.getText().toString();
Relative= txt_relative_type.getText().toString();
father = txt_father.getText().toString();
age = txt_age.getText().toString();
id = txt_id.getText().toString();
section = txt_section.getText().toString();
Intent i = new Intent (Search.this,Listdisplay.class);
i.putExtra(intentname, name1);
i.putExtra(intentacno, acno);
i.putExtra(intentpartno, part);
i.putExtra(intentpoll, poll);
i.putExtra(intentsl, sl);
i.putExtra(intentAc_name, Ac_name);
i.putExtra(intentRelative, Relative);
i.putExtra(intentfather, father );
i.putExtra(intentage, age);
i.putExtra(intentid, id);
i.putExtra(intentsection, section);
i.putExtra(intenthouse, house);
startActivity(i);
}
});
reset_btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
txtname.setText("");
txt_relative_type.setText("");
txt_father.setText("");
txt_id.setText("");
txt_part.setText("");
txt_sl.setText("");
txt_age.setText("");
txt_house.setText("");
txt_poling.setText("");
txt_section.setText("");
txt_ac_name.setText("");
txt_ac_no.setText("");
}
});
}}
Listdisplay.java
public class Listdisplay extends Activity {
ListView lvCustomList;
String intentname,intentacno,intentpartno,intentpoll,intentsl,intentAc_name,intentRelative,intentfather,intentage,intentid,intentsection,intenthouse;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.searchlayout);
Intent myIntent = getIntent();
String name_search = myIntent.getStringExtra(intentname);
String acno_search = myIntent.getStringExtra(intentacno);
String part_search = myIntent.getStringExtra(intentpartno);
String address_search = myIntent.getStringExtra(intentpoll);
String sl_search = myIntent.getStringExtra(intentsl);
String area_search = myIntent.getStringExtra(intentAc_name);
String guardian_search = myIntent.getStringExtra(intentRelative);
String father_search = myIntent.getStringExtra(intentfather);
String age_search1 = myIntent.getStringExtra(intentage);
String idcard_search = myIntent.getStringExtra(intentid);
String section_search = myIntent.getStringExtra(intentsection);
String house_search = myIntent.getStringExtra(intenthouse);
lvCustomList = (ListView) findViewById(R.id.listView1);
showList(name_search,acno_search,part_search,address_search,sl_search,area_search,guardian_search,father_search,age_search1,idcard_search,section_search,house_search);
}
private void showList(String name_search,String acno_search,String part_search, String address_search,String sl_search,String area_search,String guardian_search,String father_search,String age_search1,String idcard_search,String section_search,String house_search ) {
SqlHandler sql = new SqlHandler(this);
ArrayList<contactlistitems> contactlist = new ArrayList<contactlistitems>();
contactlist.clear();
String query="SELECT * FROM VoterSearch WHERE name LIKE (case when '"+name_search+"'!='' then '%"+name_search+"%' else name end) and PollAddress LIKE (case when '"+address_search+"'!='' then '%"+address_search+"%' else PollAddress end) and Relation LIKE (case when '"+guardian_search+"'!='' then '%"+guardian_search+"%' else Relation end) and FatherName LIKE (case when '"+father_search+"'!='' then '%"+father_search+"%' else FatherName end) and AcName LIKE (case when '"+area_search+"'!='' then '%"+area_search+"%' else AcName end)"
+" and Section LIKE (case when '"+section_search+"'!='' then '%"+section_search+"%' else Section end)"+" and IdCard LIKE (case when '"+idcard_search+"'!='' then '%"+idcard_search+"%' else IdCard end)"+" and SlNo = (case when '"+sl_search+"'!='' then '"+sl_search+"' else SlNo end) and AcNo = (case when '"+acno_search+"'!='' then '"+acno_search+"' else AcNo end) and PartNo = (case when '"+part_search+"'!='' then '"+part_search+"' else PartNo end)"
+" and HouseNo LIKE (case when '"+house_search+"'!='' then '%"+name_search+"%' else HouseNo end)"+" and Age BETWEEN (case when '"+age_search1+"'!='' then '"+age_search1+"' else Age end)"+" AND (case when '"+age_search1+"'!='' then '"+age_search1+"' else Age end)";
Cursor c1 = sql.selectQuery(query);
Log.i("Error","error");
if(c1 != null && c1.getCount() != 0)
{
Log.i("Error","error");
if(c1.moveToFirst()) {
do {
contactlistitems contactlistitems = new contactlistitems();
contactlistitems.setname(c1.getString(c1.getColumnIndex("name")));
contactlistitems.setrelative_type(c1.getString(c1.getColumnIndex("Relation")));
contactlistitems.setfather(c1.getString(c1.getColumnIndex("FatherName")));
contactlistitems.setid(c1.getString(c1.getColumnIndex("IdCard")));
contactlistitems.sethouse(c1.getString(c1.getColumnIndex("HouseNo")));
contactlistitems.setsl(c1.getString(c1.getColumnIndex("SlNo")));
contactlistitems.setage(c1.getString(c1.getColumnIndex("Age")));
contactlistitems.setpoling(c1.getString(c1.getColumnIndex("PollAddress")));
contactlistitems.setsection(c1.getString(c1.getColumnIndex("Section")));
contactlistitems.setac_name(c1.getString(c1.getColumnIndex("AcName")));
contactlistitems.setac_no(c1.getString(c1.getColumnIndex("AcNo")));
contactlistitems.setpart(c1.getString(c1.getColumnIndex("PartNo")));
contactlistitems.setSex(c1.getString(c1.getColumnIndex("Sex")));
contactlist.add(contactlistitems);
} while (c1.moveToNext());
}
}
c1.close();
ContactListAdapter contactListAdapter = new ContactListAdapter(Listdisplay.this, contactlist);
lvCustomList.setAdapter(contactListAdapter);
}
}
ContactListAdapter.java
public class ContactListAdapter extends BaseAdapter {
Context context;
ArrayList<contactlistitems> contactlist;
LayoutInflater mInflater;
public ContactListAdapter(Context context, ArrayList<contactlistitems> list) {
mInflater = LayoutInflater.from(context);
this.context = context;
contactlist = list;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return contactlist.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return contactlist.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.list, null);
holder = new ViewHolder();
holder.name = (TextView) convertView.findViewById(R.id.textView1);
holder.house = (TextView) convertView.findViewById(R.id.textView2);
holder.father = (TextView) convertView.findViewById(R.id.textView3);
holder.sex = (TextView) convertView.findViewById(R.id.textView4);
holder.part = (TextView) convertView.findViewById(R.id.textView5);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.name.setText(contactlist.get(position).getname());
holder.house.setText(contactlist.get(position).gethouse());
holder.father.setText(contactlist.get(position).getfather());
holder.sex.setText(contactlist.get(position).getSex());
holder.part.setText(contactlist.get(position).getpart());
return convertView;
}
static class ViewHolder
{
TextView name,house,father,sex,part;
}
}
I believe that the query is perfectly right! dont know from where its going wrong, is it passing values from class search to listadisplay through intent causing problem am not sure. Kindly help with this
When i tried with the live database the query was working fine. problem was whole data base was returned instead of match, hence the query may be returning null, now have to look for code. When i tested the value which i got through getIntent() it was not receiving value, hence the problem was with intent, value was not sent. error was just to enclose double quote in intent and getintent
at Search.java double quote parameter
i.putExtra("intentname", name1);
at ListDisplay.java
String name_search = myIntent.getStringExtra("intentname");
And it worked

Categories

Resources