I'm developing a recipe book and I'm implementing this method to insert my Recipe in the Database. In the for cycle I get the ingredient's name and quantity from multiples EditText, saving each of them in an Ingredient.class instance (newIngredient). Then I insert the instance into the DB and add it to an ArrayList. The followings "if conditions" are for the title, time and other Recipe's attributes. Finally, I also insert Recipe and Tag instances in the relatives DB's tables and I close DB.
public void saveRecipe() {
dbHelper = new DatabaseHelper(context);
// creating new recipe from user input
Ingredient newIngredient;
String title, childIngredient, instruction, tag;
int target, time, childQuantity, calories;
int countIngredients = parentIngredientLayout.getChildCount();
int countTags = chipGroup.getChildCount();
ArrayList<Ingredient> ingredients = null;
ArrayList<Tag> tags = null;
View childViewIng = null;
EditText childTextViewI = null;
EditText childTextViewQ = null;
// ingredients fields settings
for (int d=0; d<countIngredients; d++) {
childViewIng = parentIngredientLayout.getChildAt(d);
childTextViewI = childViewIng.findViewById(R.id.ingredientsField);
childTextViewQ = childViewIng.findViewById(R.id.quantityField);
childIngredient = childTextViewI.getText().toString();
childQuantity = Integer.parseInt(childTextViewQ.getText().toString());
newIngredient = new Ingredient(childIngredient, childQuantity);
dbHelper.insertIngredient(newIngredient);
ingredients.add(newIngredient);
}
//recipe fields settings
if (photoPath1 == null)
photoPath1 = "";
if (photoPath2 == null)
photoPath2 = "";
if (photoPath3 == null)
photoPath3 = "";
if (titleText.getText().toString().isEmpty()) {
title = "";
} else {
title = titleText.getText().toString();
}
if (targetNumber.getText().toString().isEmpty()) {
target = 0;
} else {
target = Integer.parseInt(targetNumber.getText().toString());
}
if (timeNumber.getText().toString().isEmpty()) {
time = 0;
} else {
time = Integer.parseInt(timeNumber.getText().toString());
}
if (instructionText.getText().toString().isEmpty()) {
instruction = "";
} else {
instruction = instructionText.getText().toString();
}
if (caloriesNumber.getText().toString().isEmpty()) {
calories = 0;
} else {
calories = Integer.parseInt(caloriesNumber.getText().toString());
}
if (tagName.getText().toString().isEmpty()) {
tag = "";
} else {
tag = tagName.getText().toString();
}
Recipe newRecipe = new Recipe(title, photoPath1, photoPath2, photoPath3, instruction, target, time, calories, ingredients);
Tag newTag = new Tag(tag);
dbHelper.insertRecipe(newRecipe);
dbHelper.insertTag(newTag);
dbHelper.close(); }
I found out by debugging that in this case is inserted only the first ingredient. I tried to move the FOR until the end of code, but in that case, are inserted both recipe and tag and always only the first ingredient. I think the problem is relative to the opening/closing of the DB. Can somebody help me?
Ingredient constructor:
public Ingredient(String ingredient_name, int quantity) {
this.ingredient_name = ingredient_name;
this.quantity = quantity;
}
dbHelper.insertIngredient(newIngredient) method:
public boolean insertIngredient(Ingredient ingredient) {
db = this.getWritableDatabase();
ContentValues contentValues = new ContentValues();
contentValues.put(INGREDIENT_NAME, ingredient.getIngredient_name());
contentValues.put(QUANTITY, ingredient.getQuantity());
contentValues.put(KEY_CREATED_AT, time.getTime().toString());
long result = db.insert(TBL_INGREDIENTS, null, contentValues);
//db.close();
Log.e(TAG, "Ingredient inserted!");
if (result == -1) {
return false;
} else {
return true;
}
}
Ok, thanks to your comment we got the problem :)
You are calling .add(newIngredient) on a list that you initialized with ArrayList<Ingredient> ingredients = null;
Change it to
ArrayList<Ingredient> ingredients = new ArrayList<Ingredient>();
and it will work :)
Good luck!
I am new to Android. I'm trying to sort by the date in the JSON data, but nothing works. I'm not even getting an error. I've tried so many different ways, but its not working.
I did a lot of searching but could not figure out how to implement this. How can I sort this by the days column? Thank you in advance.
Here's my code
public class ParseJSONTask extends AsyncTask< Void , Void , Void > {
public Handler handler = new Handler();
public Activity act = null;
private static String TAG_SERVICES = "services";
private static String TAG_ID = "id";
private static String TAG_COMMAND = "command";
private static String TAG_DAYS = "days";
private static String TAG_HOURS = "hours";
private static String TAG_OSMS = "osms";
private static String TAG_ISMS = "isms";
private static String TAG_TIMEOUT = "timeout";
public String SMS_SENT = "SMS Gönderildi";
public String SMS_DELIVERED = "SMS İletildi";
public String serviceString = "";
ArrayList<ServiceData> services;
#Override
public void onPreExecute() {
super.onPreExecute();
services = new ArrayList<ServiceData>();
}
#Override
public Void doInBackground(Void... params) {
WebServiceHandler webServiceHandler = new WebServiceHandler();
String JsonStr = webServiceHandler.getJSONData("http://jsonblob.com/55e34310e4b01190df36e861");
try {
JSONObject jsonObject = new JSONObject(JsonStr);
final JSONArray contactsJSON = jsonObject.getJSONArray(TAG_SERVICES);
for (int i = 0; i < contactsJSON.length(); i++) {
ServiceData aServiceData = new ServiceData();
//json parse istedimiz veriyi kullanabiliriz.
JSONObject serviceObject = contactsJSON.getJSONObject(i);
aServiceData.id = serviceObject.getString(TAG_ID);
aServiceData.command = serviceObject.getString(TAG_COMMAND);
aServiceData.days = serviceObject.getString(TAG_DAYS);
aServiceData.hours = serviceObject.getString(TAG_HOURS);
aServiceData.osms = serviceObject.getString(TAG_OSMS);
aServiceData.isms = serviceObject.getString(TAG_ISMS);
aServiceData.timeout = serviceObject.getString(TAG_TIMEOUT);
String input = aServiceData.days + " " + aServiceData.hours;
Date date = new SimpleDateFormat("yyyy-MM-dd HH:mm").parse(input);
long milliseconds = date.getTime();
final long millisecondsFromNow = milliseconds - (new Date()).getTime();
aServiceData.milliseconds = milliseconds;
services.add(aServiceData);
if(millisecondsFromNow > 0) {
new DateSendSMS().onCreate(aServiceData.days, aServiceData.hours, aServiceData.osms, aServiceData.command);
Thread.sleep(Integer.parseInt(aServiceData.timeout) * 60000);
}
//Timeout aşağı kısımda sürelendirilecek
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
String serviceString = "";
for (ServiceData aServiceData:services){
serviceString+=aServiceData.toString();
}
Collections.sort(services, new Comparator<ServiceData>() {
#Override
public int compare(ServiceData t1, ServiceData t2) {
return t1.milliseconds <= t2.milliseconds ? -1 : 1;
}
});
// here is sorted data
for (ServiceData aServiceData : services) {
// move DateSendSMS here. above you can add additional logic about millis
new DateSendSMS().onCreate(aServiceData.days, aServiceData.hours, aServiceData.osms, aServiceData.command);
Log.d("+++++", aServiceData.toString());
}
}
}
ServiceData Class:
public static class ServiceData {
public long milliseconds;
public String id = "";
public String command = "";
public String days = "";
public String hours = "";
public String osms = "";
public String isms = "";
public String timeout = "";
#Override
public String toString() {
return id + ", " + command + ", " + days + ", " + hours + ", " + osms + ", " + isms
+ ", " + timeout + "\n \n ";
}
}
Add time field to ServiceData class
ServiceDate {
...
long milliseconds;
...
}
Fill this field in for loop:
long milliseconds = date.getTime();
aServiceData.milliseconds = milliseconds;
Sort services in onPostExecute
Collections.sort(services, new Comparator<ServiceData>() {
#Override
public int compare(ServiceData t1, ServiceData t2) {
return t1.milliseconds <= t2.milliseconds ? -1 : 1;
}
});
I am not sure you can directly sort Json Data (I dont know weather there is a library that will actually do it - if so go for it). I Suggest you to put all the ServiceData into a collection (Which you do at the moment) and then Sort it.
You can write your own sorting algorithm or you can use a Java Collections library to do the sorting by implimention Comparable on your ServiceData class or using a Comparable and them you can use Colletions.sort() to sort your list.
Here is a good tutorial.
When setting datasource for the media player, following exception is raised. File not found exception. "open failed: ENOENT". No such file or directory. But the file "kick.mp3" exists in the directory "/home/user/Downloads/". How to set the datasource. I am using android on ubuntu 13.10 (Linux)
MainActivity.java
public void play(View v){
try{
mPlayer = new MediaPlayer();
mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
String filePath = "/home/user/Downloads/kick.mp3";
File file = new File(filePath);
FileInputStream inputStream = new FileInputStream(file);
mPlayer.setDataSource(inputStream.getFD());
inputStream.close();
mPlayer.prepare();
mPlayer.start();
button.setText("pause");
}
}catch (Exception e){
Log.e("mPlayer 2", ""+e);
}
}
String filePath = "/home/user/Downloads/kick.mp3";
The file path you define is in your ubuntu os, It is not file path of android media file.
It is not visible to android OS.
To access you android media first you have to fetch media by passing query on content resolver.
/**
* This defines the music songs query constants
*/
public interface SongsQuery {
// External id to be used by loader
final static int QUERY_ID = SequenceGenerator.getUniqueId();
final static Uri CONTENT_URI = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
final static String[] PROJECTIONS = {
MediaStore.Audio.Media._ID,
MediaStore.Audio.Media.ARTIST,
MediaStore.Audio.Media.ALBUM,
MediaStore.Audio.Media.ALBUM_ID,
MediaStore.Audio.Media.TITLE,
MediaStore.Audio.Media.TRACK,
MediaStore.Audio.Media.DATA
};
final static String SELECTION = MediaStore.Audio.Media.IS_MUSIC + "=" + "?";
final static String[] SELECTION_ARGS = {"1"};
final static int ID = 0;
final static int ARTIST = 1;
final static int ALBUM = 2;
final static int ALBUM_ID = 3;
final static int TITLE = 4;
final static int TRACK = 5;
final static int DATA = 6;
}
public class AndroidArtist implements MediaArtist {
private final String mName;
private final URI mArtistURI;
}
public class AndroidMediaItem implements MediaItem {
private final MediaType mMediaType;
private final String mName;
private final AndroidGenre mMediaGenre;
private final URI mFileURI;
private final URI mMediaArturi;
}
private List<MediaItem> mMediaList = new ArrayList<MediaItem>();
public List<MediaItem> loadInBackground() {
Cursor genreQuery = getContext().getContentResolver().query(GenreQuery.CONTENT_URI,
ContentQuery.GenreQuery.PROJECTIONS,
GenreQuery.SELECTION,
GenreQuery.SELECTION_ARGS, null);
if (genreQuery != null) {
for (genreQuery.moveToFirst(); !genreQuery.isAfterLast(); genreQuery.moveToNext()) {
String genreName = genreQuery.getString(GenreQuery.GENRE_NAME);
int genreId = genreQuery.getInt(GenreQuery.GENRE_ID);
Uri genreMemberUri = MediaStore.Audio.Genres.Members.getContentUri("external", genreId);
Cursor songsQuery = getContext().getContentResolver().query(genreMemberUri,
SongsQuery.PROJECTIONS,
SongsQuery.SELECTION,
SongsQuery.SELECTION_ARGS, null);
if (songsQuery != null) {
for (songsQuery.moveToFirst(); !songsQuery.isAfterLast(); songsQuery.moveToNext()) {
File mediaFile = new File(songsQuery.getString(SongsQuery.DATA));
if (mediaFile.exists()) {
AndroidArtist musicArtist = new AndroidArtist(songsQuery.getString(SongsQuery.ARTIST), null);
List< AndroidArtist > mediaArtists = new ArrayList< AndroidArtist >();
mediaArtists.add(musicArtist);
Uri albumArtUri = ContentUris.withAppendedId(sMusicArtworkUri, songsQuery.getLong(SongsQuery.ALBUM_ID));
URI mediaArtURI = null;
if (albumArtUri != null) {
try {
mediaArtURI = new URI(albumArtUri.toString());
} catch (URISyntaxException e) {
e.printStackTrace();
}
}
AndroidMediaItem mediaItem = new AndroidMediaItem(MediaType.AUDIO,
songsQuery.getString(SongsQuery.TITLE),
mediaGenre, URI.create(LibVLC.PathToURI(mediaFile.toURI().getPath())), mediaArtURI);
mMediaList.add(mediaItem);
}
}
songsQuery.close();
}
}
}
if (genreQuery != null) {
genreQuery.close();
}
return mMediaList;
}
Try creating a folder in your projects res folder called raw, then put the mp3 in there
*Edit: After doing this, you have no use for fileinputstream as you can access the file as such:
mp = MediaPlayer.create(this, R.raw.yourfilename);
Make sure that yourfilename has no capital letters, as this will throw a lot of errors & not work
I want to change the color of the text depending on the value from php jsonobject. The program can already get the value and able to display it on each textview. But my problem is, how can I change the color of each text view at the same time, depending on the Flimitstat, Vlimitstat and Climitstat. Hope you can help me!
This is my ThirdFragment.java
package com.example.RadarOperationMonitoringSystem;
import android.app.ProgressDialog;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.ListFragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListAdapter;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.util.HashMap;
public class ThirdFragment extends ListFragment {
String site1 = "";
String freq1 = "";
String curr1 = "";
String volts1 = "";
String fstat1 = "";
String vstat1 = "";
String cstat1 = "";
String site2 = "";
String freq2 = "";
String curr2 = "";
String volts2 = "";
String fstat2 = "";
String vstat2 = "";
String cstat2 = "";
String site3 = "";
String freq3 = "";
String curr3 = "";
String volts3 = "";
String fstat3 = "";
String vstat3 = "";
String cstat3 = "";
String site4 = "";
String freq4 = "";
String curr4 = "";
String volts4 = "";
String fstat4 = "";
String vstat4 = "";
String cstat4 = "";
String site5 = "";
String freq5 = "";
String curr5 = "";
String volts5 = "";
String fstat5 = "";
String vstat5 = "";
String cstat5 = "";
String site6 = "";
String freq6 = "";
String curr6 = "";
String volts6 = "";
String fstat6 = "";
String vstat6 = "";
String cstat6 = "";
String site7 = "";
String freq7 = "";
String curr7 = "";
String volts7 = "";
String fstat7 = "";
String vstat7 = "";
String cstat7 = "";
ArrayList<HashMap<String, String>> contactList = new ArrayList<HashMap<String, String>>();
TextView freqa;
TextView voltsa;
TextView curra;
TextView freqb;
TextView voltsb;
TextView currb;
TextView freqc;
TextView voltsc;
TextView currc;
TextView freqd;
TextView voltsd;
TextView currd;
TextView freqe;
TextView voltse;
TextView curre;
TextView freqf;
TextView voltsf;
TextView currf;
TextView freqg;
TextView voltsg;
TextView currg;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.third_frag, container, false);
freqa = (TextView)v.findViewById(R.id.frequency1);
voltsa = (TextView)v.findViewById(R.id.acvoltage1);
curra = (TextView)v.findViewById(R.id.accurrent1);
freqb = (TextView)v.findViewById(R.id.frequency2);
voltsb = (TextView)v.findViewById(R.id.acvoltage2);
currb = (TextView)v.findViewById(R.id.accurrent2);
freqc = (TextView)v.findViewById(R.id.frequency3);
voltsc = (TextView)v.findViewById(R.id.acvoltage3);
currc = (TextView)v.findViewById(R.id.accurrent3);
freqd = (TextView)v.findViewById(R.id.frequency4);
voltsd = (TextView)v.findViewById(R.id.acvoltage4);
currd = (TextView)v.findViewById(R.id.accurrent4);
freqe = (TextView)v.findViewById(R.id.frequency5);
voltse = (TextView)v.findViewById(R.id.acvoltage5);
curre = (TextView)v.findViewById(R.id.accurrent5);
freqf = (TextView)v.findViewById(R.id.frequency6);
voltsf = (TextView)v.findViewById(R.id.acvoltage6);
currf = (TextView)v.findViewById(R.id.accurrent6);
freqg = (TextView)v.findViewById(R.id.frequency7);
voltsg = (TextView)v.findViewById(R.id.acvoltage7);
currg = (TextView)v.findViewById(R.id.accurrent7);
new GetContacts().execute();
return v;
}
public class GetContacts extends AsyncTask<Void, Void, Void> {
private ProgressDialog pDialog;
// URL to get contacts JSON
private static final String url = "http://10.0.2.2/radaroperations/energyreadings.php";
private static final String TAG_SITENAME1 = "siteName1";
private static final String TAG_FREQUENCY1 = "Frequency1";
private static final String TAG_ACCURRENT1 = "AC_Voltage1";
private static final String TAG_ACVOLTAGE1 = "AC_Current1";
private static final String TAG_FSTAT1 = "Flimitstat1";
private static final String TAG_VSTAT1 = "Vlimitstat1";
private static final String TAG_CSTAT1 = "Climitstat1";
private static final String TAG_SITENAME2 = "siteName2";
private static final String TAG_FREQUENCY2 = "Frequency2";
private static final String TAG_ACCURRENT2 = "AC_Voltage2";
private static final String TAG_ACVOLTAGE2 = "AC_Current2";
private static final String TAG_FSTAT2 = "Flimitstat2";
private static final String TAG_VSTAT2 = "Vlimitstat2";
private static final String TAG_CSTAT2 = "Climitstat2";
private static final String TAG_SITENAME3 = "siteName3";
private static final String TAG_FREQUENCY3 = "Frequency3";
private static final String TAG_ACCURRENT3 = "AC_Voltage3";
private static final String TAG_ACVOLTAGE3 = "AC_Current3";
private static final String TAG_FSTAT3 = "Flimitstat3";
private static final String TAG_VSTAT3 = "Vlimitstat3";
private static final String TAG_CSTAT3 = "Climitstat3";
private static final String TAG_SITENAME4 = "siteName4";
private static final String TAG_FREQUENCY4 = "Frequency4";
private static final String TAG_ACCURRENT4 = "AC_Voltage4";
private static final String TAG_ACVOLTAGE4 = "AC_Current4";
private static final String TAG_FSTAT4 = "Flimitstat4";
private static final String TAG_VSTAT4 = "Vlimitstat4";
private static final String TAG_CSTAT4 = "Climitstat4";
private static final String TAG_SITENAME5 = "siteName5";
private static final String TAG_FREQUENCY5 = "Frequency5";
private static final String TAG_ACCURRENT5 = "AC_Voltage5";
private static final String TAG_ACVOLTAGE5 = "AC_Current5";
private static final String TAG_FSTAT5 = "Flimitstat5";
private static final String TAG_VSTAT5 = "Vlimitstat5";
private static final String TAG_CSTAT5 = "Climitstat5";
private static final String TAG_SITENAME6 = "siteName6";
private static final String TAG_FREQUENCY6 = "Frequency6";
private static final String TAG_ACCURRENT6 = "AC_Voltage6";
private static final String TAG_ACVOLTAGE6 = "AC_Current6";
private static final String TAG_FSTAT6 = "Flimitstat6";
private static final String TAG_VSTAT6 = "Vlimitstat6";
private static final String TAG_CSTAT6 = "Climitstat6";
private static final String TAG_SITENAME7 = "siteName7";
private static final String TAG_FREQUENCY7 = "Frequency7";
private static final String TAG_ACCURRENT7 = "AC_Voltage7";
private static final String TAG_ACVOLTAGE7 = "AC_Current7";
private static final String TAG_FSTAT7 = "Flimitstat7";
private static final String TAG_VSTAT7 = "Vlimitstat7";
private static final String TAG_CSTAT7 = "Climitstat7";
// contacts JSONArray
JSONObject c = null;
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(getActivity());
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
public Void doInBackground(Void... arg0) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject c = new JSONObject(jsonStr);
// Getting JSON Array node
site1 = c.getString(TAG_SITENAME1);
freq1 = c.getString(TAG_FREQUENCY1);
curr1 = c.getString(TAG_ACCURRENT1);
volts1 = c.getString(TAG_ACVOLTAGE1);
fstat1 = c.getString(TAG_FSTAT1);
vstat1 = c.getString(TAG_VSTAT1);
cstat1 = c.getString(TAG_CSTAT1);
site2 = c.getString(TAG_SITENAME2);
freq2 = c.getString(TAG_FREQUENCY2);
curr2 = c.getString(TAG_ACCURRENT2);
volts2 = c.getString(TAG_ACVOLTAGE2);
fstat2 = c.getString(TAG_FSTAT2);
vstat2 = c.getString(TAG_VSTAT2);
cstat2 = c.getString(TAG_CSTAT2);
site3 = c.getString(TAG_SITENAME3);
freq3 = c.getString(TAG_FREQUENCY3);
curr3 = c.getString(TAG_ACCURRENT3);
volts3 = c.getString(TAG_ACVOLTAGE3);
fstat3 = c.getString(TAG_FSTAT3);
vstat3 = c.getString(TAG_VSTAT3);
cstat3 = c.getString(TAG_CSTAT3);
site4 = c.getString(TAG_SITENAME4);
freq4 = c.getString(TAG_FREQUENCY4);
curr4 = c.getString(TAG_ACCURRENT4);
volts4 = c.getString(TAG_ACVOLTAGE4);
fstat4 = c.getString(TAG_FSTAT4);
vstat4 = c.getString(TAG_VSTAT4);
cstat4 = c.getString(TAG_CSTAT4);
site5 = c.getString(TAG_SITENAME5);
freq5 = c.getString(TAG_FREQUENCY5);
curr5 = c.getString(TAG_ACCURRENT5);
volts5 = c.getString(TAG_ACVOLTAGE5);
fstat5 = c.getString(TAG_FSTAT5);
vstat5 = c.getString(TAG_VSTAT5);
cstat5 = c.getString(TAG_CSTAT5);
site6 = c.getString(TAG_SITENAME6);
freq6 = c.getString(TAG_FREQUENCY6);
curr6 = c.getString(TAG_ACCURRENT6);
volts6 = c.getString(TAG_ACVOLTAGE6);
fstat6 = c.getString(TAG_FSTAT6);
vstat6 = c.getString(TAG_VSTAT6);
cstat6 = c.getString(TAG_CSTAT6);
site7 = c.getString(TAG_SITENAME7);
freq7 = c.getString(TAG_FREQUENCY7);
curr7 = c.getString(TAG_ACCURRENT7);
volts7 = c.getString(TAG_ACVOLTAGE7);
fstat7 = c.getString(TAG_FSTAT7);
vstat7 = c.getString(TAG_VSTAT7);
cstat7 = c.getString(TAG_CSTAT7);
// tmp hashmap for single contact
HashMap<String, String> contact = new HashMap<String, String>();
// adding each child node to HashMap key => value
contact.put(TAG_SITENAME1, site1);
contact.put(TAG_FREQUENCY1, freq1);
contact.put(TAG_ACCURRENT1, curr1);
contact.put(TAG_ACVOLTAGE1, volts1);
contact.put(TAG_FSTAT1, fstat1);
contact.put(TAG_VSTAT1, vstat1);
contact.put(TAG_CSTAT1, cstat1);
contact.put(TAG_SITENAME2, site2);
contact.put(TAG_FREQUENCY2, freq2);
contact.put(TAG_ACCURRENT2, curr2);
contact.put(TAG_ACVOLTAGE2, volts2);
contact.put(TAG_FSTAT2, fstat2);
contact.put(TAG_VSTAT2, vstat2);
contact.put(TAG_CSTAT2, cstat2);
contact.put(TAG_SITENAME3, site3);
contact.put(TAG_FREQUENCY3, freq3);
contact.put(TAG_ACCURRENT3, curr3);
contact.put(TAG_ACVOLTAGE3, volts3);
contact.put(TAG_FSTAT3, fstat3);
contact.put(TAG_VSTAT3, vstat3);
contact.put(TAG_CSTAT3, cstat3);
contact.put(TAG_SITENAME4, site4);
contact.put(TAG_FREQUENCY4, freq4);
contact.put(TAG_ACCURRENT4, curr4);
contact.put(TAG_ACVOLTAGE4, volts4);
contact.put(TAG_FSTAT4, fstat4);
contact.put(TAG_VSTAT4, vstat4);
contact.put(TAG_CSTAT4, cstat4);
contact.put(TAG_SITENAME5, site5);
contact.put(TAG_FREQUENCY5, freq5);
contact.put(TAG_ACCURRENT5, curr5);
contact.put(TAG_ACVOLTAGE5, volts5);
contact.put(TAG_FSTAT5, fstat5);
contact.put(TAG_VSTAT5, vstat5);
contact.put(TAG_CSTAT5, cstat5);
contact.put(TAG_SITENAME6, site6);
contact.put(TAG_FREQUENCY6, freq6);
contact.put(TAG_ACCURRENT6, curr6);
contact.put(TAG_ACVOLTAGE6, volts6);
contact.put(TAG_FSTAT6, fstat6);
contact.put(TAG_VSTAT6, vstat6);
contact.put(TAG_CSTAT6, cstat6);
contact.put(TAG_SITENAME7, site7);
contact.put(TAG_FREQUENCY7, freq7);
contact.put(TAG_ACCURRENT7, curr7);
contact.put(TAG_ACVOLTAGE7, volts7);
contact.put(TAG_FSTAT7, fstat7);
contact.put(TAG_VSTAT7, vstat7);
contact.put(TAG_CSTAT7, cstat7);
// adding contact to contact list
contactList.clear();
contactList.add(contact);
} catch (JSONException e) {
e.printStackTrace();
}
}else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
#Override
public void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**
*
*/
//RADAR 1
//Frequency 1 status
if (TAG_FSTAT1.equals("1")){
freqa.setTextColor(Color.GREEN);
}
else if(TAG_FSTAT1.equals("2")){
freqa.setTextColor(getResources().getColor(R.color.red));
}
//AC_Voltage 1 status
if (TAG_VSTAT1.equals("1")){
voltsa.setTextColor(getResources().getColor(R.color.green));
}
else if(TAG_VSTAT1.equals("2")){
voltsa.setTextColor(getResources().getColor(R.color.red));
}
//AC_Current 1 status
if (TAG_CSTAT1.equals("1")){
curra.setTextColor(getResources().getColor(R.color.green));
}
else if(TAG_CSTAT1.equals("2")){
curra.setTextColor(getResources().getColor(R.color.red));
}
//RADAR 2
//Frequency 2 status
if (TAG_FSTAT2.equals("1")){
freqb.setTextColor(getResources().getColor(R.color.green));
}
else if(TAG_FSTAT2.equals("2")){
freqb.setTextColor(getResources().getColor(R.color.red));
}
//AC_Voltage 2 status
if (TAG_VSTAT2.equals("1")){
voltsb.setTextColor(getResources().getColor(R.color.green));
}
else if(TAG_VSTAT2.equals("2")){
voltsb.setTextColor(getResources().getColor(R.color.red));
}
//AC_Current 2 status
if (TAG_CSTAT2.equals("1")){
currb.setTextColor(getResources().getColor(R.color.green));
}
else if(TAG_CSTAT2.equals("2")){
currb.setTextColor(getResources().getColor(R.color.red));
}
//RADAR 3
//Frequency 3 status
if (TAG_FSTAT3.equals("1")){
freqc.setTextColor(getResources().getColor(R.color.green));
}
else if(TAG_FSTAT3.equals("2")){
freqc.setTextColor(getResources().getColor(R.color.red));
}
//AC_Voltage 3 status
if (TAG_VSTAT3.equals("1")){
voltsc.setTextColor(getResources().getColor(R.color.green));
}
else if(TAG_VSTAT3.equals("2")){
voltsc.setTextColor(getResources().getColor(R.color.red));
}
//AC_Current 3 status
if (TAG_CSTAT3.equals("1")){
currc.setTextColor(getResources().getColor(R.color.green));
}
else if(TAG_CSTAT3.equals("2")){
currc.setTextColor(getResources().getColor(R.color.red));
}
//RADAR 4
//Frequency 4 status
if (TAG_FSTAT4.equals("1")){
freqd.setTextColor(getResources().getColor(R.color.green));
}
else if(TAG_FSTAT4.equals("2")){
freqd.setTextColor(getResources().getColor(R.color.red));
}
//AC_Voltage 4 status
if (TAG_VSTAT4.equals("1")){
voltsd.setTextColor(getResources().getColor(R.color.green));
}
else if(TAG_VSTAT4.equals("2")){
voltsd.setTextColor(getResources().getColor(R.color.red));
}
//AC_Current 4 status
if (TAG_CSTAT4.equals("1")){
currd.setTextColor(getResources().getColor(R.color.green));
}
else if(TAG_CSTAT4.equals("2")){
currd.setTextColor(getResources().getColor(R.color.red));
}
//RADAR 5
//Frequency 5 status
if (TAG_FSTAT5.equals("1")){
freqe.setTextColor(getResources().getColor(R.color.green));
}
else if(TAG_FSTAT5.equals("2")){
freqe.setTextColor(getResources().getColor(R.color.red));
}
//AC_Voltage 5 status
if (TAG_VSTAT5.equals("1")){
voltse.setTextColor(getResources().getColor(R.color.green));
}
else if(TAG_VSTAT5.equals("2")){
voltse.setTextColor(getResources().getColor(R.color.red));
}
//AC_Current 5 status
if (TAG_CSTAT5.equals("1")){
curre.setTextColor(getResources().getColor(R.color.green));
}
else if(TAG_CSTAT5.equals("2")){
curre.setTextColor(getResources().getColor(R.color.red));
}
//RADAR 6
//Frequency 6 status
if (TAG_FSTAT6.equals("1")){
freqf.setTextColor(getResources().getColor(R.color.green));
}
else if(TAG_FSTAT6.equals("2")){
freqf.setTextColor(getResources().getColor(R.color.red));
}
//AC_Voltage 6 status
if (TAG_VSTAT6.equals("1")){
voltsf.setTextColor(getResources().getColor(R.color.green));
}
else if(TAG_VSTAT6.equals("2")){
voltsf.setTextColor(getResources().getColor(R.color.red));
}
//AC_Current 6 status
if (TAG_CSTAT6.equals("1")){
currf.setTextColor(getResources().getColor(R.color.green));
}
else if(TAG_CSTAT6.equals("2")){
currf.setTextColor(getResources().getColor(R.color.red));
}
//RADAR 7
//Frequency 7 status
if (TAG_FSTAT7.equals("1")){
freqg.setTextColor(getResources().getColor(R.color.green));
}
else if(TAG_FSTAT7.equals("2")){
freqg.setTextColor(getResources().getColor(R.color.red));
}
//AC_Voltage 7 status
if (TAG_VSTAT7.equals("1")){
voltsg.setTextColor(getResources().getColor(R.color.green));
}
else if(TAG_VSTAT7.equals("2")){
voltsg.setTextColor(getResources().getColor(R.color.red));
}
//AC_Current 7 status
if (TAG_CSTAT7.equals("1")){
currg.setTextColor(getResources().getColor(R.color.green));
}
else if(TAG_CSTAT7.equals("2")){
currg.setTextColor(getResources().getColor(R.color.red));
}
ListAdapter adapter = new SimpleAdapter(
getActivity(), contactList,
R.layout.list_item, new String[] { TAG_SITENAME1, TAG_FREQUENCY1, TAG_ACCURRENT1,
TAG_ACVOLTAGE1,TAG_SITENAME2, TAG_FREQUENCY2, TAG_ACCURRENT2,
TAG_ACVOLTAGE2,TAG_SITENAME3, TAG_FREQUENCY3, TAG_ACCURRENT3,
TAG_ACVOLTAGE3, TAG_SITENAME4, TAG_FREQUENCY4, TAG_ACCURRENT4,
TAG_ACVOLTAGE4, TAG_SITENAME5, TAG_FREQUENCY5, TAG_ACCURRENT5,
TAG_ACVOLTAGE5, TAG_SITENAME6, TAG_FREQUENCY6, TAG_ACCURRENT6,
TAG_ACVOLTAGE6, TAG_SITENAME7, TAG_FREQUENCY7, TAG_ACCURRENT7,
TAG_ACVOLTAGE7},
new int[] { R.id.sitename1, R.id.frequency1,
R.id.accurrent1, R.id.acvoltage1, R.id.sitename2, R.id.frequency2,
R.id.accurrent2, R.id.acvoltage2, R.id.sitename3, R.id.frequency3,
R.id.accurrent3, R.id.acvoltage3, R.id.sitename4, R.id.frequency4,
R.id.accurrent4, R.id.acvoltage4, R.id.sitename5, R.id.frequency5,
R.id.accurrent5, R.id.acvoltage5, R.id.sitename6, R.id.frequency6,
R.id.accurrent6, R.id.acvoltage6, R.id.sitename7, R.id.frequency7,
R.id.accurrent7, R.id.acvoltage7});
// updating listviews
setListAdapter(adapter);
}
}
public static ThirdFragment newInstance(String text) {
ThirdFragment f = new ThirdFragment();
Bundle b = new Bundle();
b.putString("msg", text);
f.setArguments(b);
return f;
}
}
You can check my listadapter and i have implemented the same concept to set the text color in two ways
private class CustomerAdapter extends ArrayAdapter<RouteTrackerUser>
{
Context context;
int textViewResourceId;
private ArrayList<RouteTrackerUser> originalitems;
public CustomerAdapter(Context context, int textViewResourceId, ArrayList<RouteTrackerUser> items) {
super(context, textViewResourceId, items);
this.textViewResourceId = textViewResourceId;
this.context = context;
this.originalitems = items;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater inflater = ((Activity) context).getLayoutInflater();
v = inflater.inflate(textViewResourceId, parent, false);
}
final RouteTrackerUser r = originalitems.get(position);
if (r != null) {
TextView textName= (TextView) v.findViewById(R.id.sname);
TextView postal=(TextView) v.findViewById(R.id.postal);
if(r.getVisited().equals("true"))
{
if(textName != null)
{
textName.setTextColor(getResources().getColor(R.color.lightpurple));
textName.setText(r.getStorename());
}
if(postal != null)
{
postal.setTextColor(getResources().getColor(R.color.lightpurple));
postal.setText("Address: "+r.getPostalcode());
}
}
if(r.getVisited().equals("false"))
{
if(textName != null)
{
textName.setTextColor(getResources().getColor(R.color.darkpurple));
textName.setText(r.getStorename());
}
if(postal != null)
{
postal.setTextColor(getResources().getColor(R.color.darkpurple));
postal.setText("Address: "+r.getPostalcode());
}
}
if(RouteTrackerApp.sharedPreference.getInt(RouteTrackerApp.SHARED_ACCESS_UTYPE, 0) == Constants.VAR_TYPE_SALES_PERSON){
v.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
viewdata(r.getUsername(),r.getStoreid(),r.getAccountid(),r.getUid(),r.getVisitplanid(),r.getVisited(),r.getStorename());
}});
}
}
return v;
}
}
and on PostExecute i called this adapter like
protected void onPostExecute(ArrayList<RouteTrackerUser> result)
{
if(result!=null)
{
// System.out.println("User with result===>"+result);
/*for(RouteTrackerUser r :result ){
System.out.println("StoreName===>"+r.getStorename());}*/
Intent intent=getIntent();
TextView username=(TextView)findViewById(R.id.usrname);
final String sname=intent.getExtras().getString("user_name");
username.setText("Welcome, "+sname);
TextView todayvisits=(TextView)findViewById(R.id.todaylist);
todayvisits.setText("TODAY'S STORE VISITS");
userAdapter = new CustomerAdapter(ViewYourPlanList.this, R.layout.view_your_plan_list,result);
userList = (ListView) findViewById(R.id.listview);
userList.setItemsCanFocus(false);
userList.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
userList.setAdapter(userAdapter);
dialog.dismiss();
}
else
if you are want to implement in listfragment ! Design a customadapter and set the text color like i shown below and call this customadapter on postexecute.
public class CustomAdapter extends ArrayAdapter<Model> {
private final LayoutInflater mInflater;
public CustomAdapter(Context context) {
super(context, android.R.layout.simple_list_item_2);
mInflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
public void setData(List<Model> data) {
clear();
if (data != null) {
for (Model appEntry : data) {
System.out.println("cust adptr set data: "+appEntry.getStorename());
add(appEntry);
}
}
}
/**
* Populate new items in the list.
*/
#SuppressLint("SimpleDateFormat")
#Override public View getView(int position, View convertView, ViewGroup parent) {
View view;
if (convertView == null) {
view = mInflater.inflate(R.layout.view_your_plan_weekly, parent, false);
} else {
view = convertView;
}
Model item = getItem(position);
int dayVal = Calendar.getInstance().get(Calendar.DAY_OF_WEEK)-1;
ImageView arrow=(ImageView)view.findViewById(R.id.arrow_image);
arrow.setVisibility(View.INVISIBLE);
if(item.getTabId().equals(String.valueOf(dayVal))){
arrow.setVisibility(View.VISIBLE);
}
if(item.getVisited().equals("true"))
{
((TextView)view.findViewById(R.id.sname)).setText(item.getStorename());
((TextView)view.findViewById(R.id.postal)).setText(item.getPostal());
((TextView)view.findViewById(R.id.sname)).setTextColor(Color.parseColor("#D397D4"));
((TextView)view.findViewById(R.id.postal)).setTextColor(Color.parseColor("#D397D4"));
}
if(item.getVisited().equals("false"))
{
((TextView)view.findViewById(R.id.sname)).setText(item.getStorename());
((TextView)view.findViewById(R.id.postal)).setText(item.getPostal());
((TextView)view.findViewById(R.id.sname)).setTextColor(Color.parseColor("#9B419B"));
((TextView)view.findViewById(R.id.postal)).setTextColor(Color.parseColor("#9B419B"));
}
return view;
}
}
Remove this part
ListAdapter adapter = new SimpleAdapter(
getActivity(), contactList,
R.layout.list_item, new String[] { TAG_SITENAME1, TAG_FREQUENCY1, TAG_ACCURRENT1,
TAG_ACVOLTAGE1,TAG_SITENAME2, TAG_FREQUENCY2, TAG_ACCURRENT2,
TAG_ACVOLTAGE2,TAG_SITENAME3, TAG_FREQUENCY3, TAG_ACCURRENT3,
TAG_ACVOLTAGE3, TAG_SITENAME4, TAG_FREQUENCY4, TAG_ACCURRENT4,
TAG_ACVOLTAGE4, TAG_SITENAME5, TAG_FREQUENCY5, TAG_ACCURRENT5,
TAG_ACVOLTAGE5, TAG_SITENAME6, TAG_FREQUENCY6, TAG_ACCURRENT6,
TAG_ACVOLTAGE6, TAG_SITENAME7, TAG_FREQUENCY7, TAG_ACCURRENT7,
TAG_ACVOLTAGE7},
new int[] { R.id.sitename1, R.id.frequency1,
R.id.accurrent1, R.id.acvoltage1, R.id.sitename2, R.id.frequency2,
R.id.accurrent2, R.id.acvoltage2, R.id.sitename3, R.id.frequency3,
R.id.accurrent3, R.id.acvoltage3, R.id.sitename4, R.id.frequency4,
R.id.accurrent4, R.id.acvoltage4, R.id.sitename5, R.id.frequency5,
R.id.accurrent5, R.id.acvoltage5, R.id.sitename6, R.id.frequency6,
R.id.accurrent6, R.id.acvoltage6, R.id.sitename7, R.id.frequency7,
R.id.accurrent7, R.id.acvoltage7});
// updating listviews
setListAdapter(adapter);
and instead of SimpleAdapter you use customadapter. In CustomAdapter you can set the textcolor as i shown in my previous post.Just go through the class "public class CustomAdapter extends ArrayAdapter "
I'm trying to read a file which consists of some lines and each line has 3 parts: id , name and surname. There is also an EditText where the user needs to enter his id and in case it matches with one of the ones read from the file it should show a dialog like this one: Are you "Name", "Username"?
I've tried doing the following thing but unfortunately it doesn't work.
public String getDNI() {
String[] parts = fichero.split("\\,");
String DNI = parts[0];
return DNI;
}
public String getNombre() {
String[] parts = fichero.split("\\,");
String Nombre = parts[1];
return Nombre;
}
public String getEnunciado() {
String[] parts = fichero.split("\\,");
String Apellido = parts[2];
return Apellido;
}
public void onCreate(Bundle icicle)
{
super.onCreate(icicle);
setContentView(R.layout.identificacion);
Button bSiguiente = (Button) findViewById(R.id.btn_siguiente);
dniText = (EditText) findViewById(R.id.dni_candidato);
try {
InputStream is = getAssets().open(File);
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
// Skips lines
for (i = 0; i<= 100; i++) {
reader.readLine();
}
fichero = reader.readLine();
} catch (IOException e) {
e.printStackTrace();
}
bSiguiente.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
try{
longitud = dniText.getText().toString();
user = Integer.parseInt(dniText.getText().toString());
DNIWord(user);
for (i = 0; i<= 100; i++) {
if (longitud.equals(getDNI())){
// (longitud.length()==8){
showDialog(DIALOG_CONFIRMAR_CANDIDATO);}
else{
showDialog(DIALOG_ERROR_DNI);
}
}
}
catch (NumberFormatException e)
{}
}
A better approach is to create a class to represent your user:
class User{
public String nombre;
public String enunciado;
public String dni;
public User(String nombre, String enunciado, String dni){
this.nombre = nombre;
this.enunciado = enunciado;
this.dni = dni;
}
public User(String csvLine){
String[] values = csvLine.split(",");
this(values[0], values[1], values[2]);
}
}
I prefer the first constructor because it's easier to read.
Use like this:
ArrayList<User> users = new ArrayList<User>();
...
String s;
while ((s = reader.readLine()) != null) {
users.add(new User(s));
}
or
String s;
String[] value;
while ((s = reader.readLine()) != null) {
values = s.split(",");
users.add(new User(values[0], values[1], values[2])); <-- prefer this one
}
To make it even better:
public static final int DNI = 0;
public static final int NOMBRE = 1;
public static final int ENUNCIADO = 2;
...
String s;
String[] value;
while ((s = reader.readLine()) != null) {
values = s.split(",");
users.add(new User(values[DNI], values[NOMBRE], values[ENUNCIADO]));
}
Now you can work with your users collection using users.contains, users.getElementAt, Collections.sort, Collections.binarySearch etc.
Here is another question helpful for parsing CVS in C++: How can I read and parse CSV files in C++?
If you are open to other languages, like python, it might be much easier. For example, python has build-in csv tools:
http://docs.python.org/2/library/csv.html