I am trying to add multiple values to an array, but it returns a cannot resolve error. Is there any way or work-around here?
for (Map.Entry<String,String> entry : hash.entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
if(typePHP.equals("TARGET")) {
message += key + " " + value + "t\n";
}else {
message += key + " " + value + "r\n";
}
array.add(Integer.parseInt(key),value,typePHP,gamePHP);
//Heres the error.
}
Here's the error:Cannot resolve method 'add(int, java.lang.String, java.lang.String, java.lang.String)'
I need the single element to store 4 values at once and have an output like {109,40, TYPE, GAME};
First, ensure that your ArrayList is currently storing an object with a constructor of (String a, String b, String c). When you call array.add(new Item(a, b, c), Java needs to match that to an existing method.
public class Item {
public Item(String a, String b, String c) {
// initialize your object's variables here in the constructor
}
}
Then, you have to use new when you're creating a new object using add().
array.add(new Item(a, b, c));
See this from Java: Adding new objects to an ArrayList using a constructor
And this reference from Oracle about constructors: https://docs.oracle.com/javase/tutorial/java/javaOO/constructors.html
use addAll in this way:
array.addAll(Arrays.asList( key,value,typePHP,gamePHP) );
UPDATE:
You need a 2d array, based on this sentence I need the single element to store 4 values at once and have an output like {109,40, TYPE, GAME};
So, try this:
ArrayList<ArrayList<String>> array2d = new ArrayList<>();
array2d.add(new ArrayList<String>() {{
add("109");
add("40");
add("TYPE");
add("GAME");
}});
In your case, there should be something like this:
ArrayList<ArrayList<String>> array2d = new ArrayList<>();
for (Map.Entry<String,String> entry : hash.entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
if(typePHP.equals("TARGET")) {
message += key + " " + value + "t\n";
}else {
message += key + " " + value + "r\n";
}
array2d.add(new ArrayList<String>() {{
add(key);
add(value);
add(typePHP);
add(gamePHP);
}});
}
You can create Custom object of your choice member
public class Item {
private int key;
private String value;
private String typePHP;
private String gamePHP;
public Item(int key, String value, String typePHP, String gamePHP) {
this.key = key;
this.value = value;
this.typePHP = typePHP;
this.gamePHP = gamePHP;
}
public int getKey() {
return key;
}
public void setKey(int key) {
this.key = key;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public String getTypePHP() {
return typePHP;
}
public void setTypePHP(String typePHP) {
this.typePHP = typePHP;
}
public String getGamePHP() {
return gamePHP;
}
public void setGamePHP(String gamePHP) {
this.gamePHP = gamePHP;
}
}
Now you can use like
ArrayList<Item> itemArray = new ArrayList <>();
for (Map.Entry<String,String> entry : hash.entrySet()) {
String key = entry.getKey();
String value = entry.getValue();
if(typePHP.equals("TARGET")) {
message += key + " " + value + "t\n";
}else {
message += key + " " + value + "r\n";
}
itemArray.add(new Item(Integer.parseInt(key),value,typePHP,gamePHP));
}
Related
I am working on FatSecretAPI and trying to get the recipes list.
for accessing that need to send some parameters which are:
oauth_consumer_key String --Your API key when you registered as a developer
oauth_signature_method String-- The method used to generate the signature (only HMAC-SHA1 is supported)
oauth_timestamp Int-- The date and time, expressed in the number of seconds since January 1, 1970 00:00:00 GMT. The timestamp value must be a positive integer and must be equal or greater than the timestamp used in previous requests
oauth_nonce String --A randomly generated string for a request that can be combined with the timestamp to produce a unique value
oauth_version String-- MUST be "1.0"
oauth_signature String-- The signature, a consistent reproducible concatenation of the request elements into a single string. The string is used as an input in hashing or signing algorithms.
method String --MUST be "recipes.search"
And in response I will these:
recipe_id – the unique recipe identifier.
recipe_name – the name of the recipe.
recipe_url – URL of this recipe item on www.fatsecret.com.
recipe_description – A short description of the recipe.
recipe_image – URL of this recipe item's default image, only if this is available
I have a json response like this:
{
"recipes":{
"recipe":{
"recipe_description":"Healthy fish with a tasty sauce.",
"recipe_id":"91",
"recipe_image":"http:\/\/www.fatsecret.com\/static\/recipe\/bf0c5912-9cf8-4e7a-b07a-6703c4b77082.jpg",
"recipe_name":"Baked Lemon Snapper",
"recipe_url":"http:\/\/www.fatsecret.com\/recipes\/baked-lemon-snapper\/Default.aspx"
}
}
}
And my Apicall looks like:
public interface MyCallApi {
String BASE_URL = "http://platform.fatsecret.com/";
#POST("rest/server.api/")
Call<Recipes> getRecipes(#Query("oauth_consumer_key") String oauth_consumer_key,
#Query("oauth_signature_method") String oauth_signature_method,
#Query("oauth_timestamp") int oauth_timestamp,
#Query("oauth_nonce") String oauth_nonce,
#Query("oauth_version") String oauth_version,
#Query("oauth_signature") String oauth_signature,
#Query("method") String method);
And my POJO class for recipes is like:
public class Recipes {
#SerializedName("recipe")
#Expose
private Recipe recipe;
public Recipe getRecipe() {
return recipe;
}
public void setRecipe(Recipe recipe) {
this.recipe = recipe;
}
#NonNull
#Override
public String toString() {
return "ClassPojo [recipe = " + recipe + "]";
}
}
And for the data inside the recipes object are:
public class Recipe {
#SerializedName("recipe_name")
#Expose
private String recipe_name;
#SerializedName("recipe_url")
#Expose
private String recipe_url;
#SerializedName("recipe_description")
#Expose
private String recipe_description;
#SerializedName("recipe_image")
#Expose
private String recipe_image;
#SerializedName("recipe_id")
#Expose
private String recipe_id;
public String getRecipe_name() {
return recipe_name;
}
public void setRecipe_name(String recipe_name) {
this.recipe_name = recipe_name;
}
public String getRecipe_url() {
return recipe_url;
}
public void setRecipe_url(String recipe_url) {
this.recipe_url = recipe_url;
}
public String getRecipe_description() {
return recipe_description;
}
public void setRecipe_description(String recipe_description) {
this.recipe_description = recipe_description;
}
public String getRecipe_image() {
return recipe_image;
}
public void setRecipe_image(String recipe_image) {
this.recipe_image = recipe_image;
}
public String getRecipe_id() {
return recipe_id;
}
public void setRecipe_id(String recipe_id) {
this.recipe_id = recipe_id;
}
#NonNull
#Override
public String toString() {
return "ClassPojo [recipe_name = " + recipe_name + "," +
" recipe_url = " + recipe_url + ", " +
"recipe_description = " + recipe_description + "," +
" recipe_image = " + recipe_image + "," +
" recipe_id = " + recipe_id + "]";
}
}
Retrofit implementations are:
public class RecipeActivity extends AppCompatActivity {
final static private String APP_METHOD = "GET";
final static private String APP_KEY = "here api key";
final static private String APP_SECRET = "ssecret key";
final static private String APP_URL = "http://platform.fatsecret.com/rest/server.api";
private static final String HMAC_SHA1_ALGORITHM = "HMAC-SHA1";
private static String paramify(String[] params) {
String[] p = Arrays.copyOf(params, params.length);
Arrays.sort(p);
return join(p, "&");
}
private static String join(String[] array, String separator) {
StringBuilder b = new StringBuilder();
for (int i = 0; i < array.length; i++) {
if (i > 0)
b.append(separator);
b.append(array[i]);
}
return b.toString();
}
private static String nonce() {
Random r = new Random();
StringBuilder n = new StringBuilder();
for (int i = 0; i < r.nextInt(8) + 2; i++)
n.append(r.nextInt(26) + 'a');
return n.toString();
}
Long tsLong = System.currentTimeMillis() / 1000;
int ts = Integer.parseInt(tsLong.toString());
private static String[] generateOauthParams() {
return new String[]{
"oauth_consumer_key=" + APP_KEY,
"oauth_signature_method=HMAC-SHA1",
"oauth_timestamp=" +
Long.valueOf(System.currentTimeMillis() * 2).toString(),
"oauth_nonce=" + nonce(),
"oauth_version=1.0",
"format=json"};
}
private static String signature(String[] params) {
String[] p = {RecipeActivity.APP_METHOD, Uri.encode(RecipeActivity.APP_URL), Uri.encode(paramify(params))};
String s = join(p, "&");
SecretKey sk = new SecretKeySpec(APP_SECRET.getBytes(), HMAC_SHA1_ALGORITHM);
try {
Mac m = Mac.getInstance(HMAC_SHA1_ALGORITHM);
m.init(sk);
return Uri.encode(new String(Base64.encode(m.doFinal(s.getBytes()), Base64.DEFAULT)).trim());
} catch (java.security.NoSuchAlgorithmException | java.security.InvalidKeyException e) {
Log.w("FatSecret_TEST FAIL", e.getMessage());
return null;
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_recipe);
Gson gson = new GsonBuilder()
.setLenient()
.create();
Retrofit retrofit = new Retrofit.Builder()
.addConverterFactory(GsonConverterFactory.create(gson))
.baseUrl(MyCallApi.BASE_URL)
.build();
MyCallApi myCallApi = retrofit.create(MyCallApi.class);
Call<Recipes> call = myCallApi.getRecipes("c30f50a1c5474070b4db11a506d99666",
"HMAC-SHA1", ts
, nonce()
, "1.0", signature(generateOauthParams()),
"recipes.search");
call.enqueue(new Callback<Recipes>() {
#Override
public void onResponse(#NonNull Call<Recipes> call, #NonNull Response<Recipes> response) {
Log.i("if works", response.toString());
}
#Override
public void onFailure(#NonNull Call<Recipes> call, #NonNull Throwable t) {
Log.i("if not", t.getMessage());
}
});
}
}
But I am getting the mostly asked error. And I am not able to solve it on my own. I am new to retrofit. I don't know what and where I am doing wrong, kindly check the implementations and guide me to get the response successfully*. Remember I have to send those parameters along with the retrofit request.*
make one more pojo class like this ..
public class RecipeResponse{
#SerializedName("recipes")
private Recipes recipes;
public void setRecipes(Recipes recipes){
this.recipes = recipes;
}
public Recipes getRecipes(){
return recipes;
}
}
after that change api call when you used..
Call<RecipeResponse>
If I populate my listview with the primary key of my table I can get this primary key using getItemAtPosition and then it works fine.
The problem is that I don't want to use the primarykey to populate de listview, instead I want to use other fields of my table. Doing that, when I use the getItemAtPosition comand, because itsn't unic I can't use this to select my register.
I thought about using getItemIdAtPosition but I didn't reached any solution.
public void populateListView() {
//get the data and append to the list
Cursor data = db.getAllDataFillup(selectedID);
ArrayList<String> listData2 = new ArrayList<>();
while (data.moveToNext()) {
//listData2.add("FILLUP_ID: " + data.getString(0) + " FILLUP_VEHICLE_ID: " + data.getString(1));
//listData2.add(data.getString(7) + " " + data.getString(8) + " " + data.getString(2));
listData2.add(data.getString(3));
//listData2.add(data.getString(2));
}
//create the list adapter and set the adapter
ListAdapter adapter2 = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, listData2);
list_fillup.setAdapter(adapter2);
//set onItemClickListener to the listView
list_fillup.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
int fillupID = Integer.parseInt(adapterView.getItemAtPosition(i).toString());
long position = adapterView.getSelectedItemId();
//long a = list_fillup.get(codigoDoObjeto).getCodigoIdOuPKQualquer();
toastMessage("position: " + position);
//toastMessage("fillupPosition: " + fillupPosition);
//long fillupPosition = adapterView.getItemIdAtPosition(i);
Log.d(TAG, "onItemClick: You Clicked on " + fillupID);
Cursor data = db.getDataTableFillup(fillupID);//get the data associated with that fillupID
fillupID = -1;
while (data.moveToNext()) {
fillupID = data.getInt(0);
vehicleID = data.getInt(1);
fillupDate = data.getString(2);
odometer = data.getLong(3);
kmDriven = data.getLong(4);
liters = data.getLong(5);
consumption = data.getLong(6);
label = data.getString(7);
sequence = data.getInt(8);
}
if (fillupID > -1) {
Log.d(TAG, "onItemClick: The ID is: " + fillupID);
Intent screenVehicle = new Intent(Vehicle_painel.this, Fillup_edit.class);
screenVehicle.putExtra("fillupID", fillupID);
screenVehicle.putExtra("vehicleID", vehicleID);
screenVehicle.putExtra("vehicleName", selectedName);
screenVehicle.putExtra("date", fillupDate);
screenVehicle.putExtra("odometer", odometer);
screenVehicle.putExtra("kmDriven", kmDriven);
screenVehicle.putExtra("liters", liters);
screenVehicle.putExtra("consumption", consumption);
screenVehicle.putExtra("label", label);
screenVehicle.putExtra("sequence", sequence);
//toastMessage("fillupPosition: " + fillupPosition);
startActivity(screenVehicle);
} else {
toastMessage("fillupID = " + fillupID);
//db.deleteAllFillup(selectedID);
//toastMessage("No ID associated with that name hahaha");
}
The best thing to do would be to create a custom class to hold your data. That way you no longer just get a simple String value back from your adapter. Your ArrayList would be something like:
ArrayList<YourCustomClass> listData2 ...
Create a custom class "YourCustomClass" (Call it what ever you like). It could look like:
public class YourCustomClass {
private long itemId = 0;
private String itemName;
private String itemDescription;
public YourCustomClass(){
}
public void setItemId(long id){ this.itemId = id; }
public void setItemName(String itemName){ this.itemName = itemName; }
public void setItemDescription(String itemDescription){ this.itemDescription = itemDescription; }
public long getItemId() { return this.itemId; }
public String getItemName(){ return this.itemName; }
public String getItemDescription(){ return this.itemDescription; }
}
Now in your onItemClick method get the Id and the other data like this:
YourCustomClass data = (YourCustomClass) adapterView.getItemAtPosition(i);
long orderId = data.getItemId();
String name = data.getItemName();
You will need a custom adapter to populate your ListView with data.
You can also take a look at this answer. It shows how to change the background color of a ListView item, but also shows more detail of how to implement a custom adapter for your ListView.
How to set background color for each item listview depanding on variable value
I am getting array list from Global class and getting value with index , but i am getting error on sub-string is that (Sub-string cannot be resolved).
Glide.with(ChooseCategoryProductsActivity.this)
.load("file:///" + GlobalClass.IMAGES_PATH + "/" + GlobalClass.categoriesAr.get(GlobalClass.currentIndex)
.substring(categoriesAr.get(GlobalClass.currentIndex)
.lastIndexOf("/") + 1))
.placeholder(R.drawable.stub)
.into(categoryImage);
Category class :
public class Category {
public String catId = "";
public String catName = "";
public String catImage = "";
public String catDesc = "";
public String displayOrder = "";
public String createdDate = "";
public ArrayList<Product> productsAr = new ArrayList<Product>();
public Category(String catId, String catName, String catImage, String catDesc, String displayOrder, String createdDate) {
this.catId = catId;
this.catName = catName;
this.catImage = catImage;
this.catDesc = catDesc;
this.displayOrder = displayOrder;
this.createdDate = createdDate;
}
}
As you Declared
ArrayList<Category> categoriesAr = new ArrayList<Category>();
subString() is only applied on String not on custom object
There is no such method called subString() with glide as far as i know and hence the compile time error Sub string cannot be resolved. subString works with String
So finally i did just like following, but i don't know whether is it right or not :
GlobalClass.categoriesAr.get(GlobalClass.currentIndex).toString().substring(categoriesAr.get(GlobalClass.currentIndex)
This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 6 years ago.
Can anyone see any errors in this code? I've checked to make sure the data has been written to the database. Every time I click the button it gives me the "Incorrect Password" text. It's probably something stupid that I'm overlooking. Any help is appreciated.
public void buttonWork() {
button_credCheck.setOnClickListener(new View.OnClickListener() {
String rpq = regPwdQuery().toString();
String passInputStr = editText_pwdInput.getText().toString();
#Override
public void onClick(View v) {
if (passInputStr == rpq) {
Intent myIntent = new Intent(LogInActivity.this, FindInfoActivity.class);
startActivity(myIntent);
} else {
Toast.makeText(LogInActivity.this, "Incorrect Password", Toast.LENGTH_LONG).show();
}
}
});
}
EDIT:
This is not a duplicate of the referenced question because changing == to equals() did not fix my problem.
EDIT 2:
Thought maybe I should Include the cursor class for regPwdQuery
public Cursor regPwdQuery() {
String regPwdData = editText_pwdInput.getText().toString();
String regQuery = "SELECT * FROM UsrPass_table WHERE Pwrd ='" + regPwdData + "'";
SQLiteDatabase uDB = usrDB.getReadableDatabase();
Cursor result = uDB.rawQuery(regQuery, null);
return result;
The == operator is used when we have to compare the String object references. If two String variables point to the same object in memory, the comparison returns true.
The equals method is used when we need to compare the content of the text present in the String objects. This method returns true when two String objects hold the same content (i.e. the same values).
To compare two strings for equality, use equals( ).
public void buttonWork() {
button_credCheck.setOnClickListener(new View.OnClickListener() {
String rpq = regPwdQuery().toString();
String passInputStr = editText_pwdInput.getText().toString();
#Override
public void onClick(View v) {
if (passInputStr.equals(rpq))
Intent myIntent = new Intent(LogInActivity.this, FindInfoActivity.class);
startActivity(myIntent);
} else {
Toast.makeText(LogInActivity.this, "Incorrect Password", Toast.LENGTH_LONG).show();
}
}
});
}
your comparisons checks the refferences instead the actual content of the strings. Instead use .equals() to check the value of the String.
if (passInputStr == rpq)
Should be changed to:
if(passInputStr.equals(rpq))
EDIT:
you toString the result you get from the query:
String rpq = regPwdQuery().toString();
if your result only contains the password it might work, but otherwise I don't think it will give the correct result.
Since I don't know how the table UsrPass_table looks like I can only guess but I think something like this has to be implemented:
public String regPwdQuery() {
String regPwdData = editText_pwdInput.getText().toString();
String regQuery = "SELECT * FROM UsrPass_table WHERE Pwrd ='" + regPwdData + "'";
SQLiteDatabase uDB = usrDB.getReadableDatabase();
Cursor result = uDB.rawQuery(regQuery, null);
String password = "";
while(result.moveToNext()){
password = result.getString(0); //Parameter should match the column from where you get your data, normally 0 is an ID.
}
return password;
Hope it helps.
That essentially means passInputStr != rpq , You could try the .equalsIgnoreCase() method or the .equals() method. That is because you are comparing strings! You can read more about this here
You can not compare Strings in java with == operator. Use equals() method instead:
if (passInputStr.equals(rpq))
Try the
if (passInputStr.equals(rpq))
reference:
What is the difference between == vs equals() in Java?
Here is an example (you can run it):
public final class MyEqualityTest
{
public static void main( String args[] )
{
String s1 = new String( "Test" );
String s2 = new String( "Test" );
System.out.println( "\n1 - PRIMITIVES ");
System.out.println( s1 == s2 ); // false
System.out.println( s1.equals( s2 )); // true
A a1 = new A();
A a2 = new A();
System.out.println( "\n2 - OBJECT TYPES / STATIC VARIABLE" );
System.out.println( a1 == a2 ); // false
System.out.println( a1.s == a2.s ); // true
System.out.println( a1.s.equals( a2.s ) ); // true
B b1 = new B();
B b2 = new B();
System.out.println( "\n3 - OBJECT TYPES / NON-STATIC VARIABLE" );
System.out.println( b1 == b2 ); // false
System.out.println( b1.getS() == b2.getS() ); // false
System.out.println( b1.getS().equals( b2.getS() ) ); // true
}
}
final class A
{
// static
public static String s;
A()
{
this.s = new String( "aTest" );
}
}
final class B
{
private String s;
B()
{
this.s = new String( "aTest" );
}
public String getS()
{
return s;
}
}
public void buttonWork() {
button_credCheck.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String rpq = regPwdQuery().toString();
String passInputStr = editText_pwdInput.getText().toString();
if (passInputStr == rpq) {
Intent myIntent = new Intent(LogInActivity.this, FindInfoActivity.class);
startActivity(myIntent);
} else {
Toast.makeText(LogInActivity.this, "Incorrect Password", Toast.LENGTH_LONG).show();
}
}
});
}
Try this.. Put rpq and passInputStr in onClick method. also change if condition if (passInputStr.equals(rpq))
Simply, replace:
if (passInputStr == rpq)
with
if (passInputStr.equals(rpq))
Use string.equals(anotherString) method when you want to compare between two different strings.
Edit:
public String regPwdQuery() {
String regPwdData = editText_pwdInput.getText().toString();
String regQuery = "SELECT * FROM UsrPass_table WHERE Pwrd ='" + regPwdData + "'";
SQLiteDatabase uDB = usrDB.getReadableDatabase();
Cursor cursor = uDB.rawQuery(regQuery, null);
//Modify this
String result = cursor.getString(cursor.getColumnIndex("password"));
return result;
I have a custom spinner which contains name value.Using this I can show a name and in the back I can get the id of that name. It's working perfectly. which is looks like this -
// Get the readable version
SQLiteDatabase db = myDbHelper.getReadableDatabase();
Cursor cursor = db.query("address", new String[] { "name", "code"}, null, null, null, null, null);
int noOfRow = cursor.getCount();
Log.v("TAG", "no of data: " + noOfRow);
MyData[] items = new MyData[noOfRow];
int i = 0;
if (cursor.moveToFirst())
{
do
{
// Log.w("TAG", "Name: " + cursor.getString(0));
// Log.w("TAG", "Code: " + cursor.getString(1));
items[i] = new MyData( cursor.getString(0),cursor.getString(1));
i++;
}while (cursor.moveToNext());
StreetSpinnerAdapter = new ArrayAdapter<MyData>( this,android.R.layout.simple_spinner_item,items );
StreetSpinnerAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
SpinnerStreetName.setAdapter(StreetSpinnerAdapter);
populateSpinnerData(items);
}
cursor.close();
db.close();
class MyData
{
public MyData( String spinnerText, String value )
{
this.spinnerText = spinnerText;
this.value = value;
}
public String getSpinnerText() {
return spinnerText;
}
public String getValue() {
return value;
}
public String toString() {
return spinnerText;
}
String spinnerText;
String value;
}
And I am using the code to select the spinner value programetically is like this SpinnerStreetName.setSelection(((ArrayAdapter)SpinnerStreetName.getAdapter()).getPosition(SpinnerStreetName.getSelectedItem()));
But it's not working ...
First you have to store the value of spinner item by this:
String str = spinner.getSelectedItem().toString();
Then just within a for loop do this:
for(int i = 0;i<items.length();i++){
{
if(str.equals(items[i].getSpinnerText()){
//Do with your id by items[i].getValue()
}
}
hope it will helps you.Any further query ask me..
Thank you.