Instance of class in Java can't be tested for null - java

I'm trying to troubleshoot a null-pointer exception that keeps me from populating an array adapter. I've traced it down to the point at which I create an instance of the class, and so to try to troubleshoot, I created the following toast:
private void showSplits() {
// populate the split line
Split s = new Split();
s = mTransaction.getSplit();
int duration = Toast.LENGTH_SHORT;
if (s != null) {
Toast toast = Toast.makeText(getActivity(), s.getCategory(), duration);
Toast toast2 = Toast.makeText(getActivity(), s.getDescription(), duration);
Toast toast3 = Toast.makeText(getActivity(), s.getAmount(), duration);
toast.show();
toast2.show();
toast3.show();
} else {
Toast toast4 = Toast.makeText(getActivity(), "S was null.", duration);
toast4.show();
}
....
}
When run, the result of this method is to neatly print out the content of each field of the split, then neatly print out "S was null." I've verified that I'm calling the method only once, so I can't see how s could both be null and not null.
Here's the detail of the class...
public class Split implements Serializable {
private static final long serialVersionUID = 1L;
private static final String JSON_CATEGORY = "category";
private static final String JSON_AMOUNT = "amount";
private static final String JSON_DESCRIPTION = "description";
private UUID mId;
private String mCategory;
private String mAmount;
private String mDescription;
public Split(String category, String amount, String description) {
mCategory = category;
mAmount = amount;
mDescription = description;
}
public Split() {
mId = UUID.randomUUID();
mCategory = "none";
}
public Split(JSONObject json) throws JSONException {
if (json.has(JSON_CATEGORY)) {
mCategory = json.getString(JSON_CATEGORY);
}
if (json.has(JSON_AMOUNT)) {
mAmount = json.getString(JSON_AMOUNT);
}
if (json.has(JSON_DESCRIPTION)) {
mDescription = json.getString(JSON_DESCRIPTION);
}
}
public JSONObject toJSON() throws JSONException {
JSONObject json = new JSONObject();
// if (mCategory != null) {
json.put(JSON_CATEGORY, mCategory);
// }
// if (mAmount != null) {
json.put(JSON_AMOUNT, mAmount);
// }
// if (mDescription != null) {
json.put(JSON_DESCRIPTION, mDescription);
// }
return json;
}
// Factory method to convert an array of JSON objects into a list of objects
// User.fromJson(jsonArray);
public static ArrayList<Split> fromJson(JSONArray jsonObjects) {
ArrayList<Split> splits = new ArrayList<Split>();
for (int i = 0; i < jsonObjects.length(); i++) {
try {
splits.add(new Split(jsonObjects.getJSONObject(i)));
} catch (JSONException e) {
e.printStackTrace();
}
}
return splits;
}
public String getCategory() {
return mCategory;
}
public void setCategory(String category) {
mCategory = category;
}
public String getAmount() {
return mAmount;
}
public void setAmount(String amount) {
mAmount = amount;
}
public String getDescription() {
return mDescription;
}
public void setDescription(String description) {
mDescription = description;
}
}
To the best of my abilities to tell, showSplits is called only once in the fragment I'm working in.

In the first line you are referencing s variable to a new Split Object, And in the second line you are changing the reference of s to mTransaction.getSplit(). If the object is returned by mTransaction.getSplit() is null then your s will reference to null. Means value of s will be null.
Split s = new Split();
s = mTransaction.getSplit();
your mTransaction.getSplit() may be returning null value , Try to debug it

Related

how to upload file from retrofit android java

