Setter doesnt work [closed] - java

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
Iam trying to make login activity
I got a problem. My setter doesnt work, i dont know why?
I have 3 classes.
1st one is Data with server data and getters and setters
public class Data{
String addressesURL = "/DataSnap/rest/TServerMethods1/LookupCustomers";
String articlesURL = "/DataSnap/rest/TServerMethods1/LookupArticle";
String invoicesURL = "/DataSnap/rest/TServerMethods1/LookupInvoice";
String invoicesDetailsURL = "/DataSnap/rest/TServerMethods1/LookupInvoicePos";
String invoicesDetailsAddressesURL = "/DataSnap/rest/TServerMethods1/LookupInvoiceAddress";
String ordersURL = "/DataSnap/rest/TServerMethods1/LookupOrders";
String ordersDetailsURL = "/DataSnap/rest/TServerMethods1/LookupOrdersPos";
String ordersDetailsAddressesURL = "/DataSnap/rest/TServerMethods1/LookupOrdersAddress";
public String serverURL;
//String serverURL = "http://10.10.10.75:8081";
String username = "admin";
String password = "admin";
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getAddressesURL() {
return addressesURL;
}
public void setAddressesURL(String addressesURL) {
this.addressesURL = addressesURL;
}
public String getArticlesURL() {
return articlesURL;
}
public void setArticlesURL(String articlesURL) {
this.articlesURL = articlesURL;
}
public String getInvoicesURL() {
return invoicesURL;
}
public void setInvoicesURL(String invoicesURL) {
this.invoicesURL = invoicesURL;
}
public String getInvoicesDetailsURL() {
return invoicesDetailsURL;
}
public void setInvoicesDetailsURL(String invoicesDetailsURL) {
this.invoicesDetailsURL = invoicesDetailsURL;
}
public String getInvoicesDetailsAddressesURL() {
return invoicesDetailsAddressesURL;
}
public void setInvoicesDetailsAddressesURL(String invoicesDetailsAddressesURL) {
this.invoicesDetailsAddressesURL = invoicesDetailsAddressesURL;
}
public String getOrdersURL() {
return ordersURL;
}
public void setOrdersURL(String ordersURL) {
this.ordersURL = ordersURL;
}
public String getOrdersDetailsURL() {
return ordersDetailsURL;
}
public void setOrdersDetailsURL(String ordersDetailsURL) {
this.ordersDetailsURL = ordersDetailsURL;
}
public String getOrdersDetailsAddressesURL() {
return ordersDetailsAddressesURL;
}
public void setOrdersDetailsAddressesURL(String ordersDetailsAddressesURL) {
this.ordersDetailsAddressesURL = ordersDetailsAddressesURL;
}
public String getServerURL() {
return serverURL;
}
public void setServerURL(String serverURL) {
this.serverURL = serverURL;
}}
2nd one is where I start my login Activity
public class Settings extends AppCompatActivity {
//declarations
//Edittext fields for username , server, password & port information
EditText edtIpurl, edtPort, edtUsername, edtPassword;
//Textviews that can be clicked
TextView databaseDel, databaseRef, magnumgmbh, contact, support;
//imagebuttons for bottom menu
ImageButton contacts, articles, invoices, orders;
//string for server URL
//String sURL = "http://";
Thread newSettingsThread;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);
setTitle("Settings");
newSettingsThread = new Thread(){
public void run(){
runOnUiThread(new Runnable() {
#Override
public void run() {
String serverURL = "http://rest.magnumgmbh.de";
//edtIpurl = (EditText)findViewById(R.id.edtIpurl);
Data newD = new Data();
newD.setServerURL(serverURL);
}
});
}
};
newSettingsThread.start();
//start activitys if bottom buttons clicked
contacts = (ImageButton) findViewById(R.id.contacts);
//articles activity start
contacts.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//start activity addresses
Intent startAddresses = new Intent(Settings.this, Addresses.class);
startActivity(startAddresses);
}
});
}}
And the next one is where i try to get my new serverURL
public class Address extends AppCompatActivity{
Thread newAddressThread;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_addresses);
//set activity name
setTitle("Addresses");
//new thread for network operations
newAddressesThread = new Thread() {
public void run() {
//make text from json
jsonText = new StringBuilder();
try {
String str;
Data newData = new Data();
//json dates url
String addressesURL = newData.getAddressesURL();
String serverUrl = newData.getServerURL();
String username = newData.getUsername();
String password = newData.getPassword();
URL url = new URL(serverUrl + addressesURL);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
//String encoded = Base64.encode("admin:admin");
String encoded = Base64.encodeToString((username+":"+password).getBytes("UTF-8"), Base64.NO_WRAP);
urlConnection.setRequestProperty("Authorization", "Basic " + encoded);
//check http status code
try {
int statusCode = urlConnection.getResponseCode();
System.out.println(statusCode);
} catch (IOException e) {
}
BufferedReader in = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
while ((str = in.readLine()) != null) {
jsonText.append(str);
}
//cast stringbuilder to string
addressesJsonStr = jsonText.toString();
//close IOstream
in.close();
} catch (MalformedURLException e1) {
System.out.println(e1.getMessage());
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
};
//start thread
newAddressesThread.start();
}}
Hier in the third one by serverURL I got null and it thow me an exeption "Protocol not found: null/DataSnap/rest/TServerMethods1/LookupCustomers" so that is my problem.
What do I wrong?

