Information on setters and getters - android

I am learning extensively about getters and setters but I seem not to be having my way.
I have a class called Apps_Info which contains my setters and getters and I have my main activity FavouriteApps that has a list which uses the class Apps_Info.
I am trying to get the name of the package from the List in FavouriteApps but I am still getting null.
Please can someone tell what to do? Below is the code in this order: class Apps_Info and FavouriteApps activity
public class Apps_Info {
private Bitmap bIcon;
private String sName;
private String sPacks_Name;
public Apps_Info(Bitmap icon, String name, String Packs_Name) {
bIcon = icon;
sName = name;
sPacks_Name = Packs_Name;
}
public void setIcon(Bitmap icon) {
bIcon=icon;
}
public Bitmap getIcon() {
return bIcon;
}
public void setName(String name) {
sName=name;
}
public String getName() {
return sName;
}
public void setPacks_Name(String Packs_Name) {
this.sPacks_Name=Packs_Name;
}
public String getPacks_Name() {
return sPacks_Name;
}
}
FavouriteApps Activity code (part)
String packname, packsname, apps_names;
Bitmap app_icon;
Resources res = getResources();
List<Apps_Info> ListApps_Info = new ArrayList<Apps_Info>();
ListApps_Info.add(new Apps_Info(BitmapFactory.decodeResource(res, R.drawable.browser_app), "Browser", "com.browser"));
ListApps_Info.add(new Apps_Info(BitmapFactory.decodeResource(res, R.drawable.clock_app), "Alarm Clock", "com.alarm.clock"));
ListApps_Info.add(new Apps_Info(BitmapFactory.decodeResource(res, R.drawable.threegplus), "3G Secure Connection", "threeg.secureconnect"));
mGridView.setAdapter(new Apps_Info_Adapter(this, ListApps_Info));
Apps_Info packinfo = new Apps_Info(app_icon, apps_names, packname);
packsname = packinfo.getPacks_Name();
apps_names = packinfo.getName();
Log.i("The Pack_Name is " + packsname, "Pack Name");

You should do like this.
for (int i = 0; i < ListApps_Info.size(); i++) {
Apps_Info packinfo = ListApps_Info.item(i);
packsname = packinfo.getPacks_Name();
apps_names = packinfo.getName();
Log.i("The Pack_Name is " + packsname, "Pack Name");
}

It's because you never initialize the packname variable in your code.
String packname,packsname,apps_names;
When you do this :
Apps_Info packinfo=new Apps_Info(app_icon, apps_names,packname);
packsname=packinfo.getPacks_Name();
your getter is doing well and this is normal if it returns null.

Related

Android AWS DynamoDB "No hash key condition"

I have a DynamoDB table that has some data. There is a hashkey of "class_id" and a rangekey of "message_timestamp".
In my android code I am attempting to query for messages that are newer than the last message received.
int lastMessageTimestamp = GetNewestTimestamp();
DynamoChatData messagesToFind = new DynamoChatData();
Log.i(TAG,String.valueOf(class_id));
messagesToFind.SetClassId(class_id); // Set to 2 in the debugger at runtime
Condition rangeKeyCondition = new Condition();
rangeKeyCondition.withComparisonOperator(ComparisonOperator.GT.toString());
AttributeValue attributeValue = new AttributeValue();
attributeValue.withN(String.valueOf(lastMessageTimestamp));
rangeKeyCondition.withAttributeValueList(attributeValue);
DynamoDBQueryExpression<DynamoChatData> query = new DynamoDBQueryExpression<>();
query.withHashKeyValues(messagesToFind);
query.withRangeKeyCondition("message_timestamp", rangeKeyCondition);
query.withConsistentRead(false);
PaginatedQueryList result = objectMapper.query(DynamoChatData.class, query);
The DynamoChatData class:
#DynamoDBTable(tableName = "scriyb_chat")
public class DynamoChatData {
private int class_id;
private int message_timestamp;
private String user_name;
private String user_full_name;
private String message_content;
private int message_visible;
private int message_underage;
#DynamoDBRangeKey(attributeName = "message_timestamp")
public int GetMessageTimestamp(){
return message_timestamp;
}
public void SetMessageTimestamp(int _message_timestamp){
message_timestamp = _message_timestamp;
}
#DynamoDBHashKey(attributeName = "class_id")
public int GetClassId(){
return class_id;
}
public void SetClassId(int _class_id){
class_id = _class_id;
}
#DynamoDBAttribute(attributeName = "user_name")
public String GetUsername(){
return user_name;
}
public void SetUsername(String _user_name){
user_name = _user_name;
}
#DynamoDBAttribute(attributeName = "user_full_name")
public String GetUserFullName(){
return user_full_name;
}
public void SetUserFullName(String _user_full_name){
user_full_name = _user_full_name;
}
#DynamoDBAttribute(attributeName = "message_content")
public String GetMessageContent(){
return message_content;
}
public void SetMessageContent(String _message_content){
message_content = _message_content;
}
#DynamoDBAttribute(attributeName = "message_visible")
public int GetMessageVisible(){
return message_visible;
}
public void SetMessageVisible(int _message_visible){
message_visible = _message_visible;
}
#DynamoDBAttribute(attributeName = "message_underage")
public int GetMessageUnderage(){
return message_underage;
}
public void SetMessageUnderage(int _message_underage){
message_underage = _message_underage;
}
}
I followed the basic example outlined here and have read a bunch of posts on this site as well. Not sure why I get the
java.lang.IllegalArgumentException: Illegal query expression: No hash key condition is found in the query
error.
Any insight is appreciated.
Try using refactoring your getter/setter names so that they start with a lowercase letter as is standard Java convention. I believe the mapper looks for getters as methods that start with "get" and I think it's missing yours since they start with a capitol G.
Let me know if this resolves your problem!
Weston

