I have a problem : I use a web service to return some values , but some times some problems face the web services , and when I want to display them my app crashes , so I want to make sure that if there is nothing to show then return just empty space , and I use it on JSON , there is a part of my code if someone can help me ,
public static Article parseArticle(JSONObject jsonArticle) {
Article article = new Article();
try {
article.setTitle(ArabicUtilities.reshape(Html.fromHtml(jsonArticle.getString("title")).toString()));
article.setExcerpt(ArabicUtilities.reshape(Html.fromHtml(jsonArticle.getString("excerpt")).toString()));
article.setContent(ArabicUtilities.reshape(Html.fromHtml(jsonArticle.getString("content")).toString()));
article.setDate(jsonArticle.getString("date"));
return article;
} catch (JSONException e) {
e.printStackTrace();
return null;
}
}
private void loadinfo() {
{
programs = JSONParser.parseProgram(savedData);
txt1.setText(article.get(1).getTitle());
txt2.setText(article.get(0).getTitle());
txt3.setText(article.get(1).excerpt());
txt4.setText(article.get(0).excerpt());
txt5.setText(article.get(1).content());
txt6.setText(article.get(0).content());
txt7.setText(article.get(1).date());
txt8.setText(article.get(0).date());
}
this is what happened when i try to have information it give error on
txt1.setText(article.get(1).getTitle());
that there is no values
If I have not misunderstood you instead of jsonArticle.getString you can use jsonArticle.optString. It will return an empty String if the json does not contain that key.
String mString = jsonArticle.optString("title");
article.setTitle(ArabicUtilities.reshape(Html.fromHtml(mString).toString()));
mString = jsonArticle.optString("excerpt");
article.setExcerpt(ArabicUtilities.reshape(Html.fromHtml(mString).toString()));
mString = jsonArticle.optString("content");
article.setContent(ArabicUtilities.reshape(Html.fromHtml(mString).toString()));
mString = jsonArticle.optString("date");
article.setDate(mString);
here the doc for optString()
EDIT
public static Article parseArticle(JSONObject jsonArticle) {
Article article = new Article();
try {
String mString = jsonArticle.optString("title");
article.setTitle(ArabicUtilities.reshape(Html.fromHtml(mString).toString()));
mString = jsonArticle.optString("excerpt");
article.setExcerpt(ArabicUtilities.reshape(Html.fromHtml(mString).toString()));
mString = jsonArticle.optString("content");
article.setContent(ArabicUtilities.reshape(Html.fromHtml(mString).toString()));
mString = jsonArticle.optString("date");
article.setDate(mString);
} catch (JSONException e) {
e.printStackTrace();
}
return article;
}
public static Article parseArticle(JSONObject jsonArticle) {
Article article = new Article();
if(null!=jsonArticle){
try {
/*your code */
}else{
article.setTitle(ArabicUtilities.reshape("");
article.setExcerpt(ArabicUtilities.reshape("");
article.setContent(ArabicUtilities.reshape("");
article.setDate("");
return article;
}
}
Related
Why is it not possible to loop a call execute to get multiple responses inside my IntentService via Retrofit?
Please see my code:
public class UpdateAgendaService extends IntentService {
public static final int STATUS_RUNNING = 0;
public static final int STATUS_FINISHED = 1;
public static final int STATUS_ERROR = 2;
private Agenda agenda;
public UpdateAgendaService() {
super(UpdateAgendaService.class.getName());
}
#Override
protected void onHandleIntent(Intent intent) {
final ResultReceiver receiver = intent.getParcelableExtra("receiver");
String[] dateWeek = intent.getStringArrayExtra("dateWeek");
if (dateWeek != null) {
receiver.send(STATUS_RUNNING, Bundle.EMPTY);
Bundle bundle = new Bundle();
try {
//Why is this not possible?
List<Agenda> agendaList = getAgendaList(dateWeek);
receiver.send(STATUS_FINISHED, bundle);
}
} catch (Exception e) {
/* Sending error message back to activity */
bundle.putString(Intent.EXTRA_TEXT, e.toString());
receiver.send(STATUS_ERROR, bundle);
}
}
Log.d(Utilities.TAG, "Service Stopping!");
this.stopSelf();
}
private List<Agenda> getAgendaList(String[] upcomingWeekdates){
List<Agenda> agendaList = null;
for (int i = 0; i < upcomingWeekdates.length; i++) {
String weekDay = upcomingWeekdates[i];
agendaList.add(getAgenda(weekDay));
}
return agendaList;
}
private Agenda getAgenda(String date) {
Agenda agenda = null;
ApiService apiService = new QardioApi().getApiService();
Call<Agenda> call = apiService.getAgenda(date);
try {
agenda = call.execute().body();
} catch (IOException e) {
e.printStackTrace();
}
return agenda;
}
}
So the situation is that I have an API which has a url: http//:myapi.com/[date] which when called via retrofit gives me a JSON response of the Agenda(Events) for that specific day. What I want to do is to show the agenda(events) for the upcoming week, that is why I did it via loop given a String array of dates for the upcoming week. Imagine kind of like the Eventbrite app.
What I am doing wrong? I read somewhere that I should do this via JobQueue/Eventbus, should I be doing that? But I am a bit hesitant because I don't want to be using any more third party libraries. However, if that is the last case scenario I will probably just go with that then.
Nevermind guys. That was because of a very stupid mistake i made.
I just changed:
List<Agenda> agendaList = null;
to
List<Agenda> agendaList = new ArrayList<>();
I have list of web pages(over 100) with I have to vistit and collect data from.
I decided to save the html from all of them to one file, and then use Jsoup to find the interesting data.
But problem is to I do not know how to run 100 threads, and save the responses into one file, any ideas?
maybe it's not a masterpiece, but it works, and I wanted to make it as simple as possible.
ArrayList<String> links = new ArrayList<>();
Elements myDiv;
private void saveDetails() throws IOException {
if(repeat < links.size()){
repeat++;
textView.setText(String.valueOf(repeat));
saveFile(myDiv.toString());
myDiv = null;
getDetails(links.get(repeat));
}else {
textView.setText("finished");
}
}
private void getDetails(String urlStr) {
final String detailsUrl = urlStr;
new Thread() {
#Override
public void run() {
Message msg = Message.obtain();
try {
Document doc = Jsoup.connect(detailsUrl).get();
myDiv = doc.select(".exhibitor-contact");
} catch (IOException e1) {
e1.printStackTrace();
}
detailsHandler.sendMessage(msg);
}
}.start();
}
private Handler detailsHandler = new Handler() {
public void handleMessage(Message msg) {
super.handleMessage(msg);
try {
saveDetails();
} catch (IOException e) {
e.printStackTrace();
}
}
};
You don't need to save all of them in a file and then process them. You can gather information one by one. It is my suggestion:
arrayList urls = {100 site-url}; //in correct syntax
Document doc = null;
for (String url : urls) {
doc = Jsoup.connect(url).get();
//now proccess doc.toString as you want(in regular expression for example)
//save your desired information
}
I am working on android application. In my app I got the xml data response from server and stored it in a string. Now I need to get each value of that xml and display in a dropdown. How can I do that. Please help me with this. Will be really thankful.
My xml data:
<?xml version="1.0" encoding="utf-8"?>
<root>
<status>first<status>
<description>very good</description>
<Firstnames>
<name>CoderzHeaven</name>
<name>Android</name>
<name>iphone</name>
</Firstnames>
<SecondNames>
<name>Google</name>
<name>Android</name>
</SecondNames>
</root>
I am getting the above mentioned xml data from server. Now I need to display that in listview. How can I get those values using xmlparser. I tried with different examples but it didnt work for me.
You will need to create an extra class and parametrize your adapter with objects of this class, an example data model would look like:
public class DataClass {
private String status, description;
private ArrayList<String> fnames, lnames;
public DataClass() {
fnames = new ArrayList<String>();
lnames = new ArrayList<String>();
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public ArrayList<String> getFnames() {
return fnames;
}
public ArrayList<String> getLnames() {
return lnames;
}
}
As for the XML parser, there are literally tons of examples, you're definitely in advantage if you can use search. Just to give you a staring point, tutorials one, two, three, four.
If you experience problems, post your efforts and the code that didn't work, what have you tried and so on. Then you'll get help, otherwise nobody on SO is going to write code for you. https://stackoverflow.com/help/how-to-ask
Here's how you can do it if the xml is inside of your apps assets folder.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
InputStream input = null;
try {
input = getApplicationContext().getAssets().open("data.xml");
} catch (IOException e) {
e.printStackTrace();
}
DocumentBuilder builder = null;
try {
builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
} catch (ParserConfigurationException e) {
e.printStackTrace();
}
Document doc = null;
if (builder == null) {
Log.e("TAG", "Builder is empty.");
return;
}
try {
doc = builder.parse(input);
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
if (doc == null) {
Log.e("TAG", "Document is empty.");
return;
}
// Get Firstnames element
Element firstNames = (Element) doc.getElementsByTagName("Firstnames").item(0);
// Get name nodes from Firstnames
NodeList nameNodes = firstNames.getElementsByTagName("name");
// Get count of names inside of Firstnames
int cChildren = nameNodes.getLength();
List<String> names = new ArrayList<String>(cChildren);
for (int i=0; i<cChildren; i++) {
names.add(nameNodes.item(i).getTextContent());
Log.d("TAG","Name: "+names.get(i));
}
// Do same with SecondNames
}
Android provides the developer to declare the permission before an app can uses tools or hardware, I have created a class to store each permission's description like the permission name, nice name , description like what that permission does. Now is there anyway i can initialize each object programmatically, getting the information from http://developer.android.com/reference/android/Manifest.permission.html.
The code for the class is
package org.owasp.seraphimdroid.customclasses;
public class PermissionData {
private String permission;
private String permissionName;
private String description;
private String regularUseDescription;
private String maliciousUseDescription;
private int weight;
public PermissionData(String permission){
this.permission = permission;
setData();
}
private void setData(){
weight = 0;
}
//Getters and setter
public String getPermissionName() {
return permissionName;
}
public void setPermissionName(String permissionName) {
this.permissionName = permissionName;
}
public int getWeight() {
return weight;
}
public void setWeight(int weight) {
this.weight = weight;
}
public String getPermission() {
return permission;
}
public void setPermission(String permission) {
this.permission = permission;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getRegularUseDescription() {
return regularUseDescription;
}
public void setRegularUseDescription(String regularUseDescription) {
this.regularUseDescription = regularUseDescription;
}
public String getMaliciousUseDescription() {
return maliciousUseDescription;
}
public void setMaliciousUseDescription(String maliciousUseDescription) {
this.maliciousUseDescription = maliciousUseDescription;
}
}
Also should i store these objects as hashmap or in database?
These will mostly be used to display information in activity according to the permission.
Use the Context.check* methods (methods from the Context object that start with "check") for checking if a given permission is granted. See an example here.
Please note that permissions cannot be added at runtime.
The simplest ways to store your objects' data that I can think of at the moment are writing them to a database, serializing them into a file, or writing key-value pairs to SharedPreferences. It will depend on what you think is more appropriate. A hashmap has nothing to do with persistence; you may choose it as the approach to keep your data in memory and access it during the app's execution.
Training for Android developers has a section on writing key-value pairs and database persistence. If you wish to use serialization, the methods below might be useful:
private void _serializeObject(Object object, String fileName) {
String aboluteFilePath = getApplicationContext().getFilesDir().getPath() + File.separator + fileName;
try {
FileOutputStream fileOut = new FileOutputStream(absoluteFilePath);
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(object);
out.close();
fileOut.close();
} catch (IOException e) {
Log.e(TAG, "Error while serializing data to " + absoluteFilePath, e);
}
}
private Object _deserializeObject(String fileName) {
Object object = null;
String absoluteFilePath = getApplicationContext().getFilesDir().getPath() + File.separator + fileName;
try {
FileInputStream fileIn = new FileInputStream(absoluteFilePath);
ObjectInputStream in = new ObjectInputStream(fileIn);
object = in.readObject();
in.close();
fileIn.close();
} catch (FileNotFoundException e) {
// You may want to ignore this exception as it will occur the first time the
// data is deserialized unless you make sure serialization occurs before it.
} catch (IOException e) {
Log.e(TAG, IOException.class.getSimpleName() + " while deserializing from " + absoluteFilePath, e);
} catch (ClassNotFoundException e) {
Log.e(TAG, ClassNotFoundException.class.getSimpleName() + " while deserializing from " + absoluteFilePath, e);
}
return object;
}
I am developing a app based on Question and Answers.
I am using res/raw database to fetch the data,
I am planning to have a search option for that ie,
I kept a searchbox at bottom and say i have 100 questions,
The thing i want to do is to goto question no 45. by entering the number in searchbox.
I dont have any idea in working on this.
Please help me to find a solution
protected void loadQuestionset1() throws Exception {
try {
InputStream questionset1 = this.getBaseContext().getResources()
.openRawResource(R.raw.questionset1);
bReader = new BufferedReader(new InputStreamReader(questionset1));
StringBuilder quesString = new StringBuilder();
String aJsonLine = null;
while ((aJsonLine = bReader.readLine()) != null) {
quesString.append(aJsonLine);
}
Log.d(this.getClass().toString(), quesString.toString());
JSONObject quesObj = new JSONObject(quesString.toString());
quesList1 = quesObj.getJSONArray("Questions");
Log.d(this.getClass().getName(),
"Num Questions " + quesList1.length());
}
catch (Exception e){
} finally {
try {
bReader.close();
} catch (Exception e) {
Log.e("", e.getMessage().toString(), e.getCause());
}
}
}
public static JSONArray getQuesList1() {
return quesList1;
}
public ArrayList<NewQuestion> questionList=new ArrayList<NewQuestion>();
Every time you get question from data base
NewQuestion newQuestion=new NewQuestion();
newQuestion.question.put(NewQuestion.QUESTION_TEXT,q);
newQuestion.question.put(NewQuestion.OPTION_1,q);
newQuestion.question.put(NewQuestion.QPTION_2,q);
newQuestion.question.put(NewQuestion.OPTION_3,q);
newQuestion.question.put(NewQuestion.OPTION_4,q);
questionList.add(newQuestion);
public class NewQuestion {
public static List<String> q12=new ArrayList<String>();
public static final String QUESTION_TEXT="questionText";
public static final String OPTION_1="option1";
public static final String OPTION_2="option2";
public static final String OPTION_3="option3";
public static final String OPTION_4="option4";
public static final String CORRECT_ANSWER="answer";
Hashtable question=new Hashtable();
public NewQuestion()
{
question.put(NewQuestion.QUESTION_TEXT,new String());
question.put(NewQuestion.OPTION_1,new String());
question.put(NewQuestion.OPTION_2,new String());
question.put(NewQuestion.OPTION_3,new String());
question.put(NewQuestion.OPTION_4,new String());
question.put(NewQuestion.CORRECT_ANSWER,new String());
}
}
Now your questionList of 0(index 0) will contain data related to question 1. When user types 40, you can access data at 40
newQuestion=(NewQuestion)questionList.get(questionNo);//question no 45
String q=newQuestion.question.get(NewQuestion.QUESTION_TEXT).toString();//get question
String op1=newQuestion.question.get(NewQuestion.OPTION_1).toString();
String op2=newQuestion.question.get(NewQuestion.OPTION_2).toString();
String op3=newQuestion.question.get(NewQuestion.OPTION_3).toString();
String op4=newQuestion.question.get(NewQuestion.OPTION_4).toString();
If you can access questionset at position 45 directly form your raw database no need to use the above. The above procedure is not ideal as arraylist stores all data. As and when the sizes increaes may slow down the operation.
If you a database(sqlite) for storing questions and answers, it will be easier to fetch data from data base usin queries.