you are creating a new Object in the third class, so the url has the initilize value because the url you've setted in the second class is stored in another object.
If you want that all Objects of Type Data have the same adress, make the variable static otherwise you have to access the object you have created in the second class in the third class.

Related

javafx ComboBox with cellfactory does not display selected item

I have a small proof of concept app which contains 6 Labels a ComboBox and a Button, all created using SceneBuilder.
By clicking the Button, the app makes a Json api call to return a list of countries and their related details (apla2code, apla3code, name etc). I created a CountryDetails object which holds 3 String elements. I use that to return an array of the CountryDetails which I then load into an array of ObserbavleList. I then apply that to a ComboBox and I load the CountryDetails elements into 3 labels each time an item is selected in the ComboBox. The All of this works fine (although there is probably a much better way of doing this).
The problem I am having is that the ComboBox is not displaying the selected item and I cannot figure out how to correct this. The image below shows what the issue is.
The code which makes the api call is as follows:
import com.google.gson.Gson;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class GetCountries {
public CountryDetails[] getDetails() {
String inputLine = "";
StringBuilder jsonString = new StringBuilder();
HttpURLConnection urlConnection;
try {
URL urlObject = new URL("https://restcountries.eu/rest/v2/all");
urlConnection = (HttpURLConnection) urlObject.openConnection();
urlConnection.setRequestMethod("GET");
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
while ((inputLine = bufferedReader.readLine()) != null) {
jsonString.append(inputLine);
}
urlConnection.getInputStream().close();
} catch(IOException ioe) {
System.out.println(ioe.getMessage());
}
Countries[] countries = new Gson().fromJson(jsonString.toString(), Countries[].class);
CountryDetails[] countryDetails = new CountryDetails[countries.length];
for(int i = 0; i < countries.length; i++){
countryDetails[i] = new CountryDetails(
countries[i].getAlpha2Code(),
countries[i].getAlpha3Code(),
countries[i].getName()
);
}
return countryDetails;
}
}
The code for the CountryDetails object is as follows:
public class CountryDetails {
private String alpha2Code;
private String alpha3Code;
private String name;
public CountryDetails(String strAlpha2Code, String strAlpha3Code, String strName) {
this.alpha2Code = strAlpha2Code;
this.alpha3Code = strAlpha3Code;
this.name = strName;
}
public String getAlpha2Code() { return alpha2Code; }
public void setAlpha2Code(String alpha2Code) { this.alpha2Code = alpha2Code; }
public String getAlpha3Code() { return alpha3Code; }
public void setAlpha3Code(String alpha3Code) { this.alpha3Code = alpha3Code; }
public String getName() { return name; }
public void setName(String name) {this.name = name; }
}
The code which loads the ObservableList is as follows:
GetCountries countries = new GetCountries();
CountryDetails[] countryDetails = countries.getDetails();
for (CountryDetails countryDetail : countryDetails) {
countriesObservableList.add(new CountryDetails(
countryDetail.getAlpha2Code(),
countryDetail.getAlpha3Code(),
countryDetail.getName())
);
}
The code which loads the ComboBox and displays the elements in the Labels is as follows:
cbCountryList.setCellFactory(new Callback<ListView<CountryDetails>, ListCell<CountryDetails>>() {
#Override public ListCell<CountryDetails> call(ListView<CountryDetails> p) {
return new ListCell<CountryDetails>() {
#Override
protected void updateItem(CountryDetails item, boolean empty) {
super.updateItem(item, empty);
if (empty || (item == null) || (item.getName() == null)) {
setText(null);
} else {
setText(item.getName());
}
}
};
}
});
public void comboAction(ActionEvent event) {
lblAlpha2Code.setText(cbCountryList.getValue().getAlpha2Code());
lblAlpha3Code.setText(cbCountryList.getValue().getAlpha3Code());
lblCountryName.setText(cbCountryList.getValue().getName());
}
Below is the image of the app:
The problem I am having is that the ComboBox is not displaying the selected item and I cannot figure out how to correct this.
You need to set a StringConverter for your cbCountryList.
cbCountryList.setConverter(new StringConverter<CountryDetails>() {
#Override
public String toString(CountryDetails object) {
return object.getName();
}
#Override
public CountryDetails fromString(String string) {
return null;
}
});
The All of this works fine (although there is probably a much better way of doing this).
You may consider updating the following things,
Asynchronous call for HTTP request and load items
You can cache your fetched-country list as you're calling every time when the button gets triggered. You can make a Singleton object for GetCountries.
Modified GetCountries class,
It caches the countries list and uses the cached data for multiple requests,
public static class GetCountries {
private static final String API_URL = "https://restcountries.eu/rest/v2/all";
private static CountryDetails[] countryDetails;
public static CountryDetails[] getDetails() {
//uses cached countryDetails once it gets loaded
if (countryDetails != null) {
return countryDetails;
}
StringBuilder jsonString = new StringBuilder();
HttpURLConnection urlConnection;
try {
URL urlObject = new URL(API_URL);
urlConnection = (HttpURLConnection) urlObject.openConnection();
urlConnection.setRequestMethod(HttpMethod.GET.name());
String inputLine = "";
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
while ((inputLine = bufferedReader.readLine()) != null) {
jsonString.append(inputLine);
}
urlConnection.getInputStream().close();
} catch (IOException ioe) {
System.out.println(ioe.getMessage());
}
Countries[] countries = new Gson().fromJson(jsonString.toString(), Countries[].class);
countryDetails = new CountryDetails[countries.length];
for (int i = 0; i < countries.length; i++) {
countryDetails[i] = new CountryDetails(
countries[i].getAlpha2Code(),
countries[i].getAlpha3Code(),
countries[i].getName()
);
}
return countryDetails;
}
}
Use Task to fetch your countries asynchronously,
Task<CountryDetails[]> fetchCountryTask = new Task<CountryDetails[]>() {
#Override
protected CountryDetails[] call() throws Exception {
return GetCountries.getDetails();
}
};
fetchButton.setOnAction(event -> new Thread(fetchCountryTask).start());
fetchCountryTask.setOnRunning(event -> cbCountryList.setDisable(true));
fetchCountryTask.setOnSucceeded(e -> {
cbCountryList.getItems().addAll(fetchCountryTask.getValue());
cbCountryList.setDisable(false);
});