When passing 2 identical Parcable Classes, 1 is null

i have a weird issue.
I'm trying to pass 2 parcable classesfrom one activity to another.
I define both of them the exact same way, but of them is null.
The parcable class :
class Friends implements Parcelable {
private ArrayList<Integer> ids = new ArrayList<Integer>();
private ArrayList<String> names = new ArrayList<String>();
private ArrayList<Bitmap> images = new ArrayList<Bitmap>();
public void addId(Integer id)
{
ids.add(id);
}
public void addName(String name){
names.add(name);
}
public void addImage(Bitmap img){
images.add(img);
}
public ArrayList<Integer> getIds() {
return ids;
}
public ArrayList<String> getNames() {
return names;
}
public ArrayList<Bitmap> getImages() {
return images;
}
#Override
public int describeContents() {
// TODO Auto-generated method stub
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeList(ids);
dest.writeList(names);
dest.writeList(images);
}
public static final Parcelable.Creator<Friends> CREATOR = new Parcelable.Creator<Friends>() {
public Friends createFromParcel(Parcel in) {
return new Friends(in);
}
public Friends[] newArray(int size) {
return new Friends[size];
}
};
public Friends(Parcel in){
in.readList(ids, null);
in.readList(names, null);
in.readList(images, null);
}
public Friends(Integer id, String name, Bitmap img) {
ids.add(id);
names.add(name);
images.add(img);
}
public Friends(){
}
The Sending part :
for(Integer position : selectedIds)
{
String name = a.getItem(position).getFriendName();
int id = a.getItem(position).getFriendId();
Bitmap img = a.getItem(position).getFriendImage();
Log.e("ID",String.valueOf(id));
selectedFriends.addId(new Integer(id));
selectedFriends.addName(name);
selectedFriends.addImage(img);
}
for(int position=0;position<list.getCount(); position++)
{
String name = a.getItem(position).getFriendName();
int id = a.getItem(position).getFriendId();
Bitmap img = a.getItem(position).getFriendImage();
Log.e("All IDs",String.valueOf(id));
allFriends.addId(new Integer(id));
allFriends.addName(name);
allFriends.addImage(img);
}
b.putParcelable("selecet_friends", selectedFriends);
b.putParcelable("all_friends", allFriends);
data.putExtras(b);
Both of the loops are being runned ( i can see the logs), all variables you don't see are being initialized correctly, everything is fine.
The Reciving part :
i define both as null :
private Friends selectedFriends = null;
private Friends allFriends = null;
And handle the onResult like this :
Log.e("Result","yessss");
Friends all_friends = (Friends)data.getParcelableExtra("all_friends");
Friends selected_friends = (Friends)data.getParcelableExtra("selected_friends");
allFriends = all_friends;
selectedFriends = selected_friends;
if(selectedFriends != null){
Log.e("is null","No");
}
if(allFriends != null){
Log.e("is all null","No");
}
Does anyone know how come the selectedFriends is null when allFriends is not?
EDIT:
Just a thought, but maybe it's because i put 2 parcables on a Bundle?
just i just add 2 bundles?
In the sending method you have a typo in this line:
b.putParcelable("selecet_friends", selectedFriends);
try this instead:
b.putParcelable("selected_friends", selectedFriends);
Also, you should use more specific names for the keys. The documentation for putExtras() says:
Add a set of extended data to the intent. The keys must include a
package prefix, for example the app com.android.contacts would use
names like "com.android.contacts.ShowAll

How can I Json (or Gson) a class like "objects to string" and after "string to objects"

My question is about an error occurred when I use my followed class:
public class ClassePai {
private int ID;
private String Nome;
private ArrayList<ClasseFilho> listaParentes;
public ClassePai( int id, String nome){
this.ID = id;
this.Nome = nome;
listaParentes = new ArrayList<ClasseFilho>();
}
public void addParente(ClasseFilho classeFilho) {
listaParentes.add(classeFilho);
}
public ClasseFilho getParente( int index ){
return listaParentes.get(index);
}
public int length(){
return listaParentes.size();
}
public String Nome(){
return this.Nome;
}
public int ID(){
return this.ID;
}
}
and this "son" class:
public class ClasseFilho {
private String Nome;
private String Grau;
public ClasseFilho( String nome, String grau ){
this.Nome = nome;
this.Grau = grau;
}
public String Nome(){
return this.Nome;
}
public String Grau(){
return this.Grau;
}
}
This is my Activity:
public class TesteClasseActivity extends Activity {
private ClassePai cp;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
cp = new ClassePai( 1, "Junior" );
cp.addParente( new ClasseFilho( "Vinicius", "filho" ) );
cp.addParente( new ClasseFilho( "Luciene", "namorada" ) );
//old call returning error
//Toast.makeText(getApplicationContext(), cp.length(), Toast.LENGTH_SHORT).show();
Toast.makeText(getApplicationContext(), String.valueOf( cp.length() ), Toast.LENGTH_SHORT).show();
cp.addParente( new ClasseFilho( "Veraldo", "pai" ) );
cp.addParente( new ClasseFilho( "Sônia", "mãe" ) );
Toast.makeText(getApplicationContext(), String.valueOf( cp.length() ), Toast.LENGTH_SHORT).show();
( (TextView) findViewById(R.id.edit) ).setText( cp.Nome() );
Button bt = (Button) findViewById(R.id.button);
bt.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
Toast.makeText(getApplicationContext(), cp.getParente(1).Nome(), Toast.LENGTH_SHORT).show();
}
});
//my try of doing this, but don't work
JSONObject obj = new JSONObject();
obj.put("teste", cp);
// BUT unfortunatelly
//
// obj.toString() returns this:
//
// {"teste":"my.package.name.ClassePai#40516650"}
//
// BUT...
//wondering on net, I've deceided to try Gson:
//first part: object to string
Gson obj = new Gson();
obj.toJson(cp);
String obj_in_xml = obj.toString();
Toast.makeText( getApplicationContext() , obj_in_xml, Toast.LENGTH_SHORT).show();
//no error, appear works fine, but...
//second part: string to object
Gson obj2 = new Gson();
ClassePai new_cp = obj2.fromJson( obj_in_xml, ClassePai.class);
Toast.makeText( getApplicationContext() , new_cp.Nome(), Toast.LENGTH_SHORT).show();
//give me an error com.google.gson.stream.MalformedJsonException
//and I could't find my properties in obj.toString(), but only codes like:
//
//adapter=com.google.gson.internal.bind.TypeAdapters$7#40529278]
//
// and don't find any of the object's string properties in the obj.toString() string
//
// what I'm doing wrong????
}
}
How can I do to save this object with children in a text format, and after load from String to the objects again?
Please help me!!!
May be the problem is here:
Toast.makeText(getApplicationContext(), cp.length(), Toast.LENGTH_SHORT).show();
Here the second parametr must be an integer reference to a string resource or string value. If you want to show the size as a toast message use this variant:
Toast.makeText(getApplicationContext(), String.valueOf(cp.length()), Toast.LENGTH_SHORT).show();
Update
To convert JSON Object to String use:
String myString = myJSONObject.toString();
String to JSONObject:
JSONObject myJSONObject = getJSONObject(myString);
The first problem is that, you can't pass a int type to the method "Toast.makeText". You can convert the int to the String and show it. By String lengthString = String.valueOf(cp.length()).
The second problem you can use the xml to save and read string.
JSONObject person = new JSONObject();
String spmnoName = "spmno";
try{
person.put("name", spmnoName);
String getString = person.getString("name");
}catch(JSONException ex){
throw new RuntimeException(ex);
}

