Search option in my page - android

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.

Related

Why is it not possible to loop a call execute to get multiple responses inside my IntentService via Retrofit?

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<>();

how to determine if a user is online or not using Layer/Parse

I am developing an Android chat app using Layer and Parse. I have reached a point where i have to indicate if a friend is online or not. I have read the documentations on their websites but i dont find anything related to online presence. Is there a document that i have not seen? Please share some insight on how to know if a user is online when using Layer/Parse.
You just create on column inside User table, isonline, and set that flag true and false base on app open and close.
public static final String CLASSNAME = "userclass";
public static final String USERID = "userid";
public static final String USERNAME = "username";
public static final String USERLASTNAME = "lastname";
public static final String USERONLINE = "isonline";
public static void setOnline(String userId, boolean isOnline)
{
ParseQuery<ParseObject> query = ParseQuery.getQuery(UserDao.CLASSNAME);
query.whereEqualTo(USERID, userId);
List<ParseObject> list = new ArrayList<ParseObject>();
try {
list = query.find();
} catch (ParseException e) {
e.printStackTrace();
}
if(list.size() == 1)
{
ParseObject object = list.get(0);
if (isOnline) object.put(USERONLINE,1);
else object.put(USERONLINE,0);
object.saveInBackground();
}
}

Getting data from xml in android

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
}

return string from null on android

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;
}
}

Parsing large text file efficiency

Due to simplicity i have a text file with entries separated by ; and parses every line into an object. The problem is that the text file contains almost 10 000 rows.
I also need to create keys for each object im parsing so i can filter the results in a search interface.
It takes almost 16 seconds in emulator to parse the text and add the keys. I'm i doing something wrong here? Or is there a more efficient way?
Here is my database singleton:
public class Database {
private static Database instance = null; private final Map<String, List<Stop>> mDict = new ConcurrentHashMap<String, List<Stop>>();
public static Database getInstance() { if (instance == null) { instance = new Database(); } return instance; } public List<Stop> getMatches(String query) {
List<Stop> list = mDict.get(query);
return list == null ? Collections.EMPTY_LIST : list;
}
private boolean mLoaded = false;
/**
* Loads the words and definitions if they haven't been loaded already.
*
* #param resources Used to load the file containing the words and definitions.
*/
public synchronized void ensureLoaded(final Resources resources) {
if (mLoaded) return;
new Thread(new Runnable() {
public void run() {
try {
loadStops(resources);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}).start();
}
private synchronized void loadStops(Resources resources) throws IOException
{
if (mLoaded) return;
Log.d("database", "loading stops");
InputStream inputStream = resources.openRawResource(R.raw.allstops);
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
try {
String line;
while((line = reader.readLine()) != null) {
String[] strings = TextUtils.split(line, ";");
addStop(strings[0], strings[1], strings[2]);
}
} finally {
reader.close();
}
Log.d("database", "loading stops completed");
mLoaded = true;
}
private void addStop(String name, String district, String id) {
Stop stop = new Stop(id, name, district);
int len = name.length();
for (int i = 0; i < len; i++) {
String prefix = name.substring(0, len - i).toLowerCase();
addMatch(prefix, stop);
}
}
private void addMatch(String query, Stop stop) {
List<Stop> matches = mDict.get(query);
if (matches == null) {
matches = new ArrayList<Stop>();
mDict.put(query, matches);
}
matches.add(stop);
}
}
Here is some sample data:
Mosseporten Senter;Norge;9021014089003000;59.445422;10.701055;273
Oslo Bussterminal;Norge;9021014089004000;59.911369;10.759665;273
Långegärde;Strömstad;9021014026420000;58.891462;11.007767;68
Västra bryggan;Strömstad;9021014026421000;58.893080;11.009997;7
Vettnet;Strömstad;9021014026422000;58.903184;11.020739;7
Ekenäs;Strömstad;9021014026410000;58.893610;11.048821;7
Kilesand;Strömstad;9021014026411000;58.878472;11.052983;7
Ramsö;Strömstad;9021014026430000;58.831531;11.067402;7
Sarpsborg;Norge;9021014089002000;59.280937;11.111763;273
Styrsö;Strömstad;9021014026180000;58.908110;11.115818;7
Capri/Källviken;Strömstad;9021014026440000;58.965200;11.124384;63
Lindholmens vändplan;Strömstad;9021014026156000;58.890212;11.128393;64
Öddö;Strömstad;9021014026190000;58.923490;11.130767;7
Källviksdalen;Strömstad;9021014026439000;58.962414;11.131962;64
Husevägen;Strömstad;9021014026505000;58.960094;11.133535;274
Caprivägen;Strömstad;9021014026284000;58.958404;11.134281;64
Stensviks korsväg;Strömstad;9021014026341000;59.001499;11.137203;63
Kungbäck;Strömstad;9021014026340000;59.006056;11.140313;63
Kase;Strömstad;9021014026173000;58.957649;11.141904;274
You should add the information into a SQLite database and ship the app with the database in res/raw.
Additionally, the db file can often be effectively compressed into a zip file.
See this for more information: Ship an application with a database
The fastest way to load that data into memory is to place it right into .java file. E.g. stopNames={"Stop1", "Stop2", ...}; latitudes={...};
I do this in my public transit app, loading similar amounts of the data this way takes under a second, filtering is instant.

Categories

Resources