Android - Error when storing parsed xml data to sql

I am getting a java.lang.NullPointerException error when storing xml data parsed from a URL on my localhost (http://10.0.0.22/cardealers.xml) to sql. Here is the xml am parsing:
<Providers>
<CarDealer name="BEFORWARD" id="1">
<CarMake name="Toyota" id="20">
<CarModel name="Belta" id="21"/>
<CarModel name="RunX" id="22"/>
<CarModel name="Corolla" id="23"/>
</CarMake>
<CarMake name="Nissan" id="30">
<CarModel name="Murano" id="31"/>
<CarModel name="Pathfinder" id="32"/>
<CarModel name="Navara" id="33"/>
</CarMake>
</CarDealer>
</Providers>
In my xml handler class, I passed my xml like so:
public class SAXXMLHandler extends DefaultHandler {
private List<CarMake> carMaker;
private String tempVal;
// to maintain context
private CarMake carmake;
public SAXXMLHandler() {
carMaker = new ArrayList<CarMake>();
}
public List<CarMake> getCarMake() {
return carMaker;
}
// Event Handlers
public void startElement(String uri, String localName, String qName,
Attributes attributes) throws SAXException {
// reset
tempVal = "";
if (qName.equalsIgnoreCase("CarMake")) {
// create a new instance of CarMake
carmake = new CarMake();
carmake.setName(attributes.getValue("name"));
}
}
public void characters(char[] ch, int start, int length)
throws SAXException {
tempVal = new String(ch, start, length);
}
public void endElement(String uri, String localName, String qName)
throws SAXException {
if (qName.equalsIgnoreCase("CarMake")) {
// add it to the list
carMaker.add(carmake);
} else if (qName.equalsIgnoreCase("CarModel")) {
carmake.setCarModel(tempVal);
}
}
}
Then using AsyncTask in Sell.java
public class Sell extends Activity implements
View.OnClickListener, AdapterView.OnItemClickListener {
static final String URL = "http://10.0.0.22/cardealers.xml";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sell);
//new GetXMLTask().execute();
new GetXMLTask(this).execute();
}
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
}
#Override
public void onClick(View view) {
GetXMLTask task = new GetXMLTask(this);
task.execute(new String[]{URL});
}
//private inner class extending AsyncTask
private class GetXMLTask extends AsyncTask<String, Void, List<Service>> {
private Activity context;
public GetXMLTask(Activity context) {
this.context = context;
}
/* uses HttpURLConnection to make Http request from Android to download
the XML file */
private String getXmlFromUrl(String urlString) {
StringBuffer output = new StringBuffer("");
try {
InputStream stream = null;
URL url = new URL(urlString);
URLConnection connection = url.openConnection();
HttpURLConnection httpConnection = (HttpURLConnection) connection;
httpConnection.setRequestMethod("GET");
httpConnection.connect();
if (httpConnection.getResponseCode() == HttpURLConnection.HTTP_OK) {
stream = httpConnection.getInputStream();
BufferedReader buffer = new BufferedReader(
new InputStreamReader(stream));
String s = "";
while ((s = buffer.readLine()) != null)
output.append(s);
}
} catch (Exception ex) {
ex.printStackTrace();
}
return output.toString();
}
#Override
protected List<CarMake> doInBackground(String... urls) {
List<CarMake> carMaker = null;
String xml = null;
for (String url : urls) {
xml = getXmlFromUrl(url);
InputStream stream = new ByteArrayInputStream(xml.getBytes());
carMaker = SAXXMLParser.parse(stream);
}
// stream.close();
return carMaker;
}
#Override
protected void onPostExecute(List<CarMake> carMaker) {
if (carMaker==null){
Toast.makeText(Sell.this, "carMaker is empty..", Toast.LENGTH_LONG).show();
} else {
E_VodaDB myE_Voda = new E_VodaDB(this.context);
myE_Voda.InsertData(carMaker);
}
}
}
}
As can be seen, my doInBackground() returns a result, carMaker. Then in my OnPostExecute(), I am passing the carMaker arraylist to my databases class to insert in db.
// Adding new service
public void InsertData(List<CarMake> carMaker) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(CARMAKE_NAME, carMaker.get(0).getCarMake()); // CarMake Names
// Inserting Row
db.insert(TABLE_CARDEALER, null, values);
db.close(); // Closing database connection
}
}
I get the following error when I run the app in Android Studio:
java.lang.NullPointerException: Attempt to invoke virtual method 'android.database.sqlite.SQLiteDatabase android.content.Context.openOrCreateDatabase(java.lang.String, int, android.database.sqlite.SQLiteDatabase$CursorFactory, android.database.DatabaseErrorHandler)' on a null object reference
Pointing to my Sell.java in my onPostExecute(). It seems the carMaker arraylist returned from doInBackground() is empty or it is in a different data type that cannot be directly stored into db. How would I go about fixing this error? Please note am a newbie to android
on doInBackground() you create arraylist but forget to initialize. try this.
#Override
protected List<CarMake> doInBackground(String... urls) {
List<CarMake> carMaker = new ArrayList<CarMake>();
String xml = null;
for (String url : urls) {
xml = getXmlFromUrl(url);
InputStream stream = new ByteArrayInputStream(xml.getBytes());
carMaker = SAXXMLParser.parse(stream);
}
// stream.close();
return carMaker;
}
you pass the null instance of current class context in this:
#Override
protected void onPostExecute(List<CarMake> carMaker) {
//E_DB myE_db = new E_DB(null);// replace this to
E_DB myE_db = new E_DB(this);
myE_db.InsertData(carMaker);
}
}
Happy coding!!