Android - How to create a basic class and use it?

I have defined a class that contains properties of a specific answer object
The class look like this and is defined inside the class that is trying to use it
protected class Answer {
String QuestionId = "";
String AnswerValue = "";
String Correct = "";
public String getQuestionId() {
return QuestionId;
}
public void setQuestionId(String arg) {
QuestionId = arg;
}
public String getAnswerValue() {
return AnswerValue;
}
public void setAnswerValue(String arg) {
AnswerValue = arg;
}
public String getCorrect() {
return Correct;
}
public void setCorrect(String arg) {
Correct = arg;
}
}
Not sure if the above is OK
When I try to use the class I get null pointer errors
I'm using it like this
ArrayList<Answer> answerList = new ArrayList<Answer>();
for(int a=0;a<answers.getLength(); a++){
Element eAnswer = (Element) answers.item(a);
Answer anAnswer = new Answer;
NodeList answer_nodes = eAnswer.getChildNodes();
for (int ian=0; ian<answer_nodes.getLength(); ian++){
Node ans_attr = answer_nodes.item(ian);
String tag_name = ans_attr.getNodeName();
if(tag_name.equalsIgnoreCase("answer")){
anAnswer.setAnswerValue(ans_attr.getTextContent());
}
}
answerList.add(anAnswer);
}
Answer anAnswer = new Answer; gives a compilation error
All I'm trying to do is to create a list of answers which have a name value pair for a number of properties
Any guidance on this greatly appreciated - Especially if there is a better way
Answer anAnswer = new Answer();

