I m using this framework, I already trying many times for making this problem, but I cant do it. I already asking on stackoverflow but no one cant help me. Actually I m tried.
I m using this framework : https://github.com/kikoso/Swipeable-Cards
And I m using SimpleCardStackAdapter like this :
for (int i = 0; i < user.length(); i++) {
final JSONObject c = user.getJSONObject(i);
// Storing JSON item in a Variable
String id = c.getString(user_id);
String name = c.getString(username);
final String email = c.getString(text);
String image1 = c.getString(imageUrl);
String range1 = c.getString(range);
String msgId = c.getString(postId);
// adapter.add(new CardModel(name, email, image1));
//Set JSON Data in TextView
Log.i("image1image1image1image1", image1);
// CardModel cardModel = new CardModel(" cardModel", " CardModel", r.getDrawable(R.drawable.picture1));
card = new CardModel(name, email, image1);
card.setOnClickListener(new CardModel.OnClickListener() {
#Override
public void OnClickListener() {
Log.i("Swipeable Cards", "I am pressing the card");
// Intent no = new Intent(HomeListview.this, YayDetailActivity.class);
/// startActivity(no);
}
});
card.setOnCardDimissedListener(new CardModel.OnCardDimissedListener() {
#Override
public void onLike(CardModel card) {
Log.i("Swipeable Cards", "I dislike the card");
}
#Override
public void onDislike(CardModel card) {
Log.i("Swipeable Cards", "I like the card");
// new sendNewYay().execute(sharedToken, card.getTitle());
Toast.makeText(getApplicationContext(), card.getDescription(), Toast.LENGTH_SHORT).show();
}
});
// I m added adapter
adapter.add(card);
mCardContainer.setAdapter(adapter);
}
At the onDislike method, I need to get item name.
in this line : new sendNewYay().execute(sharedToken, name);
I send the item name, But it dont work.
1.How can I get the item name, in this method?
2.I have two button, one of them for onLike method, another one for onDislike Method. Ho can I triggered this two method with my button?
Thank you.
Decleare two variable global as string
String itemname;
try {
JSONArray c = new JSONArray(user.toString());
for (int i = 0 ; i < c.length();i++) {
String id = c.getString(user_id);
String name = c.getString(username);
final String email = c.getString(text);
String image1 = c.getString(imageUrl);
String range1 = c.getString(range);
String msgId = c.getString(postId);
System.out.println("Position : " + "" + i + ""+ c.getString(i));
itemname = name.getString(i);
}
} catch (JSONException e) {
e.printStackTrace();
}
System.out.println("Final itemname is " + itemname);
Related
I am stuck. I receive a JSON string from a server. I load this into a JSON array called allTheArray.
I now want to iterate through the array and pull name/value pairs out. This I can do.
For each Name in the array I have a corresponding TextView in my layout. For ease of remembering!
I now want to iterate through the array and place the correct value in the correct TextView.
pseudo code.
For I =0 to length
Name is get name from allTheArray
Value is get value from allTheArray
TextViewWithTheAboveName.setText=Value
Next
Is this possible? In PHP you can use $$variable name etc. I cannot get my head round this. Any suggestions please.
button_clearWCC.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String TAG ="JSONWALK";
Toast.makeText(MainActivity.this, "Loading all fields", Toast.LENGTH_LONG).show();
for(int i = 0; i<allTheArray.names().length(); i++){
try {
String key=allTheArray.names().getString(i);
String value = allTheArray.getString(key);
//the key string is the name of the TextView
//I know I have just set the key to be a string but is there anyway I can use that to define which //TextView I change.
key.setText(value)
Log.i(TAG, "key = " + key + " value = " + value);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
});
So this was how I solved it.. no idea about overheads or efficiencies but it worked for me. Effectively get the id of the TextView using the key. Then create a TextView t for that id and then use that to empty the cell or add value to cell. This may have implications elsewhere but not found them yet.
button_clearWCC.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
String TAG ="JSONWALK";
Toast.makeText(MainActivity.this, "Clearing all fields", Toast.LENGTH_LONG).show();
for(int i = 0; i<allTheArray.names().length(); i++){
try {
String key=allTheArray.names().getString(i);
String value = allTheArray.getString(key);
//this bit solved it
int id = getResources().getIdentifier(key, "id", getBaseContext().getPackageName());
TextView t = (TextView) findViewById(id);
t.setText("");
//end of this bit solved it
Log.i(TAG, "key = " + key + " value = " + value);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
});
This is my recycler view in which I am storing my expense related information . I want to sum the amount paid of each corresponding user . For example , sadaf : Rs (50+10+5)=65 , Gulatiji: (50)Rs =50 , Amen :(50+5)= Rs 55 .
I thought of using hash map but the problem is that the user names in my recycler view are not unique . So , how should I store the sum of each corresponding user .
I have also tried this but this is giving me the wrong answer .
I am able to successfully sum the total amount column but for the amount paid , it is giving me the wrong answer. For the time being , I was just trying to calculate the total amount of a single user by using an integer variable my_total .I am getting the answer for sadaf as 110 but it should be 65.
calcuationAdap = new CalcuationAdap(Calculation.this,data);
for (int i = 0 ;i<data.size();i++) {
System.out.println(data.get(i).getItem());
main_total = main_total + Integer.parseInt(data.get(i).getTot_amt());
}
for(int i=0;i<data.size();i++)
{
for( int j=i+1;j<data.size()-1;j++)
{
if(data.get(i).getUser_name().equals(data.get(j).getUser_name()))
{
System.out.println(data.get(i).getUser_name());
my_total = my_total+Integer.parseInt(data.get(i).getMy_amt());
}
}
}
Toast.makeText(getApplicationContext(), String.valueOf(main_total ), Toast.LENGTH_SHORT).show();
Toast.makeText(getApplicationContext(), String.valueOf(my_total), Toast.LENGTH_SHORT).show();
If you have user id then use user id. other wise use below code to get each total amount
calcuationAdap = new CalcuationAdap(Calculation.this,data);
HashMap<String,Integer> result =new HashMap<>();
for (int i = 0 ;i<data.size();i++) {
System.out.println(data.get(i).getItem());
main_total = main_total + Integer.parseInt(data.get(i).getTot_amt());
}
for(int i=0;i<data.size();i++) {
if (result.containsKey(data.get(i).getUser_name())){
Integer addTotal=result.get(data.get(i).getUser_name());
addTotal= addTotal + Integer.parseInt(data.get(i).getMy_amt());
result.put(data.get(i).getUser_name(),addTotal);
}else {
result.put(data.get(i).getUser_name(),Integer.parseInt(data.get(i).getMy_amt()));
}
}
Toast.makeText(getApplicationContext(), String.valueOf(main_total ), Toast.LENGTH_SHORT).show();
for (Map.Entry<String, Integer> entry:result.entrySet()) {
System.out.println(entry.getKey() + "/" + entry.getValue());
Toast.makeText(getApplicationContext(), entry.getKey() + "/" + entry.getValue(), Toast.LENGTH_SHORT).show();
}
create a model class like
public class MyDataClass {
String userName;
String date;
String item;
int totoalAmount;
int amountPaid;
public int getAmountPaid() {
return amountPaid;
}
public int getTotoalAmount() {
return totoalAmount;
}
public String getDate() {
return date;
}
public String getItem() {
return item;
}
public String getUserName() {
return userName;
}
public void setAmountPaid(int amountPaid) {
this.amountPaid = amountPaid;
}
public void setDate(String date) {
this.date = date;
}
public void setItem(String item) {
this.item = item;
}
public void setTotoalAmount(int totoalAmount) {
this.totoalAmount = totoalAmount;
}
public void setUserName(String userName) {
this.userName = userName;
}
}
and whenever you need to store data as a list of such type create array list of this type like
ArrayList list =new ArrayList<>()
and create object of this class to store data with getter methods like
MyDataClass data =new MyDataClass()
data.setUserName("userName")
....
list.add(data);
and whenever you need to get data use getter method to get data like
list.get(index).getUserName();
what im trying to do is look at the json pull all the names to a list view(save the imdbid of that names) and from there you can click on a movie and it will go to a new intent that will bring you the movie that you clicked on with its name summary and an image
im searching in a json with an array in it that looks like this(it based on what the user searched so this is one example...)
{"Search":[{"Title":"Batman Begins","Year":"2005","imdbID":"tt0372784","Type":"movie","Poster":"http://ia.media-imdb.com/images/M/MV5BNTM3OTc0MzM2OV5BMl5BanBnXkFtZTYwNzUwMTI3._V1_SX300.jpg"},{"Title":"Batman v Superman: Dawn of Justice","Year":"2016","imdbID":"tt2975590","Type":"movie","Poster":"http://ia.media-imdb.com/images/M/MV5BNTE5NzU3MTYzOF5BMl5BanBnXkFtZTgwNTM5NjQxODE#._V1_SX300.jpg"},{"Title":"Batman","Year":"1989","imdbID":"tt0096895","Type":"movie","Poster":"http://ia.media-imdb.com/images/M/MV5BMTYwNjAyODIyMF5BMl5BanBnXkFtZTYwNDMwMDk2._V1_SX300.jpg"},{"Title":"Batman Returns","Year":"1992","imdbID":"tt0103776","Type":"movie","Poster":"http://ia.media-imdb.com/images/M/MV5BODM2OTc0Njg2OF5BMl5BanBnXkFtZTgwMDA4NjQxMTE#._V1_SX300.jpg"},{"Title":"Batman Forever","Year":"1995","imdbID":"tt0112462","Type":"movie","Poster":"http://ia.media-imdb.com/images/M/MV5BNWY3M2I0YzItNzA1ZS00MzE3LThlYTEtMTg2YjNiOTYzODQ1XkEyXkFqcGdeQXVyMTQxNzMzNDI#._V1_SX300.jpg"},{"Title":"Batman & Robin","Year":"1997","imdbID":"tt0118688","Type":"movie","Poster":"http://ia.media-imdb.com/images/M/MV5BNTM1NTIyNjkwM15BMl5BanBnXkFtZTcwODkxOTQxMQ##._V1_SX300.jpg"},{"Title":"Batman: The Animated Series","Year":"1992–1995","imdbID":"tt0103359","Type":"series","Poster":"http://ia.media-imdb.com/images/M/MV5BMTU3MjcwNzY3NF5BMl5BanBnXkFtZTYwNzA2MTI5._V1_SX300.jpg"},{"Title":"Batman: Under the Red Hood","Year":"2010","imdbID":"tt1569923","Type":"movie","Poster":"http://ia.media-imdb.com/images/M/MV5BMTMwNDEyMjExOF5BMl5BanBnXkFtZTcwMzU4MDU0Mw##._V1_SX300.jpg"},{"Title":"Batman: The Dark Knight Returns, Part 1","Year":"2012","imdbID":"tt2313197","Type":"movie","Poster":"http://ia.media-imdb.com/images/M/MV5BMzIxMDkxNDM2M15BMl5BanBnXkFtZTcwMDA5ODY1OQ##._V1_SX300.jpg"},{"Title":"Batman: Mask of the Phantasm","Year":"1993","imdbID":"tt0106364","Type":"movie","Poster":"http://ia.media-imdb.com/images/M/MV5BMTMzODU0NTYxN15BMl5BanBnXkFtZTcwNDUxNzUyMQ##._V1_SX300.jpg"}],"totalResults":"310","Response":"True"}
so what i want to do is get the imdbid when he clicks on the listview which contains the movie name
this is what i tried:
JSONObject jsonObject = new JSONObject(finalJson);
JSONArray parentArray = jsonObject.getJSONArray("Search");
StringBuffer finalStringBuffer = new StringBuffer();
String imdbid ;
for (int i=0; i<parentArray.length(); i++){
JSONObject finalJsonObject = parentArray.getJSONObject(i);
String movieName = finalJsonObject.getString("Title");
nameOfMovie.add(movieName);
String year = finalJsonObject.getString("Year");
yearOfMovie.add(year);
String omdbID = finalJsonObject.getString("imdbID");
id.add(omdbID);
finalStringBuffer.append(movieName + " , " + year + " , " + omdbID + "\n");
imdbid = omdbID ;
}
}
catch (JSONException e) {
e.printStackTrace();
}
}
but how can i know the imdbid(which is in the movie name that is displayed in a list) that he cliked on?
listview code:
listViewInternetScreen.setClickable(true);
listViewInternetScreen.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position, long i) {
Intent intenttoEditScreen=new Intent(AddFromInternet.this, EditMovie.class);
setResult(RESULT_OK,intenttoEditScreen);
String jsonMovieName = String.valueOf(nameOfMovie);
String jsonMovieSummery = String.valueOf(yearOfMovie);
String jsonImageURL = String.valueOf(id);
intenttoEditScreen.putExtra("json", jsonMovieName);
intenttoEditScreen.putExtra("json", jsonMovieSummery);
intenttoEditScreen.putExtra("json", jsonImageURL);
startActivity(intenttoEditScreen);
}
});
and the search method:
btnGo = (Button) findViewById(R.id.btnGo);
assert btnGo != null;
btnGo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//MAKE A SEARCH STRING AND PARSE THE RESULT
final String search = "http://www.omdbapi.com/?s=" + EtSearch.getText().toString();
Log.e("JSON", search);
new JSONParser().execute(search);
ArrayList<String> list = new ArrayList<>(nameOfMovie);
arrayAdapter = new ArrayAdapter<>(AddFromInternet.this,
android.R.layout.simple_list_item_1, list);
arrayAdapter.notifyDataSetChanged();
listViewInternetScreen.setAdapter(arrayAdapter);
Log.e("JSON MOVIE", String.valueOf(nameOfMovie));
}
});
thanks for any help :D
Step 1: Use Gson (and Retrofit, if you'd like) to simplify turning a JSON string into a list of Java objects
Step 2: Make a custom ArrayAdapter that loads this list of objects. Then, when you add an Item click listener, you can get that object from the list item you clicked, and start the Intent for showing the full info for that movie.
Additional step would be to make the Movie object Parcelable, so you can add the object to the Intent in one line, rather than each individual field it contains
I have a custom listview with checkbox imageview and textview and there is a button below listview. On clicking of that button i have to pass all the checked item details to another activity and show in other listview. I am able to pass selected value but not able to pass images. Images are in drawable folder. Please help me thanks.
Here is the code:
subscribe.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
String data = "";
ArrayList<Item> stList = ((OurServiceAdapter) nAdapter)
.getAllData();
for (int i = 0; i < stList.size(); i++) {
Item singleStudent = stList.get(i);
if (singleStudent.isCheckbox() == true) {
name.add(singleStudent.getName().toString());
img.add(singleStudent.getImage());
data = data + "\n" + singleStudent.getName().toString();
}
}
// byte[] imgs = singleStudent.getImage();
Intent intent = new Intent(ActivityOurServices.this, ActivityServicesForm.class);
intent.putStringArrayListExtra("key", name);
//intent.putIntegerArrayListExtra("img", img);
startActivity(intent);
}
});
}
you can pass all image as Integer arrayList :
//first : for each imageView inside list you must to set tag ,for example ;
imageView0.setTag(R.drawable.image_0);
imageView1.setTag(R.drawable.image_1);
.
.
.
imageViewN.setTag(R.drawable.image_N);
now when you press button :
ArrayList<Integer> checkedImageSrcId = new ArrayLIst<Integer> ;
for (int i = 0; i < stList.size(); i++) {
Item singleStudent = stList.get(i);
if (singleStudent.isCheckbox() == true) {
name.add(singleStudent.getName().toString());
// img.add(singleStudent.getImage());
// you most to get checked imageViews Tag and i dont have an idea about how to get those
checkedImageSrcId.add( getImageViewTagAtPostion(i));
data = data + "\n" + singleStudent.getName().toString();
}
}
// byte[] imgs = singleStudent.getImage();
Intent intent = new Intent(ActivityOurServices.this, ActivityServicesForm.class);
intent.putStringArrayListExtra("key", name);
intent.putIntegerArrayListExtra("img", checkedImageSrcId);
startActivity(intent);
I have been working on this problem for about five hours, implementing many different ways to achieve this goal, but nothing seems to be working. I am at the point to where I can't even think straight any more, so I am posting this here.
I have a shared preference which retrieves a string. that string is converted into a string array. I have a 2d array with four arrays set to the index. I want to loop through the 2d array and compare my string array to it. If the contents of each 2d array index are found in my string array, print true, else, false.
final SharedPreferences sharedPref = CocktailsFrag.this.getActivity().getPreferences(Activity.MODE_PRIVATE);
//recall stored ingredients
String arrayString = sharedPref.getString("myIngredients", null);
if(arrayString ==null) {
//do nothing
} else {
String str1 = arrayString.replace("[", "");
String str2 = str1.replace("]", "");
String[] strValues = str2.split(",");
String drink1[] = {"Ale", "Brandy"};
String drink2[] = {"Vodka", "Tobasco Sauce"};
String drink3[] = {"Lager", "Stout"};
String drink4[] = {"Guiness", "Champagne"};
String[][] arrays = {drink1, drink2, drink3, drink4};
for(int i=0; i<arrays.length-1;i++) {
String[] indexValue = arrays[i];
if(strValues[i].contains(indexValue[i])) {
Toast.makeText(getActivity().getApplicationContext(), indexValue[i]+ "", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getActivity().getApplicationContext(), "false", Toast.LENGTH_LONG).show();
}
}
}
Any thoughts on how to achieve this?
This code is not as efficient as simply iterating over the arrays but it doesn't matter with the number of elements and it is easier to read.
final SharedPreferences sharedPref = CocktailsFrag.this.getActivity().getPreferences(Activity.MODE_PRIVATE);
//recall stored ingredients
String arrayString = sharedPref.getString("myIngredients", null);
if(arrayString ==null) {
//do nothing
} else {
String str1 = arrayString.replace("[", "").replace("]", "");
List<String> strValues2 = Arrays.asList(str1.split(","));
String drink1[] = {"Ale", "Brandy"};
String drink2[] = {"Vodka", "Tobasco Sauce"};
String drink3[] = {"Lager", "Stout"};
String drink4[] = {"Guiness", "Champagne"};
String[][] arrays = {drink1, drink2, drink3, drink4};
for(String[] drinkArr : arrays){
if(strValues2.containsAll(Arrays.asList(drinkArr))) {
Toast.makeText(getActivity().getApplicationContext(), "true", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getActivity().getApplicationContext(), "false", Toast.LENGTH_LONG).show();
}
}
}
If you wanted to do this using arrays only one option is the following.
for(String[] drinkArr : arrays) {
boolean allDrinksFound = true;
for(int i = 0; i < drinkArr.length; i++) {
boolean drinkFound = false;
for(int j = 0; j < strValues.length; j++) {
if(drinkArr[i].equals(strValues[j])) {
drinkFound = true;
break;
}
}
allDrinksFound = allDrinksFound && drinkFound;
}
if(allDrinksFound) {
Toast.makeText(getActivity().getApplicationContext(), "true", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getActivity().getApplicationContext(), "false", Toast.LENGTH_LONG).show();
}
}