Error in application android to fetch data in the database postgreSQL by WebServices with Ksoap2

First made a WebService Using axis2, which has a connection class with the database, and the class with pedidosDAO with CRUD. Using SoupUI can perform the call of methods. So far so good, I created an android app to consume these services, however this giving error when showing the data of the bank in a ListView, when I run appears (unfortunately XsaladaTeste has stopped), I had already done before and had worked but now I have been going on since time I'm not getting my logcat this buggy and not showing this log. What am I doing wrong?
PedidosXsaladaBusca.java
package com.example.xsaladateste;
public class PedidosXsaladaBusca {
private int id_pedidos;
private String informacao_adicionais;
private int mesa;
private String nome_sobrenome_cliente;
private String nome_xsalada;
private double total_a_pagar;
PedidosXsaladaBusca() {
}
PedidosXsaladaBusca(int id_pedidos, String informacao_adicionais, int mesa, String nome_sobrenome_cliente,
String nome_xsalada, double total_a_pagar) {
this.id_pedidos = id_pedidos;
this.informacao_adicionais = informacao_adicionais;
this.mesa = mesa;
this.nome_sobrenome_cliente = nome_sobrenome_cliente;
this.nome_xsalada = nome_xsalada;
this.total_a_pagar = total_a_pagar;
}
public int getId_pedidos() {
return id_pedidos;
}
public void setId_pedidos(int id_pedidos) {
this.id_pedidos = id_pedidos;
}
public String getNome_sobrenome_cliente() {
return nome_sobrenome_cliente;
}
public void setNome_sobrenome_cliente(String nome_sobrenome_cliente) {
this.nome_sobrenome_cliente = nome_sobrenome_cliente;
}
public int getMesa() {
return mesa;
}
public void setMesa(int mesa) {
this.mesa = mesa;
}
public String getInformacao_adicionais() {
return informacao_adicionais;
}
public void setInformacao_adicionais(String informacao_adicionais) {
this.informacao_adicionais = informacao_adicionais;
}
public double getTotal_a_pagar() {
return total_a_pagar;
}
public void setTotal_a_pagar(double total_a_pagar) {
this.total_a_pagar = total_a_pagar;
}
public String getNome_xsalada() {
return nome_xsalada;
}
public void setNome_xsalada(String nome_xsalada) {
this.nome_xsalada = nome_xsalada;
}
#Override
public String toString() {
return "PedidosXsaladaBusca [id_pedidos=" + id_pedidos + ", informacao_adicionais=" + informacao_adicionais
+ ", mesa=" + mesa + ", nome_sobrenome_cliente=" + nome_sobrenome_cliente + ", nome_xsalada="
+ nome_xsalada + ", total_a_pagar=" + total_a_pagar + "]";
}
}
PedidosDAO.java
public class PedidosDAO {
// Setando Caminhos
private static final String URL = "http://192.168.0.1:8080/BancoParaXsalada/services/PedidosDAO?wsdl";
private static final String nameSpace = "http://xsalada.com.br";
// referencias ao metodos no SoapUI XML file
private static final String BUSCAR = "buscarTodos";
// metodo inserir no banco pelo android usando biblioteca Ksoap2
public ArrayList<PedidosXsaladaBusca> buscarTodos() {
ArrayList<PedidosXsaladaBusca> lista = new ArrayList<PedidosXsaladaBusca>();
SoapObject buscarTodos = new SoapObject(nameSpace, BUSCAR);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.setOutputSoapObject(buscarTodos);
envelope.implicitTypes = true;
HttpTransportSE http = new HttpTransportSE(URL);
try {
http.call("urn:" + BUSCAR, envelope);
Vector<SoapObject> resposta = (Vector<SoapObject>) envelope.getResponse();
for (SoapObject soapObject : resposta) {
PedidosXsaladaBusca user = new PedidosXsaladaBusca();
user.setId_pedidos(Integer.parseInt(soapObject.getProperty("id_pedidos").toString()));
user.setInformacao_adicionais(soapObject.getProperty("informacao_adicionais").toString());
user.setMesa(Integer.parseInt(soapObject.getProperty("mesa").toString()));
user.setNome_sobrenome_cliente(soapObject.getProperty("nome_sobrenome_cliente").toString());
user.setNome_xsalada(soapObject.getProperty("nome_xsalada").toString());
user.setTotal_a_pagar(Double.parseDouble(soapObject.getProperty("total_a_pagar").toString()));
lista.add(user);
}
} catch (Exception e) {
e.printStackTrace();
return null;
}
return lista;
}
}
MainActivity.java
public class MainActivity extends Activity {
public ListView listaUsuario = (ListView) findViewById(R.id.listaPedidos);
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
PedidosDAO dao = new PedidosDAO();
ArrayList<PedidosXsaladaBusca> lista = dao.buscarTodos();
ArrayAdapter<PedidosXsaladaBusca> adpUser = new ArrayAdapter<PedidosXsaladaBusca>(this,
android.R.layout.simple_list_item_1, lista);
listaUsuario.setAdapter(adpUser);
}
Resolved, it was not code error I realized he was giving the following error: [timestamp - DDMs] Can not bind to site 8600 is debugger
then researched and solve. below is the link I found to resolve the error:
Eclipse DDMS error "Can't bind to local 8600 for debugger"