am using retrofit for insert data to my webservice, I have made it before but without uploading the image and the insert is successful, the input field through the model class not in interface,how I add an input field fot uploading files through the model so that it can be sent to my web services storage folder?
I have tried but failed please help
for my insert in activity
btnsubmit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String tanggal = textdate.getText().toString();
SimpleDateFormat formatter1=new SimpleDateFormat("dd/MM/yyyy");
Date date1= null;
try {
date1 = formatter1.parse(tanggal);
} catch (ParseException e) {
e.printStackTrace();
}
SwabtestModel sw = new SwabtestModel();
sw.sethasil(texthasil.getText().toString());
sw.settanggal(date1);
sw.settempat(texttempat.getText().toString());
sw.setuserid(Integer.valueOf(txtuserid.getText().toString()));
sw.setFile_name(new File(txturi.getText().toString()));
save(sw);
}
});
public void save(SwabtestModel sw){
Call<SwabtestModel> call = swabtestService.addswab(sw);
call.enqueue(new Callback<SwabtestModel>() {
#Override
public void onResponse(Call<SwabtestModel> call, Response<SwabtestModel> response) {
if(response.isSuccessful()){
String status = response.body().getStatus();
Toast.makeText(SwabtestActivity.this, status, Toast.LENGTH_LONG).show(); }
}
#Override
public void onFailure(Call<SwabtestModel> call, Throwable t) {
Log.e("ERROR: ", t.getMessage());
}
});
}
for my file chooser
public void onActivityResult(int request_code, int result_code, Intent data){
super.onActivityResult(request_code,result_code,data);
if(request_code==request_code && result_code== Activity.RESULT_OK){
if(data==null){
return;
}
uri= data.getData();
filePath = uri.getPath();
txturi.setText(filePath);
}
}
public void openfilechooser(){
Intent intent= new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("*/*");
startActivityForResult(intent,request_code);
}
for my model class
public class SwabtestModel {
#SerializedName("hasil")
#Expose
private String hasil;
#SerializedName("tanggal")
#Expose
private Date tanggal;
#SerializedName("tempat")
#Expose
private String tempat;
#SerializedName("file_name")
#Expose
private File file_name;
#SerializedName("user_id")
#Expose
private Integer user_id;
String data;
String status;
public SwabtestModel(String hasil, Date tanggal, String tempat){
this.hasil = hasil;
this.tanggal = tanggal;
this.tempat = tempat;
}
public void sethasil(String hasil) {
this.hasil = hasil;
}
public String gethasil(){
return hasil;
}
public void settanggal(Date tanggal) {
this.tanggal = tanggal;
}
public Date gettanggal(){
return tanggal;
}
public void settempat(String tempat) {
this.tempat = tempat;
}
public String gettempat(){
return tempat;
}
public void setuserid(Integer user_id) {
this.user_id = user_id;
}
public Integer getuserid(){
return user_id;
}
public void setFile_name( File file_name) {
this.file_name =file_name ;
}
public File getfilename(){
return file_name;
}
public String getData() {
return data;
}
public String getStatus() {
return status;
}
}
my interface
public interface swabtestService
{
#GET("hasil-antigen-list")
Call<List<SwabtestModel>> getUsers();
#POST("insert-hantigen")
Call<SwabtestModel> addswab(#Body SwabtestModel swabtest);
}
To upload files you should use Multipart, Please refer to this post for example and please ping me if you have any queries https://stackoverflow.com/a/39953566
Take a data in list like #Part List<MultipartBody.Part> partFile
private List<MultipartBody.Part> getMapPartListSave(List<PojoAttachDocList> fields) {
List<MultipartBody.Part> mapPart = new ArrayList<>();
for (int i = 0; i < fields.size(); i++) {
**PojoAttachDocList** attachDoc = fields.get(i);
if (!attachDoc.isAttached() && attachDoc.getDocFile() != null && attachDoc.getDocFile().exists()
&& attachDoc.getDocFile().length() > 0) {
String fileParam = PARAMS_DOCUMENT + "[" + i + "]";
mapPart.add(MultipartBody.Part.createFormData(fileParam, attachDoc.getDocFile().getName(),
RequestBody.create(MediaType.parse("*/*"), attachDoc.getDocFile())));
}
}
return mapPart;
}
Convert it to MultipartBody

How to pass raw data in API request using Retrofit2 [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 3 years ago.
I am trying to call login API using Retrofit2.
But in onResponse i alwasy get null as response.
Login API endpoint
#FormUrlEncoded
#POST("/api/login/{mobile}")
Call<ResObj> userLogin( #Field("phoneNumber") String mobile );
And the API implementation
private void doLogin(final String mobile){
Call<ResObj> call = userService.login(mobile);
call.enqueue(new Callback<ResObj>() {
#Override
public void onResponse(Call<ResObj> call, Response<ResObj> response) {
ResObj resObj = response.body(); // here i am getting null response.body()
if(resObj.getMessage().equals("true")){
Intent intent = new Intent(Login.this, ListActivity.class);
intent.putExtra("mobile", mobile);
startActivity(intent);
} else{
Toast.makeText(Login.this, "Phone Number is incorrect!", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onFailure(Call<ResObj> call, Throwable t) {
Toast.makeText(Login.this, t.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
ResObj class:
public class ResObj {
private String message;
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
I just want to know what causes the error and what are possible solutions.
UPDATE
POSTMAN
You are getting null response in your login API. It may be due to many reasons. You can check your API is working as expected or not using POSTMAN.
And inside your code, you can prevent this type of exception by checking OBJECT is null or not. like the following.
#Override
public void onResponse(Call<ResObj> call, Response<ResObj> response) {
ResObj resObj = response.body();
if(resObj != null){ // checking object is not null
if(resObj.getStatus()){
Intent intent = new Intent(Login.this, ListActivity.class);
intent.putExtra("mobile", mobile);
startActivity(intent);
} else{
Toast.makeText(Login.this, "Phone Number is incorrect!", Toast.LENGTH_SHORT).show();
}
}else{
// handle null response here.
}
}
Update:
According to your Response JSON, Your Model(ResObj) class should be like the following.
public class ResObj
{
private String date;
private String address;
private String accountName;
private String contactPerson;
private String timeOut;
private String problem;
private String srNo;
private String fieldEngineer;
private String joNo;
private String irNo;
private String designation;
private String email;
private String timeIn;
private String productType;
private boolean status;
private String contactNo;
public String getDate ()
{
return date;
}
public void setDate (String date)
{
this.date = date;
}
public String getAddress ()
{
return address;
}
public void setAddress (String address)
{
this.address = address;
}
public String getAccountName ()
{
return accountName;
}
public void setAccountName (String accountName)
{
this.accountName = accountName;
}
public String getContactPerson ()
{
return contactPerson;
}
public void setContactPerson (String contactPerson)
{
this.contactPerson = contactPerson;
}
public String getTimeOut ()
{
return timeOut;
}
public void setTimeOut (String timeOut)
{
this.timeOut = timeOut;
}
public String getProblem ()
{
return problem;
}
public void setProblem (String problem)
{
this.problem = problem;
}
public String getSrNo ()
{
return srNo;
}
public void setSrNo (String srNo)
{
this.srNo = srNo;
}
public String getFieldEngineer ()
{
return fieldEngineer;
}
public void setFieldEngineer (String fieldEngineer)
{
this.fieldEngineer = fieldEngineer;
}
public String getJoNo ()
{
return joNo;
}
public void setJoNo (String joNo)
{
this.joNo = joNo;
}
public String getIrNo ()
{
return irNo;
}
public void setIrNo (String irNo)
{
this.irNo = irNo;
}
public String getDesignation ()
{
return designation;
}
public void setDesignation (String designation)
{
this.designation = designation;
}
public String getEmail ()
{
return email;
}
public void setEmail (String email)
{
this.email = email;
}
public String getTimeIn ()
{
return timeIn;
}
public void setTimeIn (String timeIn)
{
this.timeIn = timeIn;
}
public String getProductType ()
{
return productType;
}
public void setProductType (String productType)
{
this.productType = productType;
}
public boolean getStatus ()
{
return status;
}
public void setStatus (boolean status)
{
this.status = status;
}
public String getContactNo ()
{
return contactNo;
}
public void setContactNo (String contactNo)
{
this.contactNo = contactNo;
}
}
You are passing parameter as raw data(according to your screen-shot). So your API endpoint would be like below.
#Headers("Content-Type: application/json")
#POST("/api/login")
Call<ResObj> userLogin(#Body JsonObject jsonObject);
And call your API like this
private void doLogin(final String mobile){
try {
JsonObject paramObject = new JsonObject();
paramObject.addProperty("mobile", mobile);
} catch (JSONException e) {
e.printStackTrace();
}
Call<ResObj> call = userService.login(paramObject);
call.enqueue(new Callback<ResObj>() {
//your rest of code
});
}
UPDATE-2:
To send object from one Activity to another using intent you have to make your model class Percelable. like this
// implements Parcelable
public class ResObj implements Parcelable {
// ...........your previous code here
// just simply add the following methods
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(date);
dest.writeString(address);
dest.writeString(accountName);
dest.writeString(contactPerson);
dest.writeString(timeOut);
dest.writeString(problem);
dest.writeString(srNo);
dest.writeString(fieldEngineer);
dest.writeString(joNo);
dest.writeString(irNo);
dest.writeString(designation);
dest.writeString(email);
dest.writeString(timeIn);
dest.writeString(productType);
dest.writeByte((byte) (status ? 1 : 0));
dest.writeString(contactNo);
}
public static final Parcelable.Creator<ResObj> CREATOR
= new Parcelable.Creator<ResObj>() {
public ResObj createFromParcel(Parcel in) {
return new ResObj(in);
}
public ResObj[] newArray(int size) {
return new ResObj[size];
}
};
protected ResObj(Parcel in) {
date = in.readString();
address = in.readString();
accountName = in.readString();
contactPerson = in.readString();
timeOut = in.readString();
problem = in.readString();
srNo = in.readString();
fieldEngineer = in.readString();
joNo = in.readString();
irNo = in.readString();
designation = in.readString();
email = in.readString();
timeIn = in.readString();
productType = in.readString();
status = in.readByte() != 0;
contactNo = in.readString();
}
}
Now pass your object via intent like the following.
if(resObj != null){
if(resObj.getStatus()){
Intent intent = new Intent(Login.this, ListActivity.class);
intent.putExtra("your_key", resObj); // pass resObj and use same key to get data
startActivity(intent);
} else{
Toast.makeText(Login.this, "Phone Number is incorrect!", Toast.LENGTH_SHORT).show();
}
}
Get data from your ListActivity like this
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
final ResObj yourObject = getIntent().getParcelableExtra("your_key"); // make sure you use same key like data.
// Now you can use your data like that
yourEditText.setText(yourObject.getEmail());
}

How to get the object properties from a list of objects in my model class so that I can pass the objects through intents?

I successfully parsed and retrieved all the data that I need from an xml document. I have two activities, one activity that shows the main data and other activity that shows an extra data for the recyclerView clicked item. I ma trying to pass all the data needed in the detail activity through intents from the main activity. But I am missing a method in my model class that helps me retrieve the objects themselves from the list to be able to send them into the putExtra(). So what should the method look like?
** The logcat is giving me this error in the detail activity: "Attempt to invoke virtual method 'void android.widget.TextView.setText(java.lang.CharSequence)' on a null object reference".
HERE is my MainAactivity:
public class MainActivity extends AppCompatActivity implements AdsAdapterOnClickHandler {
public static final String URL = "MYURL;
public static List<AdEntry> entryList = new ArrayList<>();
// Declaration
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Setting the recyclerView and the adapter
loadPage();
}
public void loadPage() {
new DownloadXmlTask().execute(URL);
System.out.print("Result" + "Succeed");
}
private class DownloadXmlTask extends AsyncTask<String, Void, List<AdEntry>> {
#Override
protected List<AdEntry> doInBackground(String... urls) {
try {
return loadXmlFromNetwork(urls[0]);
} catch (IOException e) {
return null;
} catch (XmlPullParserException e) {
return null;
}
}
#Override
protected void onPostExecute(List<AdEntry> adEntries) {
Toast.makeText(MainActivity.this, "Successfully Processed", Toast.LENGTH_SHORT).show();
mAdsAdapter.setAdData(adEntries);
super.onPostExecute(adEntries);
}
}
public List<AdEntry> loadXmlFromNetwork(String urlString) throws XmlPullParserException, IOException {
InputStream stream = null;
try {
stream = downloadUrl(urlString);
entryList = parse(stream);
} finally {
if (stream != null)
stream.close();
}
return entryList;
}
public InputStream downloadUrl(String urlString) throws IOException {
// Open HttpURLConnection
}
#Override
public void onClick(View view, int position) {
final AdEntry entry = entryList.get(position);
Class destinationClass = DetailActivity.class;
Intent intentToStartDetailActivity = new Intent(this, destinationClass);
intentToStartDetailActivity.putExtra("Product Name", entry.productName);
intentToStartDetailActivity.putExtra("Product Thumbnail", entry.productThumbnail);
intentToStartDetailActivity.putExtra("Product Description", entry.productDescription);
intentToStartDetailActivity.putExtra("Product AppId", entry.appId);
intentToStartDetailActivity.putExtra("Product CallToAction", entry.callToAction);
intentToStartDetailActivity.putExtra("Product Link", entry.proxyLink);
intentToStartDetailActivity.putExtra("Product ImageRating", entry.averageRatingImageURL);
intentToStartDetailActivity.putExtra("Product Category", entry.productCategory);
intentToStartDetailActivity.putExtra("Product Rating", entry.productRating);
intentToStartDetailActivity.putExtra("Product NumberOfRating", entry.numberOfRatings);
startActivity(intentToStartDetailActivity);
}
}
Here is my DetailActivity:
public class DetailActivity extends AppCompatActivity {
// Views Declaration
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_detail);
// findViewsById
retrieveData();
}
public void retrieveData() {
String productName = getIntent().getStringExtra("Product Name");
String productThumbnail = getIntent().getStringExtra("Product Thumbnail");
String productDescription = getIntent().getStringExtra("Product Description");
String productAppId = getIntent().getStringExtra("Product AppId");
String productCall = getIntent().getStringExtra("Product CallToAction");
String productLink = getIntent().getStringExtra("Product Link");
String productImageRating = getIntent().getStringExtra("Product ImageRating");
String productCategory = getIntent().getStringExtra("Product Category");
String productNumberOfRatings = getIntent().getStringExtra("Product NumberOfRating");
Picasso.get().load(productThumbnail).into(thumbnail_imageView);
name_textView.setText(productName);
description_textView.setText(productDescription);
numberOfRating_textView.setText(productNumberOfRatings);
link_textView.setText(productLink);
category_textView.setText(productCategory);
rating_textView.setText(productImageRating);
}
}
Here is my ModelClass:
public class AdEntry {
private List<AdEntry> entries;
public String appId;
public String averageRatingImageURL;
public String callToAction;
public String productCategory;
public String proxyLink;
public String productDescription;
public String numberOfRatings;
public String productName;
public String productThumbnail;
public String productRating;
public AdEntry() {
}
public AdEntry(String appId, String averageRatingImageURL, String callToAction, String productCategory, String proxyLink,
String productDescription, String numberOfRatings, String productName, String productThumbnail, String productRating) {
this.appId = appId;
this.averageRatingImageURL = averageRatingImageURL;
this.callToAction = callToAction;
this.productCategory = productCategory;
this.proxyLink = proxyLink;
this.productDescription = productDescription;
this.numberOfRatings = numberOfRatings;
this.productName = productName;
this.productThumbnail = productThumbnail;
this.productRating = productRating;
}
public String getAppId() {
return appId;
}
public String getAverageRatingImageURL() {
return averageRatingImageURL;
}
public String getCallToAction() {
return callToAction;
}
public String getProductCategory() {
return productCategory;
}
public String getProxyLink() {
return proxyLink;
}
public String getProductDescription() {
return productDescription;
}
public String getNumberOfRatings() {
return numberOfRatings;
}
public String getProductName() {
return productName;
}
public String getProductThumbnail() {
return productThumbnail;
}
public String getProductRating() {
return productRating;
}
}
Here is the part where I retrieved my List in the XMLPUllParser class:
private static List readAds(XmlPullParser parser) throws XmlPullParserException, IOException {
List<AdEntry> entries = new ArrayList();
parser.require(XmlPullParser.START_TAG, ns, "ads");
while (parser.next() != XmlPullParser.END_TAG) {
if (parser.getEventType() != XmlPullParser.START_TAG)
continue;
String name = parser.getName();
if (name.equals("ad"))
entries.add(readEntry(parser));
else
skip(parser);
}
System.out.println("entries" + entries);
return entries;
}
private static AdEntry readEntry(XmlPullParser parser) throws XmlPullParserException, IOException {
parser.require(XmlPullParser.START_TAG, ns, "ad");
while (parser.next() != XmlPullParser.END_TAG) {
if (parser.getEventType() != XmlPullParser.START_TAG)
continue;
String name = parser.getName();
switch (name) {
case "appId":
appId = readAppId(parser);
System.out.println("appId" + appId);
break;
case "averageRatingImageURL":
averageRatingImageURL = readRatingImage(parser);
System.out.println("rating" + averageRatingImageURL);
break;
case "callToAction":
callToAction = readCallToAction(parser);
System.out.println("callToAction" + callToAction);
break;
case "categoryName":
categoryName = readCategoryName(parser);
System.out.println("categoryName" + categoryName);
break;
case "clickProxyURL":
clickProxyURL = readProxyLink(parser);
System.out.println("clickProxyURL" + clickProxyURL);
break;
case "productDescription":
productDescription = readProductDescription(parser);
System.out.println("productDescription" + productDescription);
break;
case "numberOfRatings":
numberOfRatings = readNumberOfRatings(parser);
System.out.println("numberOfRatings" + numberOfRatings);
break;
case "productName":
productName = readNameProduct(parser);
System.out.println("productName" + productName);
break;
case "productThumbnail":
productThumbnail = readThumbnail(parser);
System.out.println("productThumbnail" + productThumbnail);
break;
case "rating":
rating = readRating(parser);
System.out.println("rating" + rating);
break;
default:
skip(parser);
break;
}
}
return new AdEntry(appId, averageRatingImageURL, callToAction, categoryName, clickProxyURL, productDescription,
numberOfRatings, productName, productThumbnail, rating);
}

Android TextView setText with Getter return

I just try my first Android app and have encountered a problem where I do not really get ahead. In my app I create an ArrayList which will filled with Objects. Each Object has four attributes. Now I´d like to write each attribute for each Object in its own specific TextView. But there is my Problem. If the same Code is run in a normal Java Application and I use System.out.Print("getter method") I get the Value I would like, but if I use .setText("getter method") I get what you can see on the screenshot.
ActivityClass:
public class ShowBeaconActivity extends Activity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_showbeacons);
setUpShowBeacons();
}
public void setUpShowBeacons(){
//
//Beacon 1
//
TextView beaconOneUUID = (TextView)findViewById(R.id.txtBeaconOneUUIDValue);
beaconOneUUID.setText(BeaconListe.getBeacon(0,"UUID"));
TextView beaconOneMajor = (TextView)findViewById(R.id.txtBeaconOneMajorValue);
beaconOneMajor.setText(BeaconListe.getBeacon(0,"Major"));
TextView beaconOneMinor = (TextView)findViewById(R.id.txtBeaconOneMinorValue);
beaconOneMinor.setText(BeaconListe.getBeacon(0,"Minor"));
TextView beaconOneRSSI = (TextView)findViewById(R.id.txtBeaconOneRSSIValue);
beaconOneRSSI.setText(BeaconListe.getBeacon(0,"RSSI"));
//
//Beacon 2
//
TextView beaconTwoUUID = (TextView)findViewById(R.id.txtBeaconTwoUUIDValue);
beaconTwoUUID.setText(BeaconListe.getBeacon(1,"UUID"));
...
}
}
BeaconClass:
public class Beacon {
private String UUID;
private String Major;
private String Minor;
private int RSSI;
public Beacon(String UUID, String Major,String Minor, int RSSI){
this.UUID = UUID;
this.Major = Major;
this.Minor = Minor;
this.RSSI = RSSI;
}
//
//Getter
//
public String getUUID(){
return UUID;
}
public String getMajor(){
return Major;
}
public String getMinor() {
return Minor;
}
public int getRSSI() {
return RSSI;
}
//
//Setter
//
public void setRSSI(int RSSI){
this.RSSI = RSSI;
}
}
BeaconListeClass
public class BeaconListe {
private static ArrayList<Beacon>Liste = new ArrayList<Beacon>();
//
//Getter
//
public static String getBeacon(int index, String value){
String result = "";
switch(value){
case "UUID": result = Liste.get(index).getUUID();
break;
case "Major": result = Liste.get(index).getMajor();
break;
case "Minor": result = Liste.get(index).getMinor();
break;
case "RSSI": int resultTemp = Liste.get(index).getRSSI();
result = String.valueOf(resultTemp);
break;
}
return result;
}
//
//Setter
//
public static void addBeacon(String UUID, String Major, String Minor, int RSSI){
Liste.add(new Beacon(UUID, Major, Minor, RSSI));
}
}
App Screenshot
It can crash because of null value;
public static String getBeacon(int index, String value)
{
String result = "";
switch(value){
Beacon becon = Liste.get(index);
case "UUID":
result = becon!=null?becon.getUUID():"";
break;
case "Major":
result = becon!=null?becon.getMajor():"";
break;
case "Minor":
result = becon!=null?becon.getMinor():"";
break;
case "RSSI":
resultTemp = becon!=null?becon.getRSSI():0;
result = String.valueOf(resultTemp);
break;
}
return result==null?"":result;
}
try this
TextView beaconOneUUID = (TextView)findViewById(R.id.txtBeaconOneUUIDValue);
if(BeaconListe.getBeacon(0,"UUID") != null){
beaconOneUUID.setText(BeaconListe.getBeacon(0,"UUID"));
}
TextView beaconOneMajor = (TextView)findViewById(R.id.txtBeaconOneMajorValue);
if(BeaconListe.getBeacon(0,"Major") != null){
beaconOneMajor.setText(BeaconListe.getBeacon(0,"Major"));
}
TextView beaconOneMinor = (TextView)findViewById(R.id.txtBeaconOneMinorValue);
if(BeaconListe.getBeacon(0,"Minor") != null){
beaconOneMinor.setText(BeaconListe.getBeacon(0,"Minor"));
}
TextView beaconOneRSSI = (TextView)findViewById(R.id.txtBeaconOneRSSIValue);
if(BeaconListe.getBeacon(0,"RSSI") != null){
beaconOneRSSI.setText(BeaconListe.getBeacon(0,"RSSI"));
}
//
//Beacon 2
//
TextView beaconTwoUUID = (TextView)findViewById(R.id.txtBeaconTwoUUIDValue);
if(BeaconListe.getBeacon(1,"UUID")){
beaconTwoUUID.setText(BeaconListe.getBeacon(1,"UUID"));
}
From what I see, the .setText("getter methods") work just fine. The problem is the text that it sets. Check your function in which you populate the BeaconListe, which you have not shown here.
I tried your code but with the following
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_showbeacons);
populateBeaconListe();
setUpShowBeacons();
}
public void populateBeaconListe(){
BeaconListe.addBeacon("B1UUID","B1MAJOR","B1MINOR",1111);
BeaconListe.addBeacon("B2UUID","B2MAJOR","B2MINOR",2222);
BeaconListe.addBeacon("B3UUID","B3MAJOR","B3MINOR",3333);
BeaconListe.addBeacon("B4UUID","B4MAJOR","B4MINOR",4444);
}
and it works just fine. See screenshot

Replacing an Array with an ArrayList

I am trying replace the arrays I have with arraylists so I don't have to worry about managing the arrays and can clean up my code. I have only just taught myself arraylists so I am having some issues. Mainly in these classes where all my "sets" and "gets" are. I don't think I have the right syntax because I am getting an ArrayList/String conflict error. Basically trying to get:
public static ArrayList<Resource> importResourcesFromXML(String documentLocation)
to import an arraylist of resources from an XML document. I also wanted to convert my arrays in Resources and my T_Resources into arraylists as well. This is the code I have so far, I believe I have Resources implemented correctly but could use help with the other two getting the XML resources to display properly.
EDIT: I want to if at all possible eliminate the array entirely and replace it with an arraylist. I want to try and avoid converting an array to an arraylist.
import java.util.ArrayList;
public class Resources {
//private static final int MAX_SUBJECTS = 20;
private String title;
private String description;
private Identifier identifier;
ArrayList<Subject> subject = new ArrayList<Subject>();
//private int subjectCount;
public Resources() {
title = "unknown title";
description = "unknown description";
identifier = null;
//subjects = new Subject[MAX_SUBJECTS];
//subjectCount = 0;
}
public void setTitle(String newTitle) {
title = newTitle;
}
public String getTitle() {
return title;
}
public void setDescription(String newDescription) {
description = newDescription;
}
public String getDescription() {
return description;
}
public void setIdentifier(Identifier newIdentifier) {
identifier = newIdentifier;
}
public Identifier getIdentifier() {
return identifier;
}
public void addSubject(Subject newSubject) {
subject.add(newSubject);
}
public ArrayList<Subject> getSubjects() {
//Subject[] result = new Subject[subjectCount];
//System.arraycopy(subjects, 0, result, 0, subjectCount);
return subject;
}
}
public class ResourceImporter {
// This operation loads the XML document specified by the document location, which can a file or a URL,
// and returns a reference to the document. If the operation cannot successfully load the document
// the operation returns the null reference.
//
private static Document loadXMLDocument(String documentLocation) {
// The XML document.
//
Document documentIn = null;
// The parser that reads in an XML files.
//
DocumentBuilder parser = null;
// Pull the document
//
try {
// Obtain a document parser.
//
DocumentBuilderFactory builderFactory = DocumentBuilderFactory.newInstance();
builderFactory.setNamespaceAware(true);
parser = builderFactory.newDocumentBuilder();
documentIn = parser.parse(documentLocation);
} catch (ParserConfigurationException p) {
System.out.println("Error creating parser.");
System.out.println(" " + p.getMessage());
} catch (SAXException s) {
System.out.println("Document is not well formed.");
System.out.println(" " + s.getMessage());
} catch (IOException i) {
System.out.println("Error accessing the file.");
System.out.println(" " + i.getMessage());
} catch (Exception e) {
System.out.println("Unknown error occurred.");
System.out.println(" " + e.getMessage());
}
return documentIn;
}
public static ArrayList<Resource> importResourcesFromXML(String documentLocation) {
ArrayList<Resource> resource = new ArrayList<Resource>();
Document doc;
Element resourceElement;
Element titleElement;
String title;
Element descriptionElement;
String description;
Element identifierElement;
String identifiers;
Element urlElement;
String url;
NodeList subjectList;
Element subjectElement;
String subjects;
Element categoryElement;
String category;
Element subcategoryElement;
String subcategory;
doc = loadXMLDocument(documentLocation);
resourceElement = (Element)doc.getElementsByTagName("resource").item(0);
if (resourceElement != null) {
titleElement = (Element)resourceElement.getElementsByTagName("title").item(0);
resource.setTitle( titleElement == null ? "unknown" : titleElement.getTextContent() );
descriptionElement = (Element)resourceElement.getElementsByTagName("description").item(0);
resource.setDescription( descriptionElement == null ? "unknown" : descriptionElement.getTextContent() );
identifierElement = (Element)resourceElement.getElementsByTagName("identifier").item(0);
if (identifierElement != null) {
Identifier identifier = new Identifier();
urlElement = (Element)identifierElement.getElementsByTagName("url").item(0);
identifier.setURL( urlElement == null ? "unknown" : urlElement.getTextContent() );
resource.setIdentifier(identifier);
subjectElement = (Element)resourceElement.getElementsByTagName("subjects").item(0);
if (subjectElement != null) {
subjectList = subjectElement.getElementsByTagName("subject");
for (int i=0; i < subjectList.getLength(); ++i) {
Subject subject = new Subject();
subjectElement = (Element)subjectList.item(i);
categoryElement = (Element)subjectElement.getElementsByTagName("category").item(0);
subject.setCategory( categoryElement == null ? "unknown" : categoryElement.getTextContent() );
subcategoryElement = (Element)subjectElement.getElementsByTagName("subcategory").item(0);
subject.setSubcategory( subcategoryElement == null ? "unknown" :subcategoryElement.getTextContent() );
resource.addSubject(subject);
}
}
}
}
return resource;
}
}
import java.util.ArrayList;
public class T_Resources {
public static void main(String[] args) {
ArrayList<Resource> resource = ResourceImporter.importResourcesFromXML("http://free1.ed.gov/xml/gemexport.xml");
displayResources(resource);
}
private static void displayResources(ArrayList<Resource> resource) {
ArrayList<Subject> subjects;
System.out.println(resource.getTitle());
System.out.println(resource.getDescription());
System.out.println(resource.getIdentifier().getURL());
subjects = resource.getSubjects();
for (int i=0; i < subjects.size(); ++i) {
System.out.println(subjects.getCategory() + " :: " + subjects.getSubcategory());
}
System.out.println();
}
}
public class Subject {
private String category;
private String subcategory;
public Subject() {
String category = "unknown";
String subcategory = "unknown";
}
public Subject(Subject subject) {
category = subject.category;
subcategory = subject.subcategory;
}
public void setCategory(String newCategory) {
category = (newCategory == null) ? "unknown" : newCategory;
}
public String getCategory() {
return category;
}
public void setSubcategory(String newSubcategory) {
subcategory = newSubcategory;
}
public String getSubcategory() {
return subcategory;
}
}
public class Identifier {
private String url;
public Identifier() {
url = "unknown";
}
public void setURL(String newURL) {
url = newURL;
}
public String getURL() {
return url;
}
}
Let me know if I'm misinterpreting things, but if all you're looking for is a way to convert a primitive array into an ArrayList then I would use the following:
arrayList = Arrays.asList(array);

Categories

Resources