Can anyone shed some light on this for me? I'm buiding this app for my final project that's due on Friday. Head. is. FRIED.
Getting this error on build
C:\Users\Gary\AndroidStudioProjects\NatureAll.v2\app\src\main\java\com\example\gary\natureallv2\SearchAnimalActivity.java:58: error: incompatible types: int cannot be converted to String
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(POST,
^
Note: Some messages have been simplified; recompile with -Xdiags:verbose to get full output
1 error
It's telling me int can't be converted to string but I can't see where the int is. Here's my code:
package com.example.gary.natureallv2;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
/**
* Created by Gary on 12/09/2016.Go Me
*/
public class SearchAnimalActivity extends AppCompatActivity{
EditText etSearchName;
Button btnSearch;
RequestQueue requestQueue;
String showUrl = "http://192.168.1.10/myDocs/mainProject/search_animal_and.php";
// String showUrl = "http://192.168.1.10/tutorial/showStudents.php";
TextView tvName;
TextView tvLatinName;
TextView tvDescription;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.search_animal_activity);
etSearchName = (EditText) findViewById(R.id.etSearchName);
tvName = (TextView) findViewById(R.id.tvName);
tvLatinName = (TextView) findViewById(R.id.tvLatinName);
tvDescription = (TextView) findViewById(R.id.tvDescription);
btnSearch = (Button) findViewById(R.id.btnSearch);
requestQueue = Volley.newRequestQueue(getApplicationContext());
btnSearch.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
// System.out.println("ww");
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.POST,
showUrl, new Response.Listener<JSONObject>() {
#Override
public void onResponse(JSONObject response) {
System.out.println(response.toString());
try {
JSONArray animals = response.getJSONArray("animals");
for (int i = 0; i < animals.length(); i++) {
JSONObject animal = animals.getJSONObject(i);
//Change here for different string names
String name = animal.getString("name");
String latinName = animal.getString("latinName");
String description = animal.getString("description");
tvName.append(name);
tvLatinName.append(latinName);
tvDescription.append(description);
}
//result.append("===\n");
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
System.out.append(error.getMessage());
}
});
requestQueue.add(jsonObjectRequest);
}
});
}
}
Many thanks in advance
tvName.append(name);
tvLatinName.append(latinName);
tvDescription.append(description);
You are trying to append a string to a View which has a value of its id (int). This wont work. you should instead call a .setText() on your view and set the text to its current value plus what you want to append.
Related
I have created a project in which I am using spinner.
In spinner I am setting data fetched from MySql database. The data is being fetched properly as I can get the whole in the dropdown.
The problem is that spinner is not showing the selected value in the text area.
When I tested it with another arraylist of strings which was created in the program it was working.
I don't know why it is not working properly with the data fetched from database.
Kindly help me if you know the solution.
The java file is here when I used the data from MySql database
package com.help.adminpasskart;
import androidx.appcompat.app.AppCompatActivity;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
public class addSubCategory extends AppCompatActivity {
ImageView categoryImageView , categoryImageBtn;
TextView categoryNameView ;
Button confirmBtn;
String categoryimg;
Spinner genderDrop , categoryDrop;
ArrayList<String> genders = new ArrayList<>();
ArrayList<String> words = new ArrayList<>();
private final String url = "http://passkart.online/Z_addCategory.php";
private final String url2 = "http://passkart.online/Z_getGender.php";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_sub_category);
categoryImageView = findViewById(R.id.addcategoryimageView);
categoryImageBtn = findViewById(R.id.addcategoryimagebtn);
categoryNameView = findViewById(R.id.addcategorynameView);
confirmBtn = findViewById(R.id.addCategoryConfirmBtn);
genderDrop = findViewById(R.id.genderDropDown);
categoryDrop = findViewById(R.id.categoryDropDown);
getGenders();
ArrayAdapter<String> myAdapter = new ArrayAdapter<String>(addSubCategory.this,
R.layout.droptextlayout,genders);
myAdapter.notifyDataSetChanged();
genderDrop.setAdapter(myAdapter);
genderDrop.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long
id) {
String item = parent.getItemAtPosition(position).toString();
Toast.makeText(parent.getContext(), "Selected: " + item,
Toast.LENGTH_LONG).show();
genderDrop.setSelection(position);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
public void getGenders(){
StringRequest request = new StringRequest(Request.Method.POST, url2, new
Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject Jobject = new
JSONObject(response.substring(response.indexOf("{"), response.lastIndexOf("}") + 1));
String success = Jobject.getString("success");
JSONArray Jarray = Jobject.getJSONArray("datas");
if(success.equals("1")) {
for (int i = 0; i < Jarray.length(); i++) {
JSONObject object = Jarray.getJSONObject(i);
String name = object.getString("name");
genders.add(name);
}
}
} catch (JSONException jsonException) {
jsonException.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
RequestQueue queue = Volley.newRequestQueue(addSubCategory.this);
queue.add(request);
};
}
The java file is here when I used the arraylist created in the program.In this code the spinner is working fine
package com.help.adminpasskart;
import androidx.appcompat.app.AppCompatActivity;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
public class addSubCategory extends AppCompatActivity {
ImageView categoryImageView , categoryImageBtn;
TextView categoryNameView ;
Button confirmBtn;
String categoryimg;
Spinner genderDrop , categoryDrop;
ArrayList<String> genders = new ArrayList<>();
ArrayList<String> words = new ArrayList<>();
private final String url = "http://passkart.online/Z_addCategory.php";
private final String url2 = "http://passkart.online/Z_getGender.php";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_sub_category);
categoryImageView = findViewById(R.id.addcategoryimageView);
categoryImageBtn = findViewById(R.id.addcategoryimagebtn);
categoryNameView = findViewById(R.id.addcategorynameView);
confirmBtn = findViewById(R.id.addCategoryConfirmBtn);
genderDrop = findViewById(R.id.genderDropDown);
categoryDrop = findViewById(R.id.categoryDropDown);
getGenders();
words.add("word1");
words.add("word2");
words.add("word3");
words.add("word4");
words.add("word5");
words.add("word6");
words.add("word7");
words.add("word8");
words.add("word9");
words.add("word10");
ArrayAdapter<String> myAdapter = new ArrayAdapter<String>(addSubCategory.this,
R.layout.droptextlayout,words);
myAdapter.notifyDataSetChanged();
genderDrop.setAdapter(myAdapter);
genderDrop.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long
id) {
String item = parent.getItemAtPosition(position).toString();
Toast.makeText(parent.getContext(), "Selected: " + item,
Toast.LENGTH_LONG).show();
genderDrop.setSelection(position);
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
public void getGenders(){
StringRequest request = new StringRequest(Request.Method.POST, url2, new
Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject Jobject = new
JSONObject(response.substring(response.indexOf("{"), response.lastIndexOf("}") + 1));
String success = Jobject.getString("success");
JSONArray Jarray = Jobject.getJSONArray("datas");
if(success.equals("1")) {
for (int i = 0; i < Jarray.length(); i++) {
JSONObject object = Jarray.getJSONObject(i);
String name = object.getString("name");
genders.add(name);
}
}
} catch (JSONException jsonException) {
jsonException.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
RequestQueue queue = Volley.newRequestQueue(addSubCategory.this);
queue.add(request);
};
}
MySql file is here
<?php
include "config.php";
$sql="SELECT * FROM `$db`.`genderCategory`";
$result=mysqli_query($conn,$sql);
$categories['datas'] = array();
if(mysqli_num_rows($result)>0){
while($row=mysqli_fetch_array($result)){
$data['id']=$row['0'];
$data['name']= $row['1'];
$data['image']=$row['2'];
array_push($categories['datas'],$data);
}
$categories['success']='1';
echo json_encode($categories);
mysqli_close($conn);
}else{
echo "No gender added";
}
?>
Finally , I have solved it by myself
The problem was that the method getGenders() was not getting the arrayAdapter
So , I defined it inside the method and booyah !! My problem got solved .
public class addSubCategory extends AppCompatActivity {
ImageView categoryImageView , categoryImageBtn;
TextView categoryNameView ;
Button confirmBtn;
Spinner genderDrop , categoryDrop;
ArrayList<String> genders = new ArrayList<>();
ArrayAdapter<String> myAdapter;
private final String url2 = "http://passkart.online/Z_getGender.php";
String gender ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_add_sub_category);
categoryImageView = findViewById(R.id.addcategoryimageView);
categoryImageBtn = findViewById(R.id.addcategoryimagebtn);
categoryNameView = findViewById(R.id.addcategorynameView);
confirmBtn = findViewById(R.id.addCategoryConfirmBtn);
genderDrop = findViewById(R.id.genderDropDown);
categoryDrop = findViewById(R.id.categoryDropDown);
getGenders();
genderDrop.setOnItemSelectedListener(new
AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int
position, long id) {
myAdapter.notifyDataSetChanged();
String item = parent.getItemAtPosition(position).toString();
genderDrop.setSelection(position);
gender = item;
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
public void getGenders(){
StringRequest request = new StringRequest(Request.Method.POST, url2,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
JSONObject Jobject = new
JSONObject(response.substring(response.indexOf("{"),
response.lastIndexOf("}") + 1));
String success = Jobject.getString("success");
JSONArray Jarray = Jobject.getJSONArray("datas");
if(success.equals("1")) {
for (int i = 0; i < Jarray.length(); i++) {
JSONObject object = Jarray.getJSONObject(i);
String name = object.getString("name");
genders.add(name);
}
//Array adapter is defined here ..........
myAdapter = new ArrayAdapter<String> (addSubCategory.this, R.layout.droptextlayout,genders);
myAdapter.notifyDataSetChanged();
genderDrop.setAdapter(myAdapter);
}
} catch (JSONException jsonException) {
jsonException.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
RequestQueue queue = Volley.newRequestQueue(addSubCategory.this);
queue.add(request);
};
}
I am posting this answer for those who are still dealing with this error.
I am trying to save data on button toggle, so that if pokemon is caught, when i run the application again, pokemon is caugt, and when released, It toggles back to "catch". But all my pokemon are displaying caught (button shows "release")
package com.example.pokedex;
import android.content.Context;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class PokemonActivity extends AppCompatActivity {
private TextView nameTextView;
private TextView numberTextView;
private TextView type1TextView;
private TextView type2TextView;
private String url;
private RequestQueue requestQueue;
Button button;
SharedPreferences sharedpreferences;
public static final String mypreference = "mypref";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pokemon);
requestQueue = Volley.newRequestQueue(getApplicationContext());
url = getIntent().getStringExtra("url");
nameTextView = findViewById(R.id.pokedex_name);
numberTextView = findViewById(R.id.pokedex_number);
type1TextView = findViewById(R.id.pokedex_type);
type2TextView = findViewById(R.id.pokedex_type2);
button = findViewById(R.id.catcher);
sharedpreferences = getSharedPreferences(mypreference,
Context.MODE_PRIVATE);
load();
}
public void load() {
type1TextView.setText("");
type2TextView.setText("");
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null, response -> {
try {
nameTextView.setText(response.getString("name"));
numberTextView.setText(String.format("#%03d", response.getInt("id")));
JSONArray typeEntries = response.getJSONArray("types");
for (int i = 0; i < typeEntries.length(); i++) {
JSONObject typeEntry = typeEntries.getJSONObject(i);
int slot = typeEntry.getInt("slot");
String type = typeEntry.getJSONObject("type").getString("name");
if (slot == 1) {
type1TextView.setText(type);
} else if (slot == 2) {
type2TextView.setText(type);
}
}
} catch (JSONException e) {
Log.e("cs50", "Pokemon json error", e);
}
}, error -> Log.e("cs50", "Pokemon details error", error));
requestQueue.add(request);
if (sharedpreferences.contains(nameTextView.getText().toString()))
button.setText("Release");
}
public void toggleCatch(View view) {
String name = nameTextView.getText().toString();
SharedPreferences.Editor editor = sharedpreferences.edit();
if (button.getText().toString().toLowerCase().equals("Catch".toLowerCase())) {
//editor.clear();
editor.putString(name, name);
editor.apply();
editor.commit();
button.setText("Release");
} else if (button.getText().toString().toLowerCase().equals("Release".toLowerCase())){
editor.remove(name);
editor.apply();
editor.commit();
button.setText("Catch");
}
}
}
I have tried everything i know how to, please help.
Unmodified source code at "https://cdn.cs50.net/2019/fall/tracks/android/pokedex/pokedex.zip"
The following line of code
if (sharedpreferences.contains(nameTextView.getText().toString()))
button.setText("Release");
should go into your onResponseListener() that is your response -> ....
Currently you are calling the if statement above synchronously. This means that you are searching for not any valid Pokemon name but "" (empty string) inside SharedPreferences. In one of your tests, you probably saved empty string as a key, and you cannot undo that because any transaction after you load your pokemons includes a non-empty string Pokemon name.
If taht is indeed the case, you can easily add a temporary code inside your activity onCreate() method to remove that entry from SharedPreferences.
This is my code for getting the data from JSON, it will contain only one row,
but it will give output for only "pro_name" for left of the values it will give just dots(......).
package com.example.sh_enterprises;
import android.app.ProgressDialog;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.CardView;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.List;
public class Detailes extends AppCompatActivity {
//this is the JSON Data URL
//make sure you are using the correct ip else it will not work
public static String URL_PRODUCTS, pass1,pass2 ;
public static String ptopic,psubcode;
private static ProgressDialog progressDialog;
//a list to store all the products
List<pro_data> productList;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detailes);
Intent i = getIntent();
pass1 = i.getStringExtra("pro_id");
//Toast.makeText(this,"HI THIS IS "+pass,Toast.LENGTH_SHORT).show();
//URL_PRODUCTS = "https://premnathindia.000webhostapp.com/Api.php?p1="+pass;
URL_PRODUCTS = "http://192.168.225.25/prem/Api.php?p1="+pass1+"&p2=det";
Toast.makeText(this, URL_PRODUCTS, Toast.LENGTH_SHORT).show();
productList = new ArrayList<>();
//this method will fetch and parse json
//to display it in recyclerview
loadProducts();
}
private void loadProducts() {
prefConfig product = new prefConfig(this);
String str = product.read_ret_id();
Toast.makeText(this,str,Toast.LENGTH_SHORT).show();
progressDialog = new ProgressDialog(this);
progressDialog.setMessage("Please wait...");
progressDialog.show();
/*
* Creating a String Request
* The request type is GET defined by first parameter
* The URL is defined in the second parameter
* Then we have a Response Listener and a Error Listener
* In response listener we will get the JSON response as a String
* */
StringRequest stringRequest = new StringRequest(Request.Method.GET, URL_PRODUCTS,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
//converting the string to json array object
JSONArray array = new JSONArray(response);
//traversing through all the object
for (int i = 0; i < 1; i++) {
//getting product object from json array
JSONObject product = array.getJSONObject(i);
product.getString("pro_id");
String st;
TextView a = findViewById(R.id.pro_name);
TextView b = findViewById(R.id.weight);
TextView c = findViewById(R.id.base_amount);
TextView d = findViewById(R.id.mass_amonut);
TextView e = findViewById(R.id.brand);
TextView f = findViewById(R.id.catogery);
String st1 = product.getString("pro_name");
a.setText(st1);
st = product.getString("weight");
b.setText(st);
st = product.getString("total_amount");
d.setText(st);
//st = product.getString("pro_img_url");
st = product.getString("base_amount");
c.setText(st);
//st = product.getString("disc");
st = product.getString("brands");
e.setText(st);
st = product.getString("categories");
f.setText(st);
}
progressDialog.dismiss();
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
//adding our stringrequest to queue
Volley.newRequestQueue(this).add(stringRequest);
}
public void downme_ooi(View view) {
String pro_id = ((TextView) view).getText().toString();
Intent i = new Intent(this,Detailes.class);
i.putExtra("pro_id",pro_id);
startActivity(i);
}
public void go_back(View view) {
super.onBackPressed();
}
}
Sorry I made the Mistake that in TextView I put the text as password .
In this android code it is sending description in database but not sending Spinner value in database
package com.example.mis_internee.test;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.sql.SQLOutput;
import java.util.HashMap;
import java.util.Map;
public class atd_leave_form extends AppCompatActivity {
EditText Descr, lastname, age;
Button insert;
TextView back;
RequestQueue requestQueue;
String insertUrl = "http://192.168.0.102/A/issue.php";
// String showUrl = "http://192.168.1.65/tutorial/showStudents.php";
TextView TV;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_atd_leave_form);
Descr = (EditText) findViewById(R.id.descText);
insert = (Button) findViewById(R.id.send);
TV = (TextView) findViewById(R.id.uname);
back = (TextView) findViewById(R.id.Back);
// TV= (TextView)findViewById(R.id.textView);
final Spinner staticSpinner = (Spinner) findViewById(R.id.spinner);
ArrayAdapter<CharSequence> staticAdapter = ArrayAdapter.createFromResource(this, R.array.list,android.R.layout.simple_spinner_item);
staticAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
staticSpinner.setAdapter(staticAdapter);
// String name= "Username= "+getIntent().getExtras().getString("username");
// TV.setText(name);
// String name= "Username= "+getIntent().getExtras().getString("username");
// result.setText(name);
//
// back.setOnClickListener(new View.OnClickListener() {
// #Override
// public void onClick(View v) {
// Intent i = new Intent(atd_leave_form.this, MainActivity.class);
// startActivity(i);
//
//
// }
// });
requestQueue = Volley.newRequestQueue(getApplicationContext());
insert.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String DESCR = Descr.getText().toString();
final String Spin = staticSpinner.getSelectedItem().toString();
StringRequest request = new StringRequest(Request.Method.POST, insertUrl, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
if(Descr.getText().toString().equals("")){
Toast.makeText(getApplication(),"Please Enter Detail ",Toast.LENGTH_LONG).show();
}
else if(Descr.getText().toString().length()<10){
Toast.makeText(getApplication(),"Text Must be Greater Than 10",Toast.LENGTH_LONG).show();
}
else{
System.out.println(response.toString());
Toast.makeText(getApplication(),"Application Submitted Successfully....!",Toast.LENGTH_LONG).show();
Intent intent = new Intent(atd_leave_form. this, Issue.class);
startActivity(intent);
}
}}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String,String> parameters = new HashMap<String, String>();
parameters.put("Descr",Descr.getText().toString());
parameters.put("Spin",staticSpinner.toString());
return parameters;
}
};
requestQueue.add(request);
}
});
}
}
i used spinner and select value and submit it but no error with submission description in database. i am using oracle web services with wamp server, but description submitting spinner value is not.
thanks in advance
use staticSpinner.getSelectedItem().toString() instead of staticSpinner.toString() in posting parameters
you are posting wrong data check below code
insert.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String DESCR = Descr.getText().toString();
final String Spin = staticSpinner.getSelectedItem().toString();
StringRequest request = new StringRequest(Request.Method.POST, insertUrl, new Response.Listener<String>() {
#Override
public void onResponse(String response) {
if(Descr.getText().toString().equals("")){
Toast.makeText(getApplication(),"Please Enter Detail ",Toast.LENGTH_LONG).show();
}
else if(Descr.getText().toString().length()<10){
Toast.makeText(getApplication(),"Text Must be Greater Than 10",Toast.LENGTH_LONG).show();
}
else{
System.out.println(response.toString());
Toast.makeText(getApplication(),"Application Submitted Successfully....!",Toast.LENGTH_LONG).show();
Intent intent = new Intent(atd_leave_form. this, Issue.class);
startActivity(intent);
}
}}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String,String> parameters = new HashMap<String, String>();
parameters.put("Descr",Descr.getText().toString());
parameters.put("Spin",Spin);//change here
return parameters;
}
};
requestQueue.add(request);
}
});
}
}
I want to display JSON data in textView and i do that but the problem is when i create a separate class for lood JSON data and Store into A ArrayList, it doesn"t work.
Here is my code please help me what i can do to solve that problem.
My inner class code
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import com.example.mdashikurrahman.transactions.AppController;
import com.example.mdashikurrahman.transactions.HouseOrPerson;
import com.example.mdashikurrahman.transactions.R;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
public class InsertActivity extends Activity {
ArrayList<HouseOrPerson> arrayList= new ArrayList<>();
// json array response url
private String urlJsonArry = "http://testgarciaplumbing.3eeweb.com/ashik/select.php";
private Button btnMakeArrayRequest;
private TextView txtResponse;
// temporary string to show the parsed response
private String jsonResponse="";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_insert);
btnMakeArrayRequest = (Button) findViewById(R.id.btnArrayRequest);
txtResponse = (TextView) findViewById(R.id.txtResponse);
btnMakeArrayRequest.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
makeJsonArrayRequest();
}
});
}
/**
* Method to make json array request where response starts with [
* */
private void makeJsonArrayRequest() {
JsonArrayRequest req = new JsonArrayRequest(Request.Method.POST, urlJsonArry, null,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
try {
// Parsing json array response
// loop through each json object
jsonResponse = "";
for (int i = 0; i < response.length(); i++) {
JSONObject person = (JSONObject) response
.get(i);
HouseOrPerson houseOrPerson =new HouseOrPerson(person.getInt("house_id"),
person.getString("house_name"), person.getInt("balance"));
arrayList.add(houseOrPerson);
}
for (int x=0; x<arrayList.size(); x++){
jsonResponse +=Integer.toString(arrayList.get(x).getId())
+ arrayList.get(x).getName()
+ Integer.toString(arrayList.get(x).getBalance())+ "\n\n";
}
txtResponse.setText(jsonResponse);
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(req);
}
}
Separate class code
BackgroundTask
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
/**
* Created by MD ASHIKUR RAHMAN on 9/24/2016.
*/
public class BackgroundTask {
ArrayList<HouseOrPerson> arrayList= new ArrayList<>();
// json array response url
private String urlJsonArry = "http://testgarciaplumbing.3eeweb.com/ashik/select.php";
/**
* Method that return a arraylist which made by jsonArray
* */
public ArrayList<HouseOrPerson> makeJsonArrayRequest() {
JsonArrayRequest req = new JsonArrayRequest(Request.Method.POST, urlJsonArry, null,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
try {
for (int i = 0; i < response.length(); i++) {
JSONObject person = (JSONObject) response
.get(i);
HouseOrPerson houseOrPerson =new HouseOrPerson(person.getInt("house_id"),
person.getString("house_name"), person.getInt("balance"));
arrayList.add(houseOrPerson);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
}
});
// Adding request to request queue
AppController.getInstance().addToRequestQueue(req);
return arrayList;
}
}
InsertActivity class where i create a object ob BackGround class and call makeJsonArrayRequest method
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import com.example.mdashikurrahman.transactions.BackgroundTask;
import com.example.mdashikurrahman.transactions.HouseOrPerson;
import com.example.mdashikurrahman.transactions.R;
import java.util.ArrayList;
public class InsertActivity extends Activity {
ArrayList<HouseOrPerson> arrayList= new ArrayList<>();
private Button btnMakeArrayRequest;
private TextView txtResponse;
// temporary string to show the parsed response
private String jsonResponse="";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_insert);
btnMakeArrayRequest = (Button) findViewById(R.id.btnArrayRequest);
txtResponse = (TextView) findViewById(R.id.txtResponse);
btnMakeArrayRequest.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
BackgroundTask bg = new BackgroundTask();
arrayList=bg.makeJsonArrayRequest();
for (int x=0; x<arrayList.size(); x++){
jsonResponse +=Integer.toString(arrayList.get(x).getId())
+ arrayList.get(x).getName()
+ Integer.toString(arrayList.get(x).getBalance())+ "\n\n";
}
txtResponse.setText(jsonResponse);
}
});
}
}
Arent you missing a constructor in your BackgroundTask?
Try putting System.out.println(arrayList.size()) before you return it in your BackgroundTask. What is the size of it?