Android: Passing extra from one activity to another activity

I have a JSON file which is populated to an activity (Main.java).
This Activity shows 3 random images from the URL on my JSON entries.
What I wanna do is: I have 13 different entries on the my JSON, whenever I click the shown random picture it goes to another activity (ProjectDetail.java) containing the picture,title,and description depends on the item I click based on its entry on the JSON.
What do I have in is by using extra by I dont know exactly how to perform that since I'm using JSON. What should I add into my top_listener method on my Main class and what should I add into my ProjectDetail class?
Thank you.
Main.java
public class Main extends Activity {
/** Called when the activity is first created. */
ArrayList<Project> prjcts=null;
private ImageThreadLoader imageLoader = new ImageThreadLoader();
private final static String TAG = "MediaItemAdapter";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
prjcts = new ArrayList<Project>();
WebService webService = new WebService("http://liebenwald.spendino.net/admanager/dev/android/projects.json");
Map<String, String> params = new HashMap<String, String>();
params.put("var", "");
String response = webService.webGet("", params);
try
{
Type collectionType = new TypeToken<ArrayList<Project>>(){}.getType();
List<Project> lst= new Gson().fromJson(response, collectionType);
for(Project l : lst)
{
prjcts.add(l);
ConstantData.projectsList.add(l);
}
}
catch(Exception e)
{
Log.d("Error: ", e.getMessage());
}
final Button project = (Button) findViewById(R.id.btn_projectslist);
final Button infos = (Button) findViewById(R.id.btn_infos);
final Button contact = (Button) findViewById(R.id.btn_contact);
project.setOnClickListener(project_listener);
infos.setOnClickListener(infos_listener);
contact.setOnClickListener(contact_listener);
ImageView image1;
ImageView image2;
ImageView image3;
try {
image1 = (ImageView)findViewById(R.id.top1);
image2 = (ImageView)findViewById(R.id.top2);
image3 = (ImageView)findViewById(R.id.top3);
} catch( ClassCastException e ) {
Log.e(TAG, "Your layout must provide an image and a text view with ID's icon and text.", e);
throw e;
}
Bitmap cachedImage1 = null;
Bitmap cachedImage2 = null;
Bitmap cachedImage3 = null;
//randomize the index of image entry
int max = prjcts.size();
List<Integer> indices = new ArrayList<Integer>(max);
for(int c = 0; c < max; ++c)
{
indices.add(c);
}
int arrIndex = (int)((double)indices.size() * Math.random());
int randomIndex1 = indices.get(arrIndex);
indices.remove(arrIndex);
int randomIndex2 = indices.get(arrIndex);
indices.remove(arrIndex);
int randomIndex3 = indices.get(arrIndex);
indices.remove(arrIndex);
setImage(cachedImage1, image1, prjcts.get(randomIndex1));
setImage(cachedImage2, image2, prjcts.get(randomIndex2));
setImage(cachedImage3, image3, prjcts.get(randomIndex3));
image1.setOnClickListener(top_listener);
image2.setOnClickListener(top_listener);
image3.setOnClickListener(top_listener);
}
public void setImage(Bitmap cachedImage, final ImageView image, Project pro)
{
//Bitmap cachedImage1 = null;
try {
cachedImage = imageLoader.loadImage(pro.smallImageUrl, new ImageLoadedListener()
{
public void imageLoaded(Bitmap imageBitmap)
{
image.setImageBitmap(imageBitmap);
//notifyDataSetChanged();
}
});
} catch (MalformedURLException e) {
Log.e(TAG, "Bad remote image URL: " + pro.smallImageUrl, e);
}
if( cachedImage != null ) {
image.setImageBitmap(cachedImage);
}
}
private OnClickListener top_listener = new OnClickListener() {
public void onClick(View v) {
Intent top = new Intent(Main.this, InfosActivity.class);
startActivity(top);
}
};
ProjectDetail.java
public class ProjectDetail extends Activity implements OnClickListener{
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.project);
Button weitersagen = (Button) findViewById(R.id.btn_weitersagen);
weitersagen.setOnClickListener(this);
Button sms = (Button) findViewById(R.id.btn_sms_spenden);
sms.setOnClickListener(this);
int position = getIntent().getExtras().getInt("spendino.de.ProjectDetail.position");
Project project = ConstantData.projectsList.get(position);
try {
ImageView projectImage = (ImageView)findViewById(R.id.project_image);
Bitmap bitmap = BitmapFactory.decodeStream((InputStream)new URL(project.bigImageUrl).getContent());
projectImage.setImageBitmap(bitmap);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
TextView project_title = (TextView)findViewById(R.id.txt_project_title);
project_title.setText(project.project_title);
TextView organization_title = (TextView)findViewById(R.id.txt_organization_title);
organization_title.setText(Html.fromHtml("von " +project.organization_title));
TextView project_description = (TextView)findViewById(R.id.txt_project_description);
project_description.setText(Html.fromHtml(project.project_description));
}
I also have this ConstantData.java, the index which holds my JSON properties:
public class ConstantData{
public static String project_title = "project title";
public static String organization_title = "organization title";
public static String keyword = "keyword";
public static String short_code = "short code";
public static String project_description = "description";
public static String smallImageUrl = "smallImageUrl";
public static String bigImageUrl = "bigImageUrl";
public static String price= "price";
public static String country= "country";
public static ArrayList<Project> projectsList = new ArrayList<Project>();
public int describeContents() {
return 0;
}
public void writeToParcel(Parcel out, int flags) {
out.writeString(project_title);
out.writeString(organization_title);
out.writeString(keyword);
out.writeString(short_code);
out.writeString(project_description);
out.writeString(smallImageUrl);
out.writeString(bigImageUrl);
out.writeString(price);
out.writeString(country);
}
public static final Parcelable.Creator<ConstantData> CREATOR
= new Parcelable.Creator<ConstantData>() {
public ConstantData createFromParcel(Parcel in) {
return new ConstantData(in);
}
public ConstantData[] newArray(int size) {
return new ConstantData[size];
}
};
private ConstantData(Parcel in) {
project_title = in.readString();
organization_title = in.readString();
keyword = in.readString();
short_code = in.readString();
project_description = in.readString();
smallImageUrl = in.readString();
bigImageUrl = in.readString();
price = in.readString();
country = in.readString();
}
}
You could make the class ConstantData serializable by extending from Parcelable and implementing a couple of methods (see the documentation). Then you could pass a constantData instance as an extra by doing
intent.putExtra("jsonData", constantDataInstance);
and retrieving it from the other activity (in it's onCreate() method) with
getIntent().getExtras().getParcelable("jsonData");
Otherwise you could just past as extra every field independently, but it would be a mess. This way is not only more easy to read and everything, but "well designed".
To pass information from one activity to another when you start the new one you do the following:
Intent top = new Intent(Main.this, InfosActivity.class);
Bundle b = new Bundle();
b.putString("key1", "value2");
b.putString("key2", "value2");
b.putString("key3", "value3");
top.putExtras(b);
startActivity(top);
Then in the newly started activity, in the onCreate() put the following:
Bundle b = getIntent().getExtras();
b.get("key1");
b.get("key2");
b.get("key3");
This will get the values from the previous activity by using the key you provided.
For more complex objects you should extend Parcelable (probably what you'll need) and then use:
b.putParcelable("Key4", yourParcelableObject);
And in your onCreate()
b.getParcelable("Key4");
I hope this helps.
Use gson to parse the json to Java. Then you can use Wagon to move the extras around with ease.
GSON:
https://github.com/google/gson
Wagon:
https://github.com/beplaya/Wagon

Categories

Resources