How do I combine two separate parsed jsonObjects into a single arraylist?

I would like to combine two separate parsed jsonObjects into a single arraylist, then display the results as Strings?
I would like to store summaryJsonObject & segment in storylineData. When I step through the code using the debugger summaryJsonObject & segment both hold the raw json. The raw json data also shows in the logcat but storylineData remains null & unavailable throughout.
Here is the parsing code.
public class StorylineData {
private static String date;
private ArrayList<SummaryData> summary;
private ArrayList<SegmentData> segments;
private String caloriesIdle;
private String lastUpdate;
public String getDate() {
return date;
}
public ArrayList<SummaryData> getSummary() {
return summary;
}
public ArrayList<SegmentData> getSegments() {
return segments;
}
public String getCaloriesIdle() {
return caloriesIdle;
}
public String getLastUpdate() {
return lastUpdate;
}
public void setDate(String date) {
this.date = date;
}
public void setSummary(ArrayList<SummaryData> summary) {
this.summary = summary;
}
public void setSegments(ArrayList<SegmentData> segments) {
this.segments = segments;
}
public void setCaloriesIdle(String caloriesIdle) {
this.caloriesIdle = caloriesIdle;
}
public void setLastUpdate(String lastUpdate) {
this.lastUpdate = lastUpdate;
}
public static StorylineData parse(JSONObject jsonObject) {
if (jsonObject != null) {
StorylineData storylineData = new StorylineData();
storylineData.date = jsonObject.optString("date");
storylineData.caloriesIdle = jsonObject.optString("caloriesIdle");
storylineData.lastUpdate = jsonObject.optString("lastUpdate");
storylineData.summary = new ArrayList<SummaryData>();
storylineData.segments = new ArrayList<SegmentData>();
JSONArray summariesJsonArray= jsonObject.optJSONArray("summary");
if (summariesJsonArray != null) {
for (int i = 0; i < summariesJsonArray.length(); i++) {
JSONObject summaryJsonObject = summariesJsonArray.optJSONObject(i);
if (summaryJsonObject != null) {
storylineData.summary.add(SummaryData.parse(summaryJsonObject));
Log.d("storylineHandler", summaryJsonObject.toString());
}
}
}
JSONArray segmentsJsonArray = jsonObject.optJSONArray("segments");
if (segmentsJsonArray != null) {
for (int i = 0; i < segmentsJsonArray.length(); i++) {
JSONObject segment = segmentsJsonArray.optJSONObject(i);
if (segment != null) {
storylineData.segments.add(SegmentData.parse(segment));
Log.d("storylineHandler", segment.toString());
}
}
}
return storylineData;
}
return null;
}
}
The MainActivity looks like this:
MainActivity
public class MainActivity extends FragmentActivity implements OnClickListener{
..other variables here..
List<StorylineData> storylineData;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
...other ui elements here...
mEditTextResponse = (TextView) findViewById(R.id.editResponse);
storylineData = new StorylineData();
MovesAPI.init(this, CLIENT_ID, CLIENT_SECRET, CLIENT_SCOPES.....
#Override
public void onClick(View v) {
toggleProgress(true);
switch (mSpinnerAPI.getSelectedItemPosition()) {
... other cases here...
break;
...other cases here...
case 4: // Get Summary Day
MovesAPI.getSummary_SingleDay(summaryHandler, "20150418", null);//Date changed to "20150117"
break;
Other cases here..
case 10: // Get Storyline Day
MovesAPI.getStoryline_SingleDay(storylineHandler, "20150418", null, false);//Date changed to "20150418"
break;
...Other cases here..
}
}
... Other MovesHandlers here...
private JSONObject summaryJsonObject;
private List<StorylineData> storylineList;
private JSONObject summariesJsonArray;
private MovesHandler<ArrayList<StorylineData>> storylineHandler = new MovesHandler<ArrayList<StorylineData>>() {
#Override
public void onSuccess(ArrayList<StorylineData> result) {
toggleProgress(false);
storylineList = (List<StorylineData>) StorylineData.parse(summaryJsonObject);
updateResponse( + storylineData.toString() + "\n" //displays true to layout view
result.add(StorylineData.parse(summariesJsonArray))+ "\n"
+Log.d("call result", result.toString()) + "\n" //displays 60 in layout view & com.protogeo.moves.demos.apps.storyline.StorylineData#52824f88, null]
+ Log.d("Log.d storylineHandler", storylineHandler.toString()) + "\n" ); //returns 78 in layout view & com.protogeo.moves.demos.apps.Mainactivity#234234 to log cat
onFailure code here..
}
};
public void toggleProgress(final boolean isProgrressing) {
togglePregress code here..
}
public void updateResponse(final String message) {
runOnUiThread(new Runnable() {
public List<StorylineData> storylineList;
#Override
public void run() {
mEditTextResponse.setText(message);
if (storylineData!= null) {
for (StorylineData storylineData : storylineList) {
mEditTextResponse.append(("storylineData" + storylineData.toString()));
}
}
}
});
}
}
HttpClass
public static void getDailyStorylineList(final MovesHandler<JSONArray> handler,
final String specificSummary,
final String from,
final String to,
final String pastDays,
final String updatedSince,
final boolean needTrackPoints) {
new Thread(new Runnable() {
#Override
public void run() {
try {
/* Refresh access token if only AuthData.MOVES_REFRESHBEFORE days are there to expire current token */
AuthData.refreshAccessTokenIfNeeded();
/* Exchange the authorization code we obtained after login to get access token */
HashMap<String, String> nameValuePairs = new HashMap<String, String>();
nameValuePairs.put("access_token", AuthData.getAuthData().getAccessToken());
// if (specificSummary != null && specificSummary.length() > 0) nameValuePairs.put("specificSummary", specificSummary);//att
if (from != null && from.length() > 0) nameValuePairs.put("from", from);
if (to != null && to.length() > 0) nameValuePairs.put("to", to);
if (pastDays != null && pastDays.length() > 0) nameValuePairs.put("pastDays", pastDays);
if (updatedSince != null && updatedSince.length() > 0) nameValuePairs.put("updatedSince", updatedSince);
if (needTrackPoints) nameValuePairs.put("trackPoints", "true");
URL url = new URL(MovesAPI.API_BASE + MovesAPI.API_PATH_STORYLINE + (specificSummary != null ? specificSummary : "") + "?" + Utilities.encodeUrl(nameValuePairs));
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setDoInput(true);
urlConnection.connect();
if (urlConnection.getResponseCode() != 200) {
/* All other HTTP errors from Moves will fall here */
handler.onFailure(getErrorStatus(Utilities.readStream(urlConnection.getErrorStream()), urlConnection.getResponseCode()), "Server not responded with success ("+ urlConnection.getResponseCode() +")");
return;
}
String response = Utilities.readStream(urlConnection.getInputStream());
Object object = new JSONTokener(response).nextValue();
if (object instanceof JSONArray) {
JSONArray jsonArray = (JSONArray) object;
ArrayList<StorylineData> storylineData = new ArrayList<StorylineData>();
if (jsonArray != null) {
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject storylineJsonObject = jsonArray.optJSONObject(i);
if (storylineJsonObject != null) {
storylineData.add(StorylineData.parse(storylineJsonObject));
}
}
}
handler.onSuccess(storylineData);
} else {
handler.onFailure(MovesStatus.INVALID_RESPONSE, "Expected a JSONArray from server, but failed");
}
} catch (Exception ex) {
ex.printStackTrace();
handler.onFailure(MovesStatus.UNEXPECTED_ERROR, "An unexpected error occured, please check logcat");
}
}
}).start();
}
MovesHandler
public interface MovesHandler<T> {//T stands for generic type
/**
* Implement this method to get success notifications along with the result
* #param result : Result of the operation completed with this handler
*/
public void onSuccess(ProfileData result);
/**
* Implement this method to get failure notifications along with the {#link MovesStatus} code and a brief message
* #param status : Status code of the failure
* #param message : A brief message about the reason behind failure
*/
public void onFailure(MovesStatus status, String message);
}
If you wanted to have one ArrayList to store both SummaryData and SegmentData, you could just created an ArrayList of Objects, ArrayList<Object>. This would be the more general solution.
The alternative would be having SummaryData and SegmentData inherit the same class or implement the same interface.
Using an extended class, you could have:
class Data {
}
class SegmentData extends Data {
}
class SummaryData extends Data {
}
You could then have an ArrayList that would be able to add both SegmentData and SummaryData objects.
If you wanted to show each item as a String you would need to loop through the list and call the toString() function of each item
ArrayList<Data> dataList;
for (Data d : dataList) {
Log.d("data", d.toString())
}
Just make sure to overwrite the toString() function in SegmentData and SummaryData
EDIT: Showing how to print JsonArray
If you wanted to just print for JsonArrays, you could:
public class StorylineData {
private static String date;
private JSONArray summary;
private JSONArray segments;
private String caloriesIdle;
private String lastUpdate;
public String getDate() {
return date;
}
public JSONArray getSummary() {
return summary;
}
public JSONArray getSegments() {
return segments;
}
public String getCaloriesIdle() {
return caloriesIdle;
}
public String getLastUpdate() {
return lastUpdate;
}
public void setDate(String date) {
this.date = date;
}
public void setSummary(JSONArray summary) {
this.summary = summary;
}
public void setSegments(JSONArray segments) {
this.segments = segments;
}
public void setCaloriesIdle(String caloriesIdle) {
this.caloriesIdle = caloriesIdle;
}
public void setLastUpdate(String lastUpdate) {
this.lastUpdate = lastUpdate;
}
public static StorylineData parse(JSONObject jsonObject) {
if (jsonObject != null) {
StorylineData storylineData = new StorylineData();
storylineData.date = jsonObject.optString("date");
storylineData.caloriesIdle = jsonObject.optString("caloriesIdle");
storylineData.lastUpdate = jsonObject.optString("lastUpdate");
storylineData.summary = jsonObject.optJSONArray("summary");
storylineData.segments = jsonObject.optJSONArray("segments");
return storylineData;
}
return null;
}
#Override
public String toString() {
JSONArray combined = new JSONArray(summary);
combined.put(segment);
return combined.toString();
}
}
In your MainActivity
private StorylineData storylineData;
private MovesHandler<JSONArray> storylineHandler = new MovesHandler<JSONArray>() {
#Override
public void onSuccess(JSONArray result) {
toggleProgress(false);
storylineData = StorylineData.parse(summaryJsonObject);
updateResponse(storylineData.toString()) //displays true to layout view
result.add(storylineData.getSummary());
Log.d("call result", result.toString());
Log.d("Log.d storylineHandler", storylineHandler.toString());
}
};

