I have a table in Parse which is named Customer_Information. And there is a column named username. I want to retrieve all the values in the username column and store it to array. After storing, i want to set it to a single textview. Is this possible? I've tried this code but it has an error ArrayIndexOutOfBounds.
public class Users extends Activity{
private static final String tbname = "Customer_Information";
private static final String uname = "username";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.users);
TextView text = (TextView)findViewById(R.id.text);
ParseQuery query = new ParseQuery(tbname);{
try{
List<ParseObject> test = query.find();
for(int x=0;x<test.size();x++){
String[] str = {test.get(x).getString(uname)};
text.setText("Username: "+str[x]+"\n");
}
}
catch (com.parse.ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
The problem is most likely with this line:
text.setText("Username: "+str[x]+"\n");
You are trying to access an index, but you are accessing it with x. If all the ParseObjects return an array of the same length, after a while, as x increases, it will become greater than that array's greatest index, resulting in an IndexOutOfBoundsException.
I suggest you first do some testing: print out the values of str, figure out what index you need, then change the line so it uses the constant index. Based on the fact that you only have 1 element in the array since you do
String[] str = {test.get(x).getString(uname)};//one element array
the index is most likely 0:
text.setText("Username: "+str[0]+"\n");
If you are not going to make str any larger than 1 element, discard it and use just a single String.
Related
I have a JSON Array which consists of some contacts in my phonebook who are also users of my app. For example, the JSON Array might look like :
[{"contact_phonenumber":"11111"},{"contact_phonenumber":"22222"},{"contact_phonenumber":"33333"}]
phoneNumberofContact is a string which, in the do statement in my code below, returns every contact in my phone. How can I check which phoneNumberofContact numbers appear in my JSON Array and then, besides those contacts in the ListView put the words '- app user'. My ListView is working fine, I just want to add this feature in.
So, for example, for the number 11111 I would have in my ListView :
Joe Blogs - app user
11111
Here's my code:
JSONArray jsonArrayContacts = response;
//response is something like [{"contact_phonenumber":"11111"}, etc...]
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new_contact);
//selectPhoneContacts is an empty array list that will hold our SelectPhoneContact info
selectPhoneContacts = new ArrayList<SelectPhoneContact>();
listView = (ListView) findViewById(R.id.listviewPhoneContacts);
}
//******for the phone contacts in the listview
// Load data in background
class LoadContact extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... voids) {
// we want to delete the old selectContacts from the listview when the Activity loads
// because it may need to be updated and we want the user to see the updated listview,
// like if the user adds new names and numbers to their phone contacts.
selectPhoneContacts.clear();
// we have this here to avoid cursor errors
if (cursor != null) {
cursor.moveToFirst();
}
try {
// get a handle on the Content Resolver, so we can query the provider,
cursor = getApplicationContext().getContentResolver()
// the table to query
.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,
null,
null,
null,
// display in ascending order
ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME + " COLLATE LOCALIZED ASC");
// get the column number of the Contact_ID column, make it an integer.
// I think having it stored as a number makes for faster operations later on.
// get the column number of the DISPLAY_NAME column
int nameIdx = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME);
// get the column number of the NUMBER column
int phoneNumberofContactIdx = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER);
cursor.moveToFirst();
// We make a new Hashset to hold all our contact_ids, including duplicates, if they come up
Set<String> ids = new HashSet<>();
do {
System.out.println("=====>in while");
// get a handle on the display name, which is a string
name = cursor.getString(nameIdx);
// get a handle on the phone number, which is a string
phoneNumberofContact = cursor.getString(phoneNumberofContactIdx);
//----------------------------------------------------------
// get a handle on the phone number of contact, which is a string. Loop through all the phone numbers
// if our Hashset doesn't already contain the phone number string,
// then add it to the hashset
if (!ids.contains(phoneNumberofContact)) {
ids.add(phoneNumberofContact);
SelectPhoneContact selectContact = new SelectPhoneContact();
selectContact.setName(name);
selectContact.setPhone(phoneNumberofContact);
selectPhoneContacts.add(selectContact);
}
} while (cursor.moveToNext());
} catch (Exception e) {
Toast.makeText(NewContact.this, "what the...", Toast.LENGTH_LONG).show();
e.printStackTrace();
// cursor.close();
} finally {
}
if (cursor != null) {
cursor.close();
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
adapter = new SelectPhoneContactAdapter(selectPhoneContacts, NewContact.this);
// we need to notify the listview that changes may have been made on
// the background thread, doInBackground, like adding or deleting contacts,
// and these changes need to be reflected visibly in the listview. It works
// in conjunction with selectContacts.clear()
adapter.notifyDataSetChanged();
listView.setAdapter(adapter);
}
}
In the first, you can parse the jsonArrayContacts to a List:
final List<String> responseContacts = new ArrayList<String>();
try {
JSONArray responseObject = new JSONArray(response);
for (int i = 0; i < responseObject.length(); i++) {
final JSONObject obj = responseObject.getJSONObject(i);
responseContacts.add(obj.getString("contact_phonenumber"));
}
// System.out.println("the matching contacts of this user are :" + responseContacts);
} catch(Exception e) {
e.printStackTrace();
}
after you get your local contacts, then you have two sets of contacts, so it's easy to check which number appears in your json array contacts.
And then you can pass the responseContacts into SelectPhoneContactAdapter during you initialize it, and in getView() method of the adapter, you can know whether you need to put the words '- app user' to your item view or not.
I need to remove stopwords from a string. I use the following code to remove stopwords and setting the final output in a textView. But when i run the code it always give the output "bugs". In other words it always give me the last string word as output. Please Check my code and Help!
public class Testing extends Activity {
TextView t1;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.testing);
t1= (TextView)findViewById(R.id.textView1);
String s="I love this phone, its super fast and there's so" +
" much new and cool things with jelly bean....but of recently I've seen some bugs.";
String[] words = s.split(" ");
ArrayList<String> wordsList = new ArrayList<String>();
Set<String> stopWordsSet = new HashSet<String>();
stopWordsSet.add("I");
stopWordsSet.add("THIS");
stopWordsSet.add("AND");
stopWordsSet.add("THERE'S");
for(String word : words)
{
String wordCompare = word.toUpperCase();
if(!stopWordsSet.contains(wordCompare))
{
wordsList.add(word);
}
}
for (String str : wordsList){
System.out.print(str+" ");
t1.setText(str);
}
}
t1.setText(str); means it doesn't care what the previous text was. It puts the last one in loop. So use append instead.
t1.append(str);
OR Append every single str to a single String and set that in TextView after the loop.
The output is "bugs." because of this line of code:
t1.setText(str);
which will re-write the textview everytime inside the loop. Because the last iteration the word is "bugs.", the textview will display bugs.
If you want to append the string instead of re-writting it use:
t1.append(str);
Hope it helps.
I'm using a web service which returns data in JSON format like this:
{"content":[{"id":"1","asset_id":"62","title":"sample page","alias":"","introtext":"","fulltext":"Some Contents"},{"id":"2","asset_id":"62","title":"sample page2","alias":"","introtext":"","fulltext":"Some Contents"},{"id":"3","asset_id":"62","title":"sample page3","alias":"","introtext":"","fulltext":"Some Contents"}]}
onCreate() of MainActivity.java is :
boolean myFlag = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.myView);
setFlag = PreferenceManager.getDefaultSharedPreferences(MainActivity.this);
dataSource = new ContentsDataSource(this);
dataSource.open();
parseAndIsertData();
}
the parseAndInsertData() is :
EDIT
private void parseAndIsertData() {
// Creating JSON Parser instance
MyJSONParser jParser = new MyJSONParser();
contentDataObject = new ContentDataObject();
// getting JSON string from URL
JSONObject json = jParser.getJSONFromUrl(BASE_URL);
try {
// first time check if data is inserted
editor = setFlag.edit();
editor.putBoolean(MY_KEY, true);
// Getting Array of Contents
jsonArray = json.getJSONArray(MOBILE_CONTENT);
// looping through All Contents
if(!myFlag){
for(int i = 0; i < jsonArray.length(); i++){
contentDataObject.setId(jsonArray.getJSONObject(i).getInt(MOBILE_CONTENT_ID));
contentDataObject.setTitle(jsonArray.getJSONObject(i).getString(MOBILE_CONTENT_TITLE));
contentDataObject.setFulltext(jsonArray.getJSONObject(i).getString(MOBILE_CONTENT_FULLTEXT));
contentDataObject.setState(jsonArray.getJSONObject(i).getInt(MOBILE_CONTENT_STATE));
contentDataObject.setNewValue(jsonArray.getJSONObject(i).getInt(MOBILE_CONTENT_NEW));
contentDataObject.setHeader(jsonArray.getJSONObject(i).getString(MOBILE_CONTENT_HEADER));
contentDataObject.setColor(jsonArray.getJSONObject(i).getInt(MOBILE_CONTENT_COLOR));
contentDataObject.setNext(jsonArray.getJSONObject(i).getString(MOBILE_CONTENT_NEXT));
contentDataObject.setPrevious(jsonArray.getJSONObject(i).getString(MOBILE_CONTENT_PREVIOUS));
contentDataObject = dataSource.create(contentDataObject);
Log.i(MY_TAGT, "Data Inserted " + contentDataObject.getId() + " Times");
}
myFlag = setFlag.getBoolean(MY_KEY, false);
}
} catch (JSONException e) {
e.printStackTrace();
}
}}
Now My logcat for first time launch is :
and when I relaunch the app my logcat is :
Now I want ask that is this approach correct or not if YES! then will I be able to update that later on!!
Thanks!
You are correct that this code will insert the data multiple times. It will be up to you to implement a pattern that allows only one row.
You need to either query the data source first and not insert the data if it exists or you need to delete the data from the data source and then insert it every time. There are other patterns but these two will be the most common. Which one you choose will depend on what the data is and how you want it maintained or updated.
define a column in your table to be primary key or unique
use SQLiteDatabase.insertWithOnConflict(...) with the conflictAlgorithm parameter (the last one) set to ``SQLiteDatabase.CONFLICT_IGNORE`
See this
I have ORMLite database with some fields. I want to select titles from the table where id == id which I get from webservice. I do like that:
try {
Dao<ProcessStatus,Integer> dao = db.getStatusDao();
Log.i("status",dao.queryForAll().toString());
QueryBuilder<ProcessStatus,Integer> query = dao.queryBuilder();
Where where = query.where();
String a = null;
for(Order r:LoginActivity.orders) {
//LoginActivity.orders - array of my objects which I get from webservice
Log.i("database",query.selectRaw("select title from process_status").
where().rawComparison(ProcessStatus.STATUS_ID, "=",
r.getProcess_status().getProccessStatusId()).toString());
}
Log.i("sr",a);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
I tried like this but I get only sets of my id, not titles. I tried like this:
Log.i("database", query.selectColumns(ProcessStatus.STATUS_TITLE).where().
eq(ProcessStatus.STATUS_ID, r.getProcess_status().getProccessStatusId())
.toString());
but I have the same result. How should I get data from database?
For selecting an specific field from the table, you could do something like this:
String result = "";
try {
GenericRawResults<String[]> rawResults = yourDAO.queryRaw("select " +
ProcessStatus.STATUS_TITLE +" from YourTable where "+
ProcessStatus.STATUS_ID + " = " +
r.getProcess_status().getProccessStatusId());
List<String[]> results = rawResults.getResults();
// This will select the first result (the first and maybe only row returned)
String[] resultArray = results.get(0);
//This will select the first field in the result which should be the ID
result = resultArray[0];
} catch (Exception e) {
e.printStackTrace();
}
Hope this helps.
It's hard to properly answer this question without seeing all of the classes of the processStatusId field and others. However I think you are doing too much raw method and may not be properly escaping your values and the like.
I would recommend that you use the IN SQL statement instead of what you are doing in the loop. Something like:
List<String> ids = new ArrayList<String>();
for(Order r : LoginActivity.orders) {
ids.add(r.getProcess_status().getProccessStatusId());
}
QueryBuilder<ProcessStatus, Integer> qb = dao.queryBuilder();
Where where = qb.where();
where.in(ProcessStatus.STATUS_ID, ids);
qb.selectColumns(ProcessStatus.STATUS_TITLE);
Now that you have built your query, either you can retrieve your ProcessStatus objects or you can get the titles themselves using dao.queryForRaw(...):
List<ProcessStatus> results = qb.query();
// or use the prepareStatementString method to get raw results
GenericRawResults<String[]> results = dao.queryRaw(qb.prepareStatementString());
// each raw result would have a String[] with 1 element for the title
I want to save weekdays in database, so i thought to store it by assigning int value to each day. i.e
1 -> Selected, 0 -> Not Selected.
Monday = 0/1
Tuesday = 0/1
.
.
.
.
.
Sunday = 0/1.
But this will make 7 columns in DB. So I was thinking if anyone can help me with this if I should store it in a single array and retrieve the values for further use. I was reading some examples over internet but didn't get it in a easy way.
To insert 7 values in one column you can use comma separator like this
where Total_Score_P1 is an string array
//string array
String[] Total_Score = new String[] { p1e1,p1e2,p1e3,p1e4,p1e5,p1e6 };
// Convderting it into a single string
String result_ScoreP1 = ("" + Arrays.asList(Total_Score_P1)).
replaceAll("(^.|.$)", " ").replace(", ", " , " );
result_ScoreP1 will be
// output of this
result_ScoreP1 = "p1e1,p1e2,p1e3,p1e4,p1e5,p1e6";
insert it as a single string in database and
when retrieve it in again break in parts like
// a string array list
// query fired
public ArrayList<String> rulTable(String id) {
// TODO Auto-generated method stub
ArrayList<String> Ruleob = new ArrayList<String>();
Cursor c_rule;
try
{
c_rule = db.query(NameTable, new String[]{
columns1
},
Rule_COurseID + "=" + id ,
null, null,
null, null, null);
c_rule.moveToFirst();
// if there is data available after the cursor's pointer, add
// it to the ArrayList that will be returned by the method.
if (!c_rule.isAfterLast())
{
do
{
Ruleob.add(c_rule.getString(0));
}
while (c_rule.moveToNext());
}
// let java know that you are through with the cursor.
c_rule.close();
}
catch(Exception e)
{
}
return Ruleob;
}
//list to get elements
ArrayList<String> ListOne = new ArrayList<String>();
ArrayList<String> row ;
try{
// received values
row = db.TheTable(id);
String r1 = row .get(0);
}
catch(Exception e)
{
}
StringTokenizer st2 = new StringTokenizer(r1, "||");
while(st2.hasMoreTokens()) {
String Desc = st2.nextToken();
System.out.println(Desc+ "\t" );
ListOne.add(Desc);
//
}
You can use a binary integer 1= selected 0 =Not Selected (1111111) (0000000)
total seven days so index 0=mon, 1=tues, 2=wed, 3=thurs, 4=friday, 5=sat, 6=sunday..and so on..
here 1111111 means all day selected, 0000000 all day not selected, 0001000 only thursday is selected.
I have also discovered a way i.e. convert your so called values to a JSON Array and then store the complete JSON String to an entity/field in Database.
It helps in serving the values easily and effectivly.
Create another table with a column for each day, boolean value. Make an association to this table by integer id (use a foreign key) This is the relational way of solving the problem.