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 use the following code to read each contacts along with their details.
private static final String[] PROJECTION =
{
Data._ID,
Data.MIMETYPE,
Data.DATA1,
Data.DATA2,
Data.DATA3,
Data.DATA4,
Data.DATA5,
Data.DATA6,
Data.DATA7,
Data.DATA8,
Data.DATA9,
Data.DATA10,
Data.DATA11,
Data.DATA12,
Data.DATA13,
Data.DATA14,
Data.DATA15
};
private static final String SELECTION = Data.LOOKUP_KEY + " = ?";
private String[] mSelectionArgs = { "" };
private static final String SORT_ORDER = Data.MIMETYPE;
private static final int MIME_TYPE_INDEX = 1;
private static final int DISPLAY_NAME_INDEX = 3;//data2
private static final int GIVEN_NAME_INDEX = 3;//data2
private static final int FAMILY_NAME_INDEX = 4;//data3
private static final int MIDDLE_NAME_INDEX = 6;//data5
private static final int ORGANIZATION_INDEX = 2;//data2
private static final int PHONE_TYPE_INDEX = 3;//data2
private static final int PHONE_LABEL_INDEX = 4;//data3
private static final int PHONE_NUMBER_INDEX = 2;//data1
private static final int EMAIL_TYPE_INDEX = 3;//data2
private static final int EMAIL_LABEL_INDEX = 4;//data1
private static final int EMAIL_INDEX = 2;//data1
private byte[] createJsonData(ArrayList<String> selected) throws JSONException, IOException{
Log.d("SynchContactActivity", "Time 1: " + java.text.DateFormat.getDateTimeInstance().format(Calendar.getInstance().getTime()));
int current = 0;
final String messagePrep = getResources().getString(R.string.progress_message_prep);
final String messageCompress = getResources().getString(R.string.progress_message_compress);
final String messageUpload = getResources().getString(R.string.progress_message_upload);
if(selected == null ){
selected = getContacts();
}
final int count = selected.size();
mHandler.post(new Runnable() {
#Override
public void run() {
if(mProgressDialog != null){
mProgressDialog.setMax(count);
mProgressDialog.setMessage(messagePrep);
}
}
});
updateProgress(current);
JSONObject root = new JSONObject();
JSONArray contactsArray = new JSONArray();
JSONObject contactJSON, phoneJSON, emailJSON;
JSONArray phonesArray,emailsArray;
String name, lastName, middleName,organization;
for (String key : selected) {
contactJSON = new JSONObject();
phonesArray = new JSONArray();
emailsArray = new JSONArray();
mSelectionArgs[0] = key;
//Cursor details = managedQuery(Data.CONTENT_URI, PROJECTION, SELECTION, mSelectionArgs, SORT_ORDER);
Cursor details = getApplicationContext().getContentResolver().query(Data.CONTENT_URI, PROJECTION, SELECTION, mSelectionArgs, SORT_ORDER);
//initialize null variables
name = null;
lastName = null;
middleName = null;
organization = null;
while(details.moveToNext()){
String mimeType = details.getString(MIME_TYPE_INDEX);
if(mimeType.equals(ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE)){
name = details.getString(GIVEN_NAME_INDEX);
lastName = details.getString(FAMILY_NAME_INDEX);
middleName = details.getString(MIDDLE_NAME_INDEX);
}
else if(mimeType.equals(ContactsContract.CommonDataKinds.Organization.CONTENT_ITEM_TYPE)){
organization = details.getString(ORGANIZATION_INDEX);
}
else if(mimeType.equals(ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE)){
phoneJSON = new JSONObject();
String phoneNumber = details.getString(PHONE_NUMBER_INDEX);
int type = details.getInt(PHONE_TYPE_INDEX);
String typeLabel = phoneTypeMap.get(String.valueOf(type));
if (typeLabel == null) {
typeLabel = details.getString(PHONE_LABEL_INDEX);
}
phoneJSON.put("ptype", typeLabel);
phoneJSON.put("number", phoneNumber);
phonesArray.put(phoneJSON);
}
else if(mimeType.equals(ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE)){
emailJSON = new JSONObject();
String email = details.getString(EMAIL_INDEX);
int type = details.getInt(EMAIL_TYPE_INDEX);
String typeLabel = emailTypeMap.get(String.valueOf(type));
if (typeLabel == null) {
typeLabel = details.getString(EMAIL_LABEL_INDEX);
}
emailJSON.put("etype", typeLabel);
emailJSON.put("address",email);
emailsArray.put(emailJSON);
}
}
contactJSON.put("firstname", name==null?"null":name);
contactJSON.put("middlename", middleName==null?"null":middleName);
contactJSON.put("lastname", lastName==null?"null":lastName);
contactJSON.put("organization", organization==null?"null":organization);
contactJSON.put("phones", phonesArray);
contactJSON.put("emails", emailsArray);
contactsArray.put(contactJSON);
details.close();
++current;
updateProgress(current);
}
root.put("contacts", contactsArray);
Log.d("SynchContactActivity", "Time 1: " + java.text.DateFormat.getDateTimeInstance().format(Calendar.getInstance().getTime()));
mHandler.post(new Runnable() {
#Override
public void run() {
if(mProgressDialog != null){
mProgressDialog.setMessage(messageCompress);
}
}
});
// to compress
String json_doc = root.toString();
byte[] compressed = compress(json_doc);
mHandler.post(new Runnable() {
#Override
public void run() {
if(mProgressDialog != null){
mProgressDialog.setMessage(messageUpload);
}
}
});
return compressed;
}
This code is too slow - that reads 3-4 contacts per second on average. Is this normal or can be optimized?
I think projection might be a good candidate to be optimized but I'm not sure.
Thanks in advance.
It's hard for me to tell exactly what you're trying to do, but it looks like you're trying to read data from the Contacts Provider and send it to a server using JSON. I suggest you look at the ContactsContract.RawContacts.Entity table, which contains all the data you're probably looking for without the mess of trying to figure out the MIME type of the DATA row you've just retrieved. You're certainly slowing down your app by getting the entire contents of the DATA row.
In addition, you should use a SyncAdapter to do this work. See Transferring Data Using Sync Adapters
Reading contacts can be made in 2-5 seconds. See the example app here
Source code attached
It is already asked but i didn't find any solution. For bluetooth application i am using the bluetoothShare.class .
My source code for sending the file to the target device
MainActvity.class:
Set<BluetoothDevice> devices = btAdapter
.getBondedDevices();
final String btDeviceName = selected_deviceName;
BluetoothDevice device = null;
for (BluetoothDevice itDevice : devices) {
if (btDeviceName.equals(itDevice.getName())) {
device = itDevice;
}
}
if (device != null) {
ContentValues values = new ContentValues();
values.put(BluetoothShare.URI, uri.toString());
values.put(BluetoothShare.MIMETYPE, "image/jpeg");
values.put(BluetoothShare.DESTINATION,
device.getAddress());
values.put(BluetoothShare.DIRECTION,
BluetoothShare.DIRECTION_OUTBOUND);
Long ts = System.currentTimeMillis();
values.put(BluetoothShare.TIMESTAMP, ts);
final Uri contentUri = getApplicationContext()
.getContentResolver().insert(
BluetoothShare.CONTENT_URI, values);
Log.v(TAG, "Insert contentUri: " + contentUri
+ " to device: " + device.getName());
Toast.makeText(getApplicationContext(), "Success",
Toast.LENGTH_LONG).show();
} else {
textStatus
.setText("Bluetooth remote device not found");
}
} else {
textStatus.setText("Bluetooth not activated");
}
}
else {
Toast.makeText(getApplicationContext(), "No devices found",
Toast.LENGTH_LONG).show();
}
and the blueToothShare.class:
package process.bluetooth.sendfile.opp;
import android.net.Uri;
import android.provider.BaseColumns;
public final class BluetoothShare implements BaseColumns {
private BluetoothShare() {
}
public static final String PERMISSION_ACCESS = "android.permission.ACCESS_BLUETOOTH_SHARE";
public static final Uri CONTENT_URI = Uri
.parse("content://com.android.bluetooth.opp/btopp");
public static final String TRANSFER_COMPLETED_ACTION = "android.btopp.intent.action.TRANSFER_COMPLETE";
public static final String INCOMING_FILE_CONFIRMATION_REQUEST_ACTION = "android.btopp.intent.action.INCOMING_FILE_NOTIFICATION";
public static final String USER_CONFIRMATION_TIMEOUT_ACTION = "android.btopp.intent.action.USER_CONFIRMATION_TIMEOUT";
public static final String URI = "uri";
public static final String FILENAME_HINT = "hint";
public static final String _DATA = "_data";
public static final String MIMETYPE = "mimetype";
public static final String DIRECTION = "direction";
public static final String DESTINATION = "destination";
public static final String VISIBILITY = "visibility";
public static final String USER_CONFIRMATION = "confirm";
public static final String STATUS = "status";
public static final String TOTAL_BYTES = "total_bytes";
public static final String CURRENT_BYTES = "current_bytes";
public static final String TIMESTAMP = "timestamp";
public static final int DIRECTION_OUTBOUND = 0;
public static final int DIRECTION_INBOUND = 1;
public static final int USER_CONFIRMATION_PENDING = 0;
public static final int USER_CONFIRMATION_CONFIRMED = 1;
public static final int USER_CONFIRMATION_AUTO_CONFIRMED = 2;
public static final int USER_CONFIRMATION_DENIED = 3;
public static final int USER_CONFIRMATION_TIMEOUT = 4;
public static final int VISIBILITY_VISIBLE = 0;
public static final int VISIBILITY_HIDDEN = 1;
public static boolean isStatusInformational(int status) {
return (status >= 100 && status < 200);
}
public static boolean isStatusSuspended(int status) {
return (status == STATUS_PENDING);
}
public static boolean isStatusSuccess(int status) {
return (status >= 200 && status < 300);
}
public static boolean isStatusError(int status) {
return (status >= 400 && status < 600);
}
public static boolean isStatusClientError(int status) {
return (status >= 400 && status < 500);
}
public static boolean isStatusServerError(int status) {
return (status >= 500 && status < 600);
}
public static boolean isStatusCompleted(int status) {
return (status >= 200 && status < 300)
|| (status >= 400 && status < 600);
}
public static final int STATUS_PENDING = 190;
public static final int STATUS_RUNNING = 192;
public static final int STATUS_SUCCESS = 200;
public static final int STATUS_BAD_REQUEST = 400;
public static final int STATUS_FORBIDDEN = 403;
public static final int STATUS_NOT_ACCEPTABLE = 406;
public static final int STATUS_LENGTH_REQUIRED = 411;
public static final int STATUS_PRECONDITION_FAILED = 412;
public static final int STATUS_CANCELED = 490;
public static final int STATUS_UNKNOWN_ERROR = 491;
public static final int STATUS_FILE_ERROR = 492;
public static final int STATUS_ERROR_NO_SDCARD = 493;
public static final int STATUS_ERROR_SDCARD_FULL = 494;
public static final int STATUS_UNHANDLED_OBEX_CODE = 495;
public static final int STATUS_OBEX_DATA_ERROR = 496;
public static final int STATUS_CONNECTION_ERROR = 497;
}
BluetoothShare class not supported android 4.1 and above. you can use the following intent coding to send file in android version 4.1 and above
Intent intent = new Intent();
intent.setAction(Intent.ACTION_SEND);
intent.setComponent(new ComponentName(
"com.android.bluetooth",
"com.android.bluetooth.opp.BluetoothOppLauncherActivity"));
intent.setType("image/jpeg");
file = new File(filepath);
intent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(file));
startActivity(intent);
and also some devices in Android v 2.2/2.3 not send the file via bluetoothShare class.
Maybe you can try another solution with BufferedWriter and BufferedReader.
Here is a snipped code:
BluetoothDevice mmDevice;
Set<BluetoothDevice> mBluetoothAdapter;
BluetoothAdapter bAdapter = BluetoothAdapter
.getDefaultAdapter();
mBluetoothAdapter = bAdapter.getBondedDevices();
for (BluetoothDevice bc : mBluetoothAdapter) {
if (bc.getName().indexOf("name_of_bluetoothdevide") != -1) {
UUID uuid = UUID
.fromString("00001101-0000-1000-8000-00805F9B34FB"); // Standard
// SerialPortService
// ID
mmDevice = bc;
BluetoothSocket mmSocket = mmDevice
.createInsecureRfcommSocketToServiceRecord(uuid);
bAdapter.cancelDiscovery();
mmSocket.connect();
BufferedWriter Writer = new BufferedWriter(
new OutputStreamWriter(
mmSocket.getOutputStream()));
Writer.write("Bluetooth connected!");
Writer.flush();
app.setmSocket(mmSocket);
break;
}
}
And for reading:
BufferedReader Reader = new BufferedReader(
new InputStreamReader(mmSocket.getInputStream()));
receivedMsg = Reader.readLine();
Hope it can help you.
This code works with firmware from MediaTek. Tested on Android 4.0.4. Sends the file, without asking anything from the user
public boolean SendFileViaBluetoothOPP(String file_path, String destinationMAC){
BluetoothAdapter btadapter = BluetoothAdapter.getDefaultAdapter();
if(btadapter == null)
return false;
BluetoothDevice btdev = btadapter.getRemoteDevice(destinationMAC);
if(btdev == null)
return false;
Uri uri = Uri.fromFile(new File(file_path));
Intent shareIntent = new Intent(Intent.ACTION_SEND)
.putExtra(Intent.EXTRA_STREAM, uri)
.setType("application/zip");
List<ResolveInfo> resolvedActivities = getPackageManager().queryIntentActivities(shareIntent, 0);
boolean found = false;
for(ResolveInfo actInfo: resolvedActivities){
if(actInfo.activityInfo.packageName.equals("com.mediatek.bluetooth"))
{
shareIntent.setComponent( new ComponentName(actInfo.activityInfo.packageName, actInfo.activityInfo.name ) );
shareIntent.putExtra("com.mediatek.bluetooth.sharegateway.extra.DEVICE_ADDRESS", btdev);
shareIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
found = true;
break;
}
}
if(found){
startActivity(shareIntent);
return true;
}
return false;
}
On older phone from MediaTek with Android 2.2.1 this code launches BluetoothDevicePicker to complete the operation.
Maybe this could help you in some way…
private void sendData(String message) {
byte[] msgBuffer = message.getBytes();
Log.d(TAG, "...Sending data: " + message + "...");
try {
outStream.write(msgBuffer);
} catch (IOException e) {
String msg = "In onResume() and an exception occurred during write: " + e.getMessage();
if (address.equals("00:00:00:00:00:00"))
msg = msg + ".\n\nUpdate your server address from 00:00:00:00:00:00 to the correct address on java code";
msg = msg + ".\n\nCheck that the SPP UUID: " + MY_UUID.toString() + " exists on server.\n\n";
errorExit("Fatal Error", msg);
}
}