Smack messaging client other than Chat Text

client1 can send txt message to client2 using
connection.getChatManager().createChat(to, this).sendMessage(message);
How to send other kind of message: like INFO message ? (client1 to client2) ?
Because I want, INFO message should not be displayed in the chat window....is it possible ? using smack, smackx library.
Many Thanks.
What you want do do here is to add an extension to your text message. Here is a rough guide.
Chat chat = connection.getChatManager().createChat(to, this);
Message message = new Message(to, Message.Type.chat);
message.setBody("hello");
message.setProperty(prop0, val0);
message.setProperty(prop1, val1);
chat.sendMessage(message)
The properties are carried in a separate namespace (use toXML() to look at it) and will not appear in the chat window. On the 'other side', the applications uses getProperty() to retrieve the value.
If you do not want key/value pairs, but structured data, use addExtension() in the message body. This is a little more complicated because you basically have to extend PacketExtension, provide your own namespace. You might even have to write a PacketExtensionProvider.
Here is the example for message extension.
The basic XML structure of the XMPP protocol is:
<message
from='sender_jid'
to='receiver_jid'
type='message_type'>
<body> content </body>
</message>
The process of sending messages:
//build chat
Chat chat = chatManager.createChat("jid");
//build extension
UserInfo4XMPP userInfo4XMPP = new UserInfo4XMPP();
userInfo4XMPP.setNameText("userx");
userInfo4XMPP.setUrlText("http://www.liaoku.org/");
//build message
Message message = new Message();
message.setBody("hello");
message.addExtension(userInfo4XMPP);// add the extension
//send
chat.sendMessage(message);
The UserInfo4XMPP is defined as:
import org.jivesoftware.smack.packet.ExtensionElement;
public class UserInfo4XMPP implements ExtensionElement{
private String elementName = "userinfo";
private String nameElement = "name";
private String urlElement = "url";
private String nameText = "";
private String urlText = "";
#Override
public String getElementName() {
return elementName;
}
#Override
public CharSequence toXML() {
StringBuilder sb = new StringBuilder();
sb.append("<");
sb.append(elementName);
sb.append(">");
sb.append("<");
sb.append(nameElement);
sb.append(">");
sb.append(nameText);
sb.append("</");
sb.append(nameElement);
sb.append(">");
sb.append("<");
sb.append(urlElement);
sb.append(">");
sb.append(urlText);
sb.append("</");
sb.append(urlElement);
sb.append(">");
sb.append("</");
sb.append(elementName);
sb.append(">");
return sb.toString();
}
#Override
public String getNamespace() {
return "";
}
public String getNameText() {
return nameText;
}
public void setNameText(String nameText) {
this.nameText = nameText;
}
public String getUrlText() {
return urlText;
}
public void setUrlText(String urlText) {
this.urlText = urlText;
}
}
A more complicated example of message extention:
Message videoMsg = new Message();
VideoChatRTP videoXml = new VideoChatRTP();
videoXml.setVideoType(VideoMediaType.REQUEST);
videoXml.setAddress(address);
videoMsg.setTo(receive);
videoMsg.addExtension(videoXml);
XMPPConnection conn = BaseService.getInstance().getConnection();
conn.sendPacket(videoMsg);
The extension class VideoChatRIP must implement PacketExtension:
public class VideoChatRTP implements PacketExtension {
private VideoMediaType videoType;
private String address;
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public VideoMediaType getVideoType() {
return videoType;
}
public void setVideoType(VideoMediaType videoType) {
this.videoType = videoType;
}
public static final String NAME = "jingle";
public static final String NAME_SPACE = "com:roger:video";
public VideoChatRTP() {
super();
}
#Override
public String getElementName() {
return NAME;
}
#Override
public String getNamespace() {
return NAME_SPACE;
}
#Override
public String toXML() {
StringBuffer sb = new StringBuffer();
sb.append("<jingle").append(" xmlns=\"").append(NAME_SPACE).append(
"\">");
sb.append("<type>").append(videoType).append("</type>");
sb.append("<ipAddress>").append(address).append("</ipAddress>");
sb.append("</jingle>");
return sb.toString();
}
}
The Listener:
ProviderManager.getInstance().addExtensionProvider(VideoChatRTP.NAME, VideoChatRTP.NAME_SPACE, new VideoChatReceive());
Processing:
public class VideoChatReceive implements PacketExtensionProvider {
#Override
public PacketExtension parseExtension(XmlPullParser parser)
throws Exception {
boolean done = false;
String requestType = "asdasd";
String ipAddress = "asdasd";
while (!done) {
int eventType = parser.next();
String name = parser.getName();
if (eventType == XmlPullParser.START_TAG) {
if (name.equals("type")) {
requestType = parser.nextText();
}
if (name.equals("ipAddress")) {
ipAddress = parser.nextText();
}
}
if (eventType == XmlPullParser.END_TAG) {
if (name.equals("jingle")) {
done = true;
}
}
}
VideoChatRTP videoRtp = new VideoChatRTP();
videoRtp.setVideoType(VideoMediaType.valueOf(requestType));
videoRtp.setAddress(ipAddress);
return videoRtp;
}
}

Categories