I have two images male and female. I want to set image male if my gender is contains male and set image female if my gender is contains female.
The string gender is getting from JSON array.
Here is my code.
public class Profile extends AppCompatActivity {
JSONArray jsonarray = null;
JSONParser jsonParser = new JSONParser();
private static final String TAG_ID= "id";
private static final String TAG_PROFILE= "user";
private static final String TAG_NAME = "name";
private static final String TAG_MOB = "phn_number";
private static final String TAG_PER_ADD= "permanent_address";
private static final String TAG_PRE_ADD = "present_address";
private static final String TAG_OFF_ADD = "office_address";
private static final String TAG_MRG_ANN = "anniversary";
private static final String TAG_CITY = "city";
private static final String TAG_DOB = "dob";
private static final String TAG_NATIONALITY = "nationality";
private static final String TAG_OCC = "occupation";
private static final String TAG_MRG_STATUS = "martial_status";
private static final String TAG_GENDER = "gender";
private static final String TAG_NOY = "no_of_years";
private static String TAG_EMAIL = "email";
ListView list;
TextView name, mobile, permanent_add, present_add, office_add,mrg_anni,city,date_of_birth,nationality,occupation,mrd_status,gender,no_of_yr,email;
ArrayList<HashMap<String, String>> profile;
ImageView male,female;
private ProgressDialog pDialog;
String url = "http://app.goholidays.info/user_login.php";
String uid;
View view;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.my_profile);
profile = new ArrayList<HashMap<String, String>>();
list = (ListView) findViewById(android.R.id.list);
male = (ImageView) findViewById(R.id.profileimagemale);
female = (ImageView) findViewById(R.id.profileimagefemale);
name = (TextView) findViewById(R.id.name);
mobile = (TextView) findViewById(R.id.mob);
permanent_add = (TextView) findViewById(R.id.permanent_add);
present_add = (TextView) findViewById(R.id.present_add);
office_add = (TextView) findViewById(R.id.office_add);
mrg_anni = (TextView) findViewById(R.id.mrg_anni);
city = (TextView) findViewById(R.id.city);
date_of_birth = (TextView) findViewById(R.id.dob);
nationality = (TextView) findViewById(R.id.nationality);
occupation = (TextView) findViewById(R.id.o);
mrd_status = (TextView) findViewById(R.id.mrd_status);
gender = (TextView) findViewById(R.id.gender);
no_of_yr = (TextView) findViewById(R.id.no_of_years);
email = (TextView) findViewById(R.id.email);
new ReadJSON().execute();
}
private class ReadJSON extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(Profile.this);
pDialog.setMessage("Loading Profile ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected String doInBackground(String... param) {
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(Profile.this);
//String post_email = sp.getString("email", TAG_EMAIL);
String post_id = sp.getString("id",uid);
List<NameValuePair> params = new ArrayList<NameValuePair>();
//params.add(new BasicNameValuePair("email", post_email));
params.add(new BasicNameValuePair("id",post_id));
// getting JSON string from URL
JSONObject json = jsonParser.makeHttpRequest(url, "GET", params);
// Check your log cat for JSON response
try {
jsonarray = json.getJSONArray(TAG_PROFILE);
// looping through All Products
for (int i = 0; i < jsonarray.length(); i++) {
JSONObject jsonobject = jsonarray.getJSONObject(i);
// Storing each json item in variable
uid = jsonobject.getString(TAG_ID);
String name = jsonobject.getString(TAG_NAME);
String phn_number = jsonobject.getString(TAG_MOB);
String permanent_address = jsonobject.getString(TAG_PER_ADD);
String present_address = jsonobject.getString(TAG_PRE_ADD);
String office_address = jsonobject.getString(TAG_OFF_ADD);
String anniversary = jsonobject.getString(TAG_MRG_ANN);
String city = jsonobject.getString(TAG_CITY);
String dob = jsonobject.getString(TAG_DOB);
String nationality = jsonobject.getString(TAG_NATIONALITY);
String occupation = jsonobject.getString(TAG_OCC);
String martial_status = jsonobject.getString(TAG_MRG_STATUS);
final String gender = jsonobject.getString(TAG_GENDER);
String no_of_years = jsonobject.getString(TAG_NOY);
String email = jsonobject.getString(TAG_EMAIL);
// creating new HashMap
HashMap<String, String> contact = new HashMap<String, String>();
// adding each child node to HashMap key => value
contact.put(TAG_ID, uid);
contact.put(TAG_NAME, StringUtils.capitalize(name.toLowerCase().trim()));
contact.put(TAG_MOB, phn_number);
contact.put(TAG_PER_ADD, permanent_address);
contact.put(TAG_PRE_ADD, present_address);
contact.put(TAG_OFF_ADD, office_address);
contact.put(TAG_MRG_ANN, anniversary);
contact.put(TAG_CITY, city);
contact.put(TAG_DOB, dob);
contact.put(TAG_NATIONALITY, nationality);
contact.put(TAG_OCC, occupation);
contact.put(TAG_MRG_STATUS, StringUtils.capitalize(martial_status.toLowerCase().trim()));
contact.put(TAG_GENDER, StringUtils.capitalize(gender.toLowerCase().trim()));
runOnUiThread(new Runnable() {
#Override
public void run() {
if (gender.equalsIgnoreCase("male"))
{
male.setVisibility(View.VISIBLE);
female.setVisibility(View.INVISIBLE);
}else{
male.setVisibility(View.INVISIBLE);
female.setVisibility(View.VISIBLE);
}
}
});
contact.put(TAG_NOY, no_of_years+" Years");
contact.put(TAG_EMAIL, email);
// adding HashList to ArrayList
profile.add(contact);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
runOnUiThread(new Runnable() {
public void run() {
ListAdapter adapter = new SimpleAdapter(
Profile.this, profile,
R.layout.newpage, new String[] {TAG_NAME, TAG_MOB, TAG_PER_ADD, TAG_PRE_ADD, TAG_OFF_ADD, TAG_MRG_ANN, TAG_CITY, TAG_DOB, TAG_NATIONALITY, TAG_OCC, TAG_MRG_STATUS, TAG_GENDER, TAG_NOY, TAG_EMAIL},
new int[] {R.id.name, R.id.mob, R.id.permanent_add, R.id.present_add, R.id.office_add, R.id.mrg_anni, R.id.city, R.id.dob, R.id.nationality, R.id.o, R.id.mrd_status, R.id.gender, R.id.no_of_years, R.id.email });
list.setAdapter(adapter);
}
});
//SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
//SharedPreferences.Editor editor = prefs.edit();
//editor.putString("id",uid);
//editor.commit();
pDialog.dismiss();
}
}
}
and my xml file
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_weight="1.2"
android:layout_gravity="center"
android:weightSum="1">
<RelativeLayout
android:layout_weight="1.2"
android:layout_width="match_parent"
android:layout_height="0dp">
<ImageView
android:layout_width="#dimen/_110sdp"
android:layout_height="#dimen/_121sdp"
android:src="#drawable/male"
android:id="#+id/profileimagemale"
android:contentDescription="#string/app_name" />
<ImageView
android:layout_width="#dimen/_110sdp"
android:layout_height="#dimen/_121sdp"
android:src="#drawable/female"
android:id="#+id/profileimagefemale"
android:contentDescription="#string/app_name" />
</RelativeLayout>
<View
android:id="#+id/view1"
android:layout_width="#dimen/_110sdp"
android:layout_height="#dimen/_1sdp"
android:layout_marginTop="#dimen/_2sdp"
android:background="#E6E6E6" />
<LinearLayout
android:id="#+id/ll11"
android:layout_width="#dimen/_110sdp"
android:layout_height="wrap_content"
android:layout_marginLeft="#dimen/_10sdp"
android:layout_marginTop="#dimen/_5sdp"
android:orientation="horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="SEX:"
android:gravity="center"/>
<TextView
android:textColor="#000"
android:layout_marginLeft="#dimen/_5sdp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/gender"/>
</LinearLayout>
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_weight="1.8"
android:layout_gravity="center">
<LinearLayout
android:id="#+id/ll01"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="#dimen/_5sdp"
android:layout_marginRight="#dimen/_10sdp"
android:orientation="vertical">
<TextView
android:drawableLeft="#drawable/faculties"
android:drawablePadding="#dimen/_10sdp"
android:gravity="center"
android:textColor="#000"
android:hint="000"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/name"/>
</LinearLayout>
.........continued...................................
I am getting error nullpointerexception here is my logcat
FATAL EXCEPTION: main
java.lang.NullPointerException
at com.hotel.yasmeenshaikh.GoHolidays.Profile$ReadJSON$1.run(Profile.java:156)
at android.os.Handler.handleCallback(Handler.java:615)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4918)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:807)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:574)
at dalvik.system.NativeStart.main(Native Method)
Please help me solve this issue.
line number 156 is male.setVisibility(View.VISIBLE);
Call new ReadJSON().execute(); after all views are initialized. Because it is executed before your views initialization.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.my_profile);
profile = new ArrayList<HashMap<String, String>>();
list = (ListView) findViewById(android.R.id.list);
male = (ImageView) findViewById(R.id.profileimagemale);
female = (ImageView) findViewById(R.id.profileimagefemale);
name = (TextView) findViewById(R.id.name);
mobile = (TextView) findViewById(R.id.mob);
permanent_add = (TextView) findViewById(R.id.permanent_add);
present_add = (TextView) findViewById(R.id.present_add);
office_add = (TextView) findViewById(R.id.office_add);
mrg_anni = (TextView) findViewById(R.id.mrg_anni);
city = (TextView) findViewById(R.id.city);
date_of_birth = (TextView) findViewById(R.id.dob);
nationality = (TextView) findViewById(R.id.nationality);
occupation = (TextView) findViewById(R.id.o);
mrd_status = (TextView) findViewById(R.id.mrd_status);
gender = (TextView) findViewById(R.id.gender);
no_of_yr = (TextView) findViewById(R.id.no_of_years);
email = (TextView) findViewById(R.id.email);
new ReadJSON().execute(); // Call here
}
Related
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 4 years ago.
I am trying to select the first index in listview on first load onCreate. I've try the listView.setSelection(0) but some error occur. this is my code...
public class QandAPractice extends AppCompatActivity {
String qsid;
ListView listView;
ArrayList<String> myqid;
RadioButton r1,r2,r3,r4;
String txtcontent, txtTimer,txtAnskey,txtImg, txtA, txtB, txtC, txtD, txtID;
private static final String TAG_QID = "id";
private static final String TAG_TITLE = "content";
private static final String TAG_TIMER = "timer";
private static final String TAG_IMAGE = "images";
private static final String TAG_QSID = "qsid";
private static final String TAG_KEY = "key";
private static final String TAG_A = "A";
private static final String TAG_B = "B";
private static final String TAG_C = "C";
private static final String TAG_D = "D";
ArrayList<HashMap<String, String>> questions;
Dialog quizDialog;
public int i = 60;
public int loadindex = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_qand_apractice);
questions = new ArrayList<>();
myqid = new ArrayList<>();
Bundle b = getIntent().getExtras();
setTitle(b.getString("subject"));
qsid = b.getString("qsid");
quizDialog = new Dialog(this,android.R.style.Theme_Black_NoTitleBar_Fullscreen);
listView = findViewById(R.id.lvquestions);
getJSON(Constants.ROOT_URL+"mobile_question_index.php?qsid="+qsid);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
txtID = ((TextView) view.findViewById(R.id.quiz_id)).getText()
.toString();
txtcontent = ((TextView) view.findViewById(R.id.quiz_content)).getText()
.toString();
txtTimer = ((TextView) view.findViewById(R.id.quiz_timer)).getText()
.toString();
txtAnskey = ((TextView) view.findViewById(R.id.quiz_key)).getText()
.toString();
txtA = ((TextView) view.findViewById(R.id.quiz_A)).getText()
.toString();
txtB = ((TextView) view.findViewById(R.id.quiz_B)).getText()
.toString();
txtC = ((TextView) view.findViewById(R.id.quiz_C)).getText()
.toString();
txtD = ((TextView) view.findViewById(R.id.quiz_D)).getText()
.toString();
txtImg = ((TextView) view.findViewById(R.id.quiz_image)).getText()
.toString();
showQuiz();
}
});
listView.setSelection(0);
listView.getSelectedView().setSelected(true);
}
private void getJSON(final String urlWebService) {
class GetJSON extends AsyncTask<Void, Void, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
try {
loadIntoListView(s);
} catch (JSONException e) {
e.printStackTrace();
}
}
#Override
protected String doInBackground(Void... voids) {
try {
URL url = new URL(urlWebService);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
StringBuilder sb = new StringBuilder();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));
String json;
while ((json = bufferedReader.readLine()) != null) {
sb.append(json + "\n");
}
return sb.toString().trim();
} catch (Exception e) {
return null;
}
}
}
GetJSON getJSON = new GetJSON();
getJSON.execute();
}
private void loadIntoListView(String json) throws JSONException {
JSONArray jsonArray = new JSONArray(json);
//String[] question = new String[jsonArray.length()];
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject obj = jsonArray.getJSONObject(i);
String id = obj.getString(TAG_QID);
String content = obj.getString(TAG_TITLE);
String image = obj.getString(TAG_IMAGE);
String a = obj.getString(TAG_A);
String b = obj.getString(TAG_B);
String c = obj.getString(TAG_C);
String d = obj.getString(TAG_D);
String key = obj.getString(TAG_KEY);
String timer = obj.getString(TAG_TIMER);
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_QID,id);
map.put(TAG_TITLE,content);
map.put(TAG_IMAGE,image);
map.put(TAG_A,a);
map.put(TAG_B,b);
map.put(TAG_C,c);
map.put(TAG_D,d);
map.put(TAG_KEY,key);
map.put(TAG_TIMER,timer);
myqid.add(id);
questions.add(map);
}
// ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, question);
SimpleAdapter adapter = new SimpleAdapter(
QandAPractice.this, questions,
R.layout.quizlayout, new String[]{TAG_QID,
TAG_TITLE, TAG_IMAGE,TAG_A,TAG_B,TAG_C,TAG_D,TAG_KEY,TAG_TIMER},
new int[]{R.id.quiz_id, R.id.quiz_content, R.id.quiz_image,R.id.quiz_A,R.id.quiz_B,
R.id.quiz_C,R.id.quiz_D,R.id.quiz_key,R.id.quiz_timer});
/* AtomicReference<ListAdapter> la =
new AtomicReference<>(new ListAdapter(getApplicationContext(), questions));*/
listView.setAdapter(adapter);
}
this is the Error fetch in debug logcat..
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.view.View.setSelected(boolean)' on a null object reference
at com.example.jhan08.engineeringexclusivereviewer.QandAPractice.onCreate(QandAPractice.java:90)
at android.app.Activity.performCreate(Activity.java:6351)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1114)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2470)
I've read some thread that has the same issue like mine. They use adapter to fix the issue but still in my case this error still occur. Any help is much appreciated.
Do Your Selection after you set Your Adapter to the Listview
private void loadIntoListView(String json) throws JSONException {
JSONArray jsonArray = new JSONArray(json);
//String[] question = new String[jsonArray.length()];
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject obj = jsonArray.getJSONObject(i);
String id = obj.getString(TAG_QID);
String content = obj.getString(TAG_TITLE);
String image = obj.getString(TAG_IMAGE);
String a = obj.getString(TAG_A);
String b = obj.getString(TAG_B);
String c = obj.getString(TAG_C);
String d = obj.getString(TAG_D);
String key = obj.getString(TAG_KEY);
String timer = obj.getString(TAG_TIMER);
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_QID,id);
map.put(TAG_TITLE,content);
map.put(TAG_IMAGE,image);
map.put(TAG_A,a);
map.put(TAG_B,b);
map.put(TAG_C,c);
map.put(TAG_D,d);
map.put(TAG_KEY,key);
map.put(TAG_TIMER,timer);
myqid.add(id);
questions.add(map);
}
// ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, question);
SimpleAdapter adapter = new SimpleAdapter(
QandAPractice.this, questions,
R.layout.quizlayout, new String[]{TAG_QID,
TAG_TITLE, TAG_IMAGE,TAG_A,TAG_B,TAG_C,TAG_D,TAG_KEY,TAG_TIMER},
new int[]{R.id.quiz_id, R.id.quiz_content, R.id.quiz_image,R.id.quiz_A,R.id.quiz_B,
R.id.quiz_C,R.id.quiz_D,R.id.quiz_key,R.id.quiz_timer});
/* AtomicReference<ListAdapter> la =
new AtomicReference<>(new ListAdapter(getApplicationContext(), questions));*/
listView.setAdapter(adapter);
listView.setSelection(0);
listView.getSelectedView().setSelected(true);
}
I think I got the main issue you have faced. You try to select an item before populating the list view. You need to set this after adapter added on the listview.
Add this lines after adding the adapter.
listView.setAdapter(adapter);
listView.setSelection(0);
listView.getSelectedView().setSelected(true);
or use
listView.setAdapter(adapter);
listView.setItemChecked(0, true)
This will show a toast message for first opening. This should be added after the adapter set.
Iterator myVeryOwnIterator = questions.get(0).keySet().iterator();
while(myVeryOwnIterator.hasNext()) {
String key=(String)myVeryOwnIterator.next();
String value=(String)meMap.get(key);
Toast.makeText(ctx, "Key: "+key+" Value: "+value, Toast.LENGTH_LONG).show();
}
I am new to android and stackoverflow so forgive if it sounds or reads silly. I have a listview of suppose 10 job details. The list consists of only the names of the jobs. When I tap on any name, I want to open two tabbed views. The first tab would contain further details of the job and the second tab would contain a data entry page which will take input from the user for storage. All the job details (names and further details) are parsed from a json string fetched from the web.
Now, I have created the listview and the details page (containing further details of a single job). But I can't implement the tabbed view on the details page, i.e., I can't make a normal activity tabbed. Please help.
Note: The job list page gets all the details too, but in the XML the visibility of all the details except the job name is kept at "gone".
Ijob.java (Job list activity)
package com.example.administrator.signin;
import com.example.administrator.signin.R;
import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ListActivity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.Settings;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
public class Ijob extends ListActivity {
private ProgressDialog pDialog;
// URL to get contacts JSON
// JSON Node names
private static final String TAG_CON_NO = "CONSUMER_NO";
private static final String TAG_MET_NO = "METER_NO";
private static final String TAG_REC_ON = "RECEIVED_ON";
private static final String TAG_CON_NAME = "CON_NAME";
//private static final String TAG_CON_CAT = "CON_CAT";
private static final String TAG_MET_RAT = "MET_RAT";
private static final String TAG_CON_ADD = "CON_ADD";
//private static final String TAG_CON_ACC_ADD = "CON_ACC_ADD";
private static final String TAG_COM_RSN = "COM_RSN";
private static final String TAG_M_REF = "M_REF";
private static final String TAG_M_DATE = "M_DATE";
// //private static final String TAG_CON_CAT = " ";
private static final String TAG_PREV_DATA = "PREV_DATA";
private static final String TAG_TELE_NO = "TELE_NO";
private static final String TAG_IE_DT_N_PRSNT_PREV_RDG = "IE_DT_N_PRSNT_PREV_RDG";
private static final String TAG_LCC_LRO_ROM = "LCC_LRO_ROM";
// Hashmap for ListView
ArrayList<HashMap<String, String>> jobList;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.ijob);
jobList = new ArrayList<HashMap<String, String>>();
ListView lv = getListView();
// Listview on item click listener
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String CONSUMER_NO = ((TextView) view.findViewById(R.id.CON_NO))
.getText().toString();
String METER_NO = ((TextView) view.findViewById(R.id.MET_NO))
.getText().toString();
String MET_RAT = ((TextView) view.findViewById(R.id.MET_RAT))
.getText().toString();
String REC_ON = ((TextView) view.findViewById(R.id.REC_ON))
.getText().toString();
String CON_NAME = ((TextView) view.findViewById(R.id.CON_NAME))
.getText().toString();
String CON_ADD = ((TextView) view.findViewById(R.id.CON_ADD))
.getText().toString();
String COM_RSN = ((TextView) view.findViewById(R.id.COM_RSN))
.getText().toString();
String M_REF = ((TextView) view.findViewById(R.id.M_REF))
.getText().toString();
String M_DATE = ((TextView) view.findViewById(R.id.M_DATE))
.getText().toString();
String PREV_DATA = ((TextView) view.findViewById(R.id.PREV_DATA)).getText().toString();
String TELE_NO = ((TextView) view.findViewById(R.id.TELE_NO))
.getText().toString();
String IE_DT_N_PRSNT_PREV_RDG = ((TextView) view.findViewById(R.id.IE_DT_N_PRSNT_PREV_RDG))
.getText().toString();
String LCC_LRO_ROM = ((TextView) view.findViewById(R.id.LCC_LRO_ROM))
.getText().toString();
// Starting single contact activity
Intent in = new Intent(getApplicationContext(),
SingleContactActivity.class);
in.putExtra(TAG_CON_NO, CONSUMER_NO);
in.putExtra(TAG_MET_NO, METER_NO);
in.putExtra(TAG_MET_RAT, MET_RAT);
in.putExtra(TAG_REC_ON, REC_ON);
in.putExtra(TAG_CON_NAME, CON_NAME);
in.putExtra(TAG_CON_ADD, CON_ADD);
in.putExtra(TAG_COM_RSN, COM_RSN);
in.putExtra(TAG_M_REF, M_REF);
in.putExtra(TAG_M_DATE, M_DATE);
in.putExtra(TAG_PREV_DATA, PREV_DATA);
in.putExtra(TAG_TELE_NO, TELE_NO);
in.putExtra(TAG_IE_DT_N_PRSNT_PREV_RDG, IE_DT_N_PRSNT_PREV_RDG);
in.putExtra(TAG_LCC_LRO_ROM, LCC_LRO_ROM);
startActivity(in);
}
});
// Calling async task to get json
new GetContacts().execute();
}
/**
* Async task class to get json by making HTTP call
* */
private class GetContacts extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(Ijob.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... arg0) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String aid = Settings.Secure.getString(getContentResolver(), Settings.Secure.ANDROID_ID);
String url = "http://00.00.00.00/fetch_emp_1.jsp?ecd=" + aid;
String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
// JSONObject jsonObj = new JSONObject(jsonStr);
JSONArray jobs = new JSONArray(jsonStr);
// Getting JSON Array node
// jobs = jsonObj.getJSONArray("");
// looping through All Contacts
for (int i = 0; i < jobs.length(); i++) {
JSONObject c = jobs.getJSONObject(i);
String CON_NO = c.getString(TAG_CON_NO);// +" - "+c.getString(TAG_CON_CAT);
String MET_NO = c.getString(TAG_MET_NO);
String MET_RAT = c.getString(TAG_MET_RAT);
String REC_ON = c.getString(TAG_REC_ON);
String CON_NAME = (i + 1) + " . " + c.getString(TAG_CON_NAME);
String CON_ADD = c.getString(TAG_CON_ADD); //+" "+c.getString(TAG_CON_ACC_ADD);
String COM_RSN = c.getString(TAG_COM_RSN);
String M_REF = c.getString(TAG_M_REF);
String M_DATE = c.getString(TAG_M_DATE);
String PREV_DATA = c.getString(TAG_PREV_DATA);
String TELE_NO = c.getString(TAG_TELE_NO);
String IE_DT_N_PRSNT_PREV_RDG = c.getString(TAG_IE_DT_N_PRSNT_PREV_RDG);
String LCC_LRO_ROM = c.getString(TAG_LCC_LRO_ROM);
// tmp hashmap for single contact
HashMap<String, String> contact = new HashMap<String, String>();
// adding each child node to HashMap key => value
contact.put(TAG_CON_NO, CON_NO);
contact.put(TAG_MET_NO, MET_NO);
contact.put(TAG_MET_RAT, MET_RAT);
contact.put(TAG_REC_ON, REC_ON);
contact.put(TAG_CON_NAME, CON_NAME);
contact.put(TAG_CON_ADD, CON_ADD);
contact.put(TAG_COM_RSN, COM_RSN);
contact.put(TAG_M_REF, M_REF);
contact.put(TAG_M_DATE, M_DATE);
contact.put(TAG_PREV_DATA, PREV_DATA);
contact.put(TAG_TELE_NO, TELE_NO);
contact.put(TAG_IE_DT_N_PRSNT_PREV_RDG, IE_DT_N_PRSNT_PREV_RDG);
contact.put(TAG_LCC_LRO_ROM, LCC_LRO_ROM);
// adding contact to contact list
jobList.add(contact);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
Ijob.this, jobList,
R.layout.list_item, new String[]{TAG_CON_NO, TAG_MET_NO, TAG_MET_RAT,
TAG_REC_ON, TAG_CON_NAME, TAG_CON_ADD, TAG_COM_RSN, TAG_M_REF, TAG_M_DATE, TAG_PREV_DATA, TAG_TELE_NO, TAG_IE_DT_N_PRSNT_PREV_RDG, TAG_LCC_LRO_ROM}, new int[]{R.id.CON_NO,
R.id.MET_NO, R.id.MET_RAT, R.id.REC_ON, R.id.CON_NAME, R.id.CON_ADD, R.id.COM_RSN, R.id.M_REF, R.id.M_DATE, R.id.PREV_DATA, R.id.TELE_NO, R.id.IE_DT_N_PRSNT_PREV_RDG, R.id.LCC_LRO_ROM});
setListAdapter(adapter);
}
}
}
And the single job details page is like this:
package com.example.administrator.signin;
import android.app.ActionBar;
import android.app.Activity;
import android.app.FragmentTransaction;
import android.content.Intent;
import android.os.Bundle;
import android.widget.TextView;
public class SingleContactActivity extends Activity {
// JSON node keys
private static final String TAG_CON_NO = "CONSUMER_NO";
private static final String TAG_MET_NO = "METER_NO";
private static final String TAG_REC_ON = "RECEIVED_ON";
private static final String TAG_CON_NAME = "CON_NAME";
private static final String TAG_CON_ADD = "CON_ADD";
private static final String TAG_COM_RSN = "COM_RSN";
private static final String TAG_MET_RAT = "MET_RAT";
private static final String TAG_M_REF = "M_REF";
private static final String TAG_M_DATE = "M_DATE";
//private static final String TAG_CON_CAT = " ";
private static final String TAG_PREV_DATA = "PREV_DATA";
private static final String TAG_TELE_NO = "TELE_NO";
private static final String TAG_IE_DT_N_PRSNT_PREV_RDG = "IE_DT_N_PRSNT_PREV_RDG";
private static final String TAG_LCC_LRO_ROM = "LCC_LRO_ROM";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_single_contact);
// getting intent data
Intent in = getIntent();
// Get JSON values from previous intent
String CON_NO = in.getStringExtra(TAG_CON_NO);
String MET_NO = in.getStringExtra(TAG_MET_NO);
String REC_ON = in.getStringExtra(TAG_REC_ON);
String CON_NAME = in.getStringExtra(TAG_CON_NAME);
String CON_ADD = in.getStringExtra(TAG_CON_ADD);
String COM_RSN = in.getStringExtra(TAG_COM_RSN);
String MET_RAT = in.getStringExtra(TAG_MET_RAT);
//String CON_CAT = in.getStringExtra(TAG_CON_CAT);
String MET_REF = in.getStringExtra(TAG_M_REF);
String M_DATE = in.getStringExtra(TAG_M_DATE);
String PREV_DATA = in.getStringExtra(TAG_PREV_DATA);
String IE_DT_N_PRSNT_PREV_RDG = in.getStringExtra(TAG_IE_DT_N_PRSNT_PREV_RDG);
String LCC_LRO_ROM = in.getStringExtra(TAG_LCC_LRO_ROM);
String TELE_NO = in.getStringExtra(TAG_TELE_NO);
//PARSING THE STRING ===================
String delims = "[;]";
String[] CON_NAME_tokens = CON_NAME.split(" . ");
String[] PREV_DATA_tokens = PREV_DATA.split(delims);
String[] MM_YY_1_final = PREV_DATA_tokens[0].split(":");
String[] MM_YY_2_tokens = PREV_DATA_tokens[1].split(delims);
String[] MM_YY_2_final = MM_YY_2_tokens[0].split(":");
String[] MM_YY_3_tokens = PREV_DATA_tokens[2].split(delims);
String[] MM_YY_3_final = MM_YY_3_tokens[0].split(":");
String[] MM_YY_4_tokens = PREV_DATA_tokens[3].split(delims);
String[] MM_YY_4_final = MM_YY_4_tokens[0].split(":");
String[] MM_YY_5_tokens = PREV_DATA_tokens[4].split(delims);
String[] MM_YY_5_final = MM_YY_5_tokens[0].split(":");
String[] MM_YY_6_tokens = PREV_DATA_tokens[5].split(delims);
String[] MM_YY_6_final = MM_YY_6_tokens[0].split(":");
String[] MM_YY_7_tokens = PREV_DATA_tokens[6].split(delims);
String[] MM_YY_7_final = MM_YY_7_tokens[0].split(":");
String[] MM_YY_8_tokens = PREV_DATA_tokens[7].split(delims);
String[] MM_YY_8_final = MM_YY_8_tokens[0].split(":");
String[] MM_YY_9_tokens = PREV_DATA_tokens[8].split(delims);
String[] MM_YY_9_final = MM_YY_9_tokens[0].split(":");
String[] MM_YY_10_tokens = PREV_DATA_tokens[9].split(delims);
String[] MM_YY_10_final = MM_YY_10_tokens[0].split(":");
String[] MM_YY_11_tokens = PREV_DATA_tokens[10].split(delims);
String[] MM_YY_11_final = MM_YY_11_tokens[0].split(":");
String[] MM_YY_12_tokens = PREV_DATA_tokens[11].split(delims);
String[] MM_YY_12_final = MM_YY_12_tokens[0].split(":");
String[] MM_YY_13_tokens = PREV_DATA_tokens[12].split(delims);
String[] MM_YY_13_final = MM_YY_13_tokens[0].split(":");
String[] MM_YY_14_tokens = PREV_DATA_tokens[13].split(delims);
String[] MM_YY_14_final = MM_YY_14_tokens[0].split(":");
String[] MM_YY_15_tokens = PREV_DATA_tokens[14].split(delims);
String[] MM_YY_15_final = MM_YY_15_tokens[0].split(":");
String[] MM_YY_16_tokens = PREV_DATA_tokens[15].split(delims);
String[] MM_YY_16_final = MM_YY_16_tokens[0].split(":");
String[] MM_YY_17_tokens = PREV_DATA_tokens[16].split(delims);
String[] MM_YY_17_final = MM_YY_17_tokens[0].split(":");
String[] MM_YY_18_tokens = PREV_DATA_tokens[17].split(delims);
String[] MM_YY_18_final = MM_YY_18_tokens[0].split(":");
String[] MM_YY_19_tokens = PREV_DATA_tokens[18].split(delims);
String[] MM_YY_19_final = MM_YY_18_tokens[0].split(":");
String[] MM_YY_20_tokens = PREV_DATA_tokens[19].split(delims);
String[] MM_YY_20_final = MM_YY_20_tokens[0].split(":");
String[] MM_YY_21_tokens = PREV_DATA_tokens[20].split(delims);
String[] MM_YY_21_final = MM_YY_21_tokens[0].split(":");
String[] MM_YY_22_tokens = PREV_DATA_tokens[21].split(delims);
String[] MM_YY_22_final = MM_YY_22_tokens[0].split(":");
String[] MM_YY_23_tokens = PREV_DATA_tokens[22].split(delims);
String[] MM_YY_23_final = MM_YY_23_tokens[0].split(":");
String[] MM_YY_24_tokens = PREV_DATA_tokens[23].split(delims);
String[] MM_YY_24_final = MM_YY_24_tokens[0].split(":");
String[] IE_DT_N_PRSNT_PREV_RDG_tokens =
IE_DT_N_PRSNT_PREV_RDG.split(delims);
String[] IE_date_final = IE_DT_N_PRSNT_PREV_RDG_tokens[0].split(":");
String[] Present_Rdg_tokens = IE_DT_N_PRSNT_PREV_RDG_tokens[1].split(delims);
String[] Present_Rdg_final = Present_Rdg_tokens[0].split(":");
String[] Last_Rdg_tokens = IE_DT_N_PRSNT_PREV_RDG_tokens[2].split(delims);
String[] Last_Rdg_final = Last_Rdg_tokens[0].split(":");
String[] LCC_LRO_ROM_tokens = LCC_LRO_ROM.split(delims);
String[] LCC_Act_final = LCC_LRO_ROM_tokens[0].split(":");
String[] Last_Read_On_tokens = LCC_LRO_ROM_tokens[1].split(delims);
String[] Last_Read_On_final = Last_Read_On_tokens[0].split(":");
String[] R_no_tokens = LCC_LRO_ROM_tokens[2].split(delims);
String[] R_no_final = R_no_tokens[0].split("\\s");
String[] O_no_tokens = LCC_LRO_ROM_tokens[3].split(delims);
String[] O_no_final = R_no_tokens[0].split("\\s");
String[] M_no_tokens = LCC_LRO_ROM_tokens[4].split(delims);
String[] M_no_final = R_no_tokens[0].split("\\s");
//END OF PARSING STRINGS==================
// Displaying all values on the screen
TextView lblMref = (TextView) findViewById(R.id.m_ref);
TextView lblMdate = (TextView) findViewById(R.id.m_date);
TextView lblRec_On = (TextView) findViewById(R.id.rec_on_label);
TextView lblCons_No = (TextView) findViewById(R.id.con_no_label);
TextView lblMet_No = (TextView) findViewById(R.id.met_no_label);
TextView lblCons_Name = (TextView) findViewById(R.id.con_name_label);
TextView lblCons_Addr = (TextView) findViewById(R.id.con_add_label);
TextView lblComp_Reason = (TextView) findViewById(R.id.com_rsn_label);
TextView lblMet_Rat = (TextView) findViewById(R.id.met_rat_label);
TextView lblCon_Cat = (TextView) findViewById(R.id.con_cat_label);
TextView lblTele_No = (TextView) findViewById(R.id.tele_no_label);
TextView lblIE_Date_final = (TextView) findViewById(R.id.IE_label);
TextView lblPresent_Rdng_final = (TextView) findViewById(R.id.present_reading_label);
TextView lblLast_Rdng_final = (TextView) findViewById(R.id.prev_reading_label);
TextView lblLCC_Act_final = (TextView) findViewById(R.id.lcc_action_label);
TextView lblLast_read_On_final = (TextView) findViewById(R.id.last_read_label);
TextView lblR_no_final = (TextView) findViewById(R.id.R_no_label);
TextView lblO_no_final = (TextView) findViewById(R.id.O_no_label);
TextView lblM_no_final = (TextView) findViewById(R.id.M_no_label);
TextView lblMMYY_1 = (TextView) findViewById(R.id.mm_yy_1);
TextView lblMMYY_2 = (TextView) findViewById(R.id.mm_yy_2);
TextView lblMMYY_3 = (TextView) findViewById(R.id.mm_yy_3);
TextView lblMMYY_4 = (TextView) findViewById(R.id.mm_yy_4);
TextView lblMMYY_5 = (TextView) findViewById(R.id.mm_yy_5);
TextView lblMMYY_6 = (TextView) findViewById(R.id.mm_yy_6);
TextView lblMMYY_7 = (TextView) findViewById(R.id.mm_yy_7);
TextView lblMMYY_8 = (TextView) findViewById(R.id.mm_yy_8);
TextView lblMMYY_9 = (TextView) findViewById(R.id.mm_yy_9);
TextView lblMMYY_10 = (TextView) findViewById(R.id.mm_yy_10);
TextView lblMMYY_11 = (TextView) findViewById(R.id.mm_yy_11);
TextView lblMMYY_12 = (TextView) findViewById(R.id.mm_yy_12);
TextView lblMMYY_13 = (TextView) findViewById(R.id.mm_yy_13);
TextView lblMMYY_14 = (TextView) findViewById(R.id.mm_yy_14);
TextView lblMMYY_15 = (TextView) findViewById(R.id.mm_yy_15);
TextView lblMMYY_16 = (TextView) findViewById(R.id.mm_yy_16);
TextView lblMMYY_17 = (TextView) findViewById(R.id.mm_yy_17);
TextView lblMMYY_18 = (TextView) findViewById(R.id.mm_yy_18);
TextView lblMMYY_19 = (TextView) findViewById(R.id.mm_yy_19);
TextView lblMMYY_20 = (TextView) findViewById(R.id.mm_yy_20);
TextView lblMMYY_21 = (TextView) findViewById(R.id.mm_yy_21);
TextView lblMMYY_22 = (TextView) findViewById(R.id.mm_yy_22);
TextView lblMMYY_23 = (TextView) findViewById(R.id.mm_yy_23);
TextView lblMMYY_24 = (TextView) findViewById(R.id.mm_yy_24);
TextView lblCont_1 = (TextView) findViewById(R.id.mm_yy_1_content);
TextView lblCont_2 = (TextView) findViewById(R.id.mm_yy_2_content);
TextView lblCont_3 = (TextView) findViewById(R.id.mm_yy_3_content);
TextView lblCont_4 = (TextView) findViewById(R.id.mm_yy_4_content);
TextView lblCont_5 = (TextView) findViewById(R.id.mm_yy_5_content);
TextView lblCont_6 = (TextView) findViewById(R.id.mm_yy_6_content);
TextView lblCont_7 = (TextView) findViewById(R.id.mm_yy_7_content);
TextView lblCont_8 = (TextView) findViewById(R.id.mm_yy_8_content);
TextView lblCont_9 = (TextView) findViewById(R.id.mm_yy_9_content);
TextView lblCont_10 = (TextView) findViewById(R.id.mm_yy_10_content);
TextView lblCont_11 = (TextView) findViewById(R.id.mm_yy_11_content);
TextView lblCont_12 = (TextView) findViewById(R.id.mm_yy_12_content);
TextView lblCont_13 = (TextView) findViewById(R.id.mm_yy_13_content);
TextView lblCont_14 = (TextView) findViewById(R.id.mm_yy_14_content);
TextView lblCont_15 = (TextView) findViewById(R.id.mm_yy_15_content);
TextView lblCont_16 = (TextView) findViewById(R.id.mm_yy_16_content);
TextView lblCont_17 = (TextView) findViewById(R.id.mm_yy_17_content);
TextView lblCont_18 = (TextView) findViewById(R.id.mm_yy_18_content);
TextView lblCont_19 = (TextView) findViewById(R.id.mm_yy_19_content);
TextView lblCont_20 = (TextView) findViewById(R.id.mm_yy_20_content);
TextView lblCont_21 = (TextView) findViewById(R.id.mm_yy_21_content);
TextView lblCont_22 = (TextView) findViewById(R.id.mm_yy_22_content);
TextView lblCont_23 = (TextView) findViewById(R.id.mm_yy_23_content);
TextView lblCont_24 = (TextView) findViewById(R.id.mm_yy_24_content);
lblMref.setText(MET_REF);
lblMdate.setText(M_DATE);
lblRec_On.setText(REC_ON);
lblCons_No.setText(CON_NO);
lblMet_No.setText(MET_NO);
lblCons_Name.setText(CON_NAME_tokens[1]);
lblCons_Addr.setText(CON_ADD);
lblComp_Reason.setText(COM_RSN);
lblMet_Rat.setText(MET_RAT);
// lblCon_Cat.setText(CON_CAT);
lblIE_Date_final.setText(IE_date_final[1]);
lblPresent_Rdng_final.setText(Present_Rdg_final[1]);
lblLast_Rdng_final.setText(Last_Rdg_final[1]);
lblLCC_Act_final.setText(LCC_Act_final[1]);
lblLast_read_On_final.setText(Last_Read_On_final[1]);
lblR_no_final.setText(R_no_final[2]);
lblO_no_final.setText(O_no_final[2]);
lblM_no_final.setText(M_no_final[2]);
lblTele_No.setText(TELE_NO);
lblMMYY_1.setText(MM_YY_1_final[0]);
lblMMYY_2.setText(MM_YY_2_final[0]);
lblMMYY_3.setText(MM_YY_3_final[0]);
lblMMYY_4.setText(MM_YY_4_final[0]);
lblMMYY_5.setText(MM_YY_5_final[0]);
lblMMYY_6.setText(MM_YY_6_final[0]);
lblMMYY_7.setText(MM_YY_7_final[0]);
lblMMYY_8.setText(MM_YY_8_final[0]);
lblMMYY_9.setText(MM_YY_9_final[0]);
lblMMYY_10.setText(MM_YY_10_final[0]);
lblMMYY_11.setText(MM_YY_11_final[0]);
lblMMYY_12.setText(MM_YY_12_final[0]);
lblMMYY_13.setText(MM_YY_13_final[0]);
lblMMYY_14.setText(MM_YY_14_final[0]);
lblMMYY_15.setText(MM_YY_15_final[0]);
lblMMYY_16.setText(MM_YY_16_final[0]);
lblMMYY_17.setText(MM_YY_17_final[0]);
lblMMYY_18.setText(MM_YY_18_final[0]);
lblMMYY_19.setText(MM_YY_19_final[0]);
lblMMYY_20.setText(MM_YY_20_final[0]);
lblMMYY_21.setText(MM_YY_21_final[0]);
lblMMYY_22.setText(MM_YY_22_final[0]);
lblMMYY_23.setText(MM_YY_23_final[0]);
lblMMYY_24.setText(MM_YY_24_final[0]);
lblCont_1.setText(MM_YY_1_final[1]);
lblCont_2.setText(MM_YY_2_final[1]);
lblCont_3.setText(MM_YY_3_final[1]);
lblCont_4.setText(MM_YY_4_final[1]);
lblCont_5.setText(MM_YY_5_final[1]);
lblCont_6.setText(MM_YY_6_final[1]);
lblCont_7.setText(MM_YY_7_final[1]);
lblCont_8.setText(MM_YY_8_final[1]);
lblCont_9.setText(MM_YY_9_final[1]);
lblCont_10.setText(MM_YY_10_final[1]);
lblCont_11.setText(MM_YY_11_final[1]);
lblCont_12.setText(MM_YY_12_final[1]);
lblCont_13.setText(MM_YY_13_final[1]);
lblCont_14.setText(MM_YY_14_final[1]);
lblCont_15.setText(MM_YY_15_final[1]);
lblCont_16.setText(MM_YY_16_final[1]);
lblCont_17.setText(MM_YY_17_final[1]);
lblCont_18.setText(MM_YY_18_final[1]);
lblCont_19.setText(MM_YY_19_final[1]);
lblCont_20.setText(MM_YY_20_final[1]);
lblCont_21.setText(MM_YY_21_final[1]);
lblCont_22.setText(MM_YY_22_final[1]);
lblCont_23.setText(MM_YY_23_final[1]);
lblCont_24.setText(MM_YY_24_final[1]);
}
}
I am loading pictures (below ~3MB in size) into Cardview from a database and it was infalte in Listviewstview.
The loading and browsing of these pictures is way too slow.
Is there any method to downscale these pictures to speed up & sometimes dispalyind [Duplicate] images on other card view?
cardview xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<android.support.v7.widget.CardView xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:id="#+id/cv"
android:layout_width="match_parent"
android:layout_height="140dp"
android:alpha="1"
android:layout_marginLeft="10dp"
android:layout_marginRight="10dp"
card_view:cardBackgroundColor="#FFFFFF"
card_view:cardCornerRadius="10dp">
<RelativeLayout
android:id="#+id/r1"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="#+id/img_product"
android:layout_width="90dp"
android:layout_height="90dp"
android:layout_marginLeft="#dimen/activity_vertical_margin"
android:layout_marginTop="20dp" />
<TextView
android:id="#+id/product_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="#+id/img_product"
android:layout_toEndOf="#+id/img_product"
android:layout_toRightOf="#+id/img_product"
android:inputType="textMultiLine"
android:text="Parvana Fancy Necklace Set"
android:textSize="18dp"
android:textStyle="bold" />
<TextView
android:id="#+id/txt_total"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/img_product"
android:layout_toEndOf="#+id/img_product"
android:layout_toRightOf="#+id/img_product"
android:text="RS.234"
android:textSize="20dp"
android:textStyle="bold" />
<Button
android:id="#+id/btn_remove"
android:layout_width="32dp"
android:layout_height="wrap_content"
android:background="#drawable/wishlistddelete_selector"
android:drawableLeft="#drawable/delete_icon"
android:layout_alignTop="#+id/txt_total"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true" />
</RelativeLayout>
</android.support.v7.widget.CardView>
</RelativeLayout>
listview xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#drawable/home_bground">
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<RelativeLayout
android:id="#+id/topbar1"
android:layout_width="match_parent"
android:layout_height="55dp"
android:background="#drawable/top">
<ImageView
android:id="#+id/btn_hme"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:src="#drawable/home_icon" />
<TextView
android:id="#+id/txt_pro_name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:gravity="center_horizontal"
android:text="Shopping Cart"
android:textColor="#ffffff"
android:textSize="18dp"
android:textStyle="bold" />
</RelativeLayout>
<ListView
android:id="#+id/list_item"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#id/topbar1"
android:animationCache="false"
android:dividerHeight="0dp"
android:listSelector="#00000000"
android:scrollingCache="false"
android:smoothScrollbar="true" />
</RelativeLayout>
</RelativeLayout>
by using sqllite access the data from database
public class Wishlist extends Activity {
Button checkout;
ListView ListCart;
String name, cusid, ffname, llname, phone, fax, password, email;
String[] qu, s;
int[] g;
int k = 0;
String cost;
ProgressDialog pDialog = null;
List<CartProducts> product_list;
Context ctx;
Integer pos = 0, total = 0, q = 0, gtot = 0, total1 = 0, sum = 0;
SQLiteDatabase FavData;
private Context context;
Integer i;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_modifywishlist);
Intent page1 = getIntent();
cusid = page1.getStringExtra("cus_id");
ffname = page1.getStringExtra("fname");
llname = page1.getStringExtra("lname");
phone = page1.getStringExtra("ph");
fax = page1.getStringExtra("fax");
password = page1.getStringExtra("password");
email = page1.getStringExtra("email");
ListCart = (ListView) findViewById(R.id.list_item);
ListCart.setScrollingCacheEnabled(false);
Intent page2 = getIntent();
i = page2.getIntExtra("kvalue",1);
pDialog = new ProgressDialog(this);
ctx = this;
FavData = Wishlist.this.openOrCreateDatabase("SHOPPING_CARTFAV", MODE_PRIVATE, null);
FavData.execSQL("CREATE TABLE IF NOT EXISTS fav_items(product_id varchar, name varchar, price varchar, quantity integer, model varchar, image varchar, manufacturer varchar )");
ArrayList<CartProducts> myList = new ArrayList<CartProducts>();
Cursor crsr = FavData.rawQuery("SELECT * FROM fav_items", null);
final String[] productID = new String[crsr.getCount()];
final String[] ProductName = new String[crsr.getCount()];
final String[] ProductPrice = new String[crsr.getCount()];
final String[] ProductQuantity = new String[crsr.getCount()];
final String[] ProductModel = new String[crsr.getCount()];
final String[] ProductImage = new String[crsr.getCount()];
final String[] ProductManufacturer = new String[crsr.getCount()];
int j = 0;
while (crsr.moveToNext()) {
String id = crsr.getString(crsr.getColumnIndex("product_id"));
productID[j] = id;//product_id,name,price,quantity,model,image,manufacturer
name = crsr.getString(crsr.getColumnIndex("name"));
ProductName[j] = name;
String price = crsr.getString(crsr.getColumnIndex("price"));
ProductPrice[j] = price;
String s = ProductPrice[j].toString();
s = s.replace(",", "");
String[] parts = s.split("\\."); // escape .
String part1 = parts[0];
String part2 = parts[1];
part1 = part1.replace("₹", "");
total = Integer.parseInt(part1); // Toast.makeText(Table.this, part1, Toast.LENGTH_SHORT).show();
String qnty = crsr.getString(crsr.getColumnIndex("quantity"));
ProductQuantity[j] = qnty;
String s2 = ProductQuantity[j].toString();
total1 = Integer.parseInt(s2);
sum = total * total1;
String model = crsr.getString(crsr.getColumnIndex("model"));
ProductModel[j] = model;
String image = crsr.getString(crsr.getColumnIndex("image"));
ProductImage[j] = image;
String manufacturer = crsr.getString(crsr.getColumnIndex("manufacturer"));
ProductManufacturer[j] = manufacturer;
myList.add(new CartProducts(productID[j], ProductName[j], ProductPrice[j], ProductQuantity[j], ProductModel[j], ProductImage[j], ProductManufacturer[j]));
gtot = gtot + sum;
j++;
}
ListCart.setAdapter(new Wishlist_Listadapter(ctx, R.layout.activity_wishlist_cartrow, myList));
String s1 = ProductPrice.toString();
}
}
adapter class
public class Wishlist_Listadapter extends ArrayAdapter<CartProducts> {
Bitmap bitmap;
ImageView img;
String urll, name,totalps;
SQLiteDatabase FavData;
Integer total = 0, quanty = 1, grandtot = 0, i = 0;
String it;
Button addbtn, minbtn;
EditText editqu;
int total1 = 0, quantity=0, fulltotal = 0, sum;
SQLiteOpenHelper dbhelper;
Wishlist_Listadapter cart = Wishlist_Listadapter.this;
private int resource;
private LayoutInflater inflater;
private Context context;
int count=1 ;
public Wishlist_Listadapter(Context ctx, int resourceId, List<CartProducts> objects) {
super(ctx, resourceId, objects);
resource = resourceId;
inflater = LayoutInflater.from(ctx);
context = ctx;
}
public View getView(int position, View convertView, ViewGroup parent) {
/* create a new view of my layout and inflate it in the row */
convertView = (RelativeLayout) inflater.inflate(resource, null);
final ViewHolder viewholder;
viewholder = new ViewHolder();
final CartProducts banqt = getItem(position);
totalps=(banqt.getPrice());
String s = totalps.toString();
s = s.replace(",", "");
String[] parts = s.split("\\."); // escape .
String part1 = parts[0];
String part2 = parts[1];
part1 = part1.replace("₹", "");// Toast.makeText(getContext(), part1, Toast.LENGTH_LONG).show();
total = Integer.parseInt(part1);
quanty = Integer.parseInt(banqt.getQuantity());
grandtot = total *quanty;
viewholder.total = (TextView) convertView.findViewById(R.id.txt_total);
viewholder.total.setText(String.valueOf(grandtot));
Button delet = (Button) convertView.findViewById(R.id.btn_remove);
delet.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
/*delete function*/
it = banqt.getProduct_id();
FavData = context.openOrCreateDatabase("SHOPPING_CARTFAV", context.MODE_PRIVATE, null);
FavData.execSQL("DELETE FROM fav_items WHERE product_id=" + it + ";");
Intent intent = ((Wishlist) context).getIntent();
((Wishlist) context).finish();
context.startActivity(intent);
}
});
viewholder.txtName = (TextView) convertView.findViewById(R.id.product_name);
viewholder.txtName.setText(banqt.getName());
img = (ImageView) convertView.findViewById(R.id.img_product);
urll = banqt.getImage().toString();
urll = urll.replaceAll(" ", "%20");// Toast.makeText(getContext(),urll,Toast.LENGTH_LONG).show();
new LoadImage().execute(urll);
return convertView;
}
static class ViewHolder {
TextView txtName;
TextView total;
EditText editqu;
TextView txtprice;
}
private class LoadImage extends AsyncTask<String, String, Bitmap> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
protected Bitmap doInBackground(String... args) {
try {
bitmap = BitmapFactory.decodeStream((InputStream) new URL(args[0]).getContent());
} catch (Exception e) {
e.printStackTrace();
}
return bitmap;
}
protected void onPostExecute(Bitmap image) {
if (image != null) {
img.setImageBitmap(image);
// pDialog.dismiss();
} else {
// pDialog.dismiss();
Toast.makeText(getContext(), "Image Does Not exist or Network Error", Toast.LENGTH_SHORT).show();
}
}
}
}
Try scale your bitmap to lower its actual resolution, I've used the following codes to reduce bitmap's size.
int nh = (int) (bitmap.getHeight() * (512.0 / bitmap.getWidth()));
Bitmap scaled = Bitmap.createScaledBitmap(bitmap, 512, nh, true);
For you case, add the following codes into your adapter class AsyncTask's doInBackground method
try {
bitmap = BitmapFactory.decodeStream((InputStream) new URL(args[0]).getContent());
int nh = (int) (bitmap.getHeight() * (512.0 / bitmap.getWidth()));
Bitmap scaled = Bitmap.createScaledBitmap(bitmap, 512, nh, true);
} catch (Exception e) {
e.printStackTrace();
}
return scaled;
Return scaled bitmap instead of original bitmap.
I have a listview where I have 50 elements being displayed. I have decided to paginate the view so on each part of the view there are 10 elements and then a next button is clicked to get to the next 10 elements. How can i set 10 data ? I follow this article
http://rakhi577.wordpress.com/2013/05/20/listview-pagination-ex-2/
Here is my code .Can you help me with my code or a link to a guide on how to implement this correctly?
public class MainActivity extends ListActivity {
Context context;
Button btnSearch ;
EditText txtSearch;
private ProgressDialog pDialog;
// URL to get contacts JSON
public int TOTAL_LIST_ITEMS = 50;
public int NUM_ITEMS_PAGE = 10;
private int noOfBtns;
private Button[] btns;
// JSON Node names
private static final String TAG_CONTACTS = "contacts";
private static final String TAG_ID = "id";
private static final String TAG_NAME = "name";
private static final String TAG_EMAIL = "email";
private static final String TAG_ADDRESS = "address";
private static final String TAG_GENDER = "gender";
private static final String TAG_PHONE = "phone";
private static final String TAG_PHONE_MOBILE = "mobile";
private static final String TAG_PHONE_HOME = "home";
private static final String TAG_PHONE_OFFICE = "office";
// contacts JSONArray
JSONArray contacts = null;
// Hashmap for ListView
ArrayList<HashMap<String, String>> contactList;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnSearch=(Button)findViewById(R.id.buttonSearch);
txtSearch=(EditText)findViewById(R.id.Searchtext);
}
public String gotourl()
{
final EditText txtSearch=(EditText)findViewById(R.id.Searchtext);
String ts=txtSearch.getText().toString();
String url = "http://latest.bloomapi.com/api/search?limit=50&offset=0&key1=last_name&op1=eq&value1="+ts;
return url ;
}
public void Searchfunction(View v)
{
Btnfooter();
//loadList(0);
CheckBtnBackGroud(0);
contactList = new ArrayList<HashMap<String, String>>();
ListView lv = getListView();
// Listview on item click listener
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// getting values from selected ListItem
String name = ((TextView) view.findViewById(R.id.name))
.getText().toString();
String cost = ((TextView) view.findViewById(R.id.email))
.getText().toString();
String description = ((TextView) view.findViewById(R.id.mobile))
.getText().toString();
// Starting single contact activity
Intent in = new Intent(getApplicationContext(),
SingleContactActivity.class);
in.putExtra(TAG_NAME, name);
in.putExtra(TAG_EMAIL, cost);
in.putExtra(TAG_PHONE_MOBILE, description);
startActivity(in);
}
});
// Calling async task to get json
new GetContacts().execute();
}
private void Btnfooter()
{
int val = TOTAL_LIST_ITEMS%NUM_ITEMS_PAGE;
val = val==0?0:1;
noOfBtns=TOTAL_LIST_ITEMS/NUM_ITEMS_PAGE+val;
LinearLayout ll = (LinearLayout)findViewById(R.id.btnLay);
btns =new Button[noOfBtns];
for(int i=0;i<noOfBtns;i++)
{
btns[i] = new Button(this);
btns[i].setBackgroundColor(getResources().getColor(android.R.color.transparent));
btns[i].setText(""+(i+1));
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
ll.addView(btns[i], lp);
final int j = i;
btns[j].setOnClickListener(new OnClickListener() {
public void onClick(View v)
{
//loadList(j);
CheckBtnBackGroud(j);
}
});
}
}
private void CheckBtnBackGroud(int index)
{
for(int i=0;i<noOfBtns;i++)
{
if(i==index)
{
btns[index].setBackgroundDrawable(getResources().getDrawable(R.drawable.box_green));
btns[i].setTextColor(getResources().getColor(android.R.color.white));
}
else
{
btns[i].setBackgroundColor(getResources().getColor(android.R.color.transparent));
btns[i].setTextColor(getResources().getColor(android.R.color.black));
}
}
}
private class GetContacts extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected 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(gotourl(), ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
contacts = jsonObj.getJSONArray("result");
// looping through All Contacts
for (int i = 0; i < contacts.length(); i++) {
Integer a = contacts.length();
Log.d("loop", a.toString());
JSONObject c = contacts.getJSONObject(i);
String id = c.getString("npi");
String name = c.getString("first_name");
String email = c.getString("last_name");
//String address = c.getString(TAG_ADDRESS);
String gender = c.getString("type");
// tmp hashmap for single contact
HashMap<String, String> contact = new HashMap<String, String>();
// adding each child node to HashMap key => value
contact.put("npi", id);
contact.put("first_name", name);
contact.put("last_name", email);
//contact.put(TAG_PHONE_MOBILE, mobile);
contact.put("type", gender);
// adding contact to contact list
contactList.add(contact);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.d("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
MainActivity.this, contactList,
R.layout.list_item, new String[] { "first_name", "last_name",
"type" }, new int[] { R.id.name,
R.id.email, R.id.mobile });
setListAdapter(adapter);
}
}}
I change the code. When i click next button[like 2,3,4,5]. showing first page data. Here is my modified code.Any help Appreciated :
public class MainActivity extends ListActivity {
private TextView title;
Context context;
Button btnSearch ;
EditText txtSearch;
private ListView listview;
private ProgressDialog pDialog;
// URL to get contacts JSON
public int TOTAL_LIST_ITEMS = 50;
public int NUM_ITEMS_PAGE = 10;
private int noOfBtns;
private Button[] btns;
// JSON Node names
private static final String TAG_CONTACTS = "contacts";
private static final String TAG_ID = "id";
private static final String TAG_NAME = "name";
private static final String TAG_EMAIL = "email";
private static final String TAG_ADDRESS = "address";
private static final String TAG_GENDER = "gender";
private static final String TAG_PHONE = "phone";
private static final String TAG_PHONE_MOBILE = "mobile";
private static final String TAG_PHONE_HOME = "home";
private static final String TAG_PHONE_OFFICE = "office";
// contacts JSONArray
JSONArray contacts = null;
// Hashmap for ListView
ArrayList<HashMap<String, String>> contactList;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnSearch=(Button)findViewById(R.id.buttonSearch);
txtSearch=(EditText)findViewById(R.id.Searchtext);
title = (TextView)findViewById(R.id.title);
}
public String gotourl()
{
final EditText txtSearch=(EditText)findViewById(R.id.Searchtext);
String ts=txtSearch.getText().toString();
String url = "http://latest.bloomapi.com/api/search?limit=50&offset=0&key1=last_name&op1=eq&value1="+ts;
return url ;
}
public void Searchfunction(View v)
{
Btnfooter();
CheckBtnBackGroud(0);
contactList = new ArrayList<HashMap<String, String>>();
ListView lv = getListView();
// Listview on item click listener
lv.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
if(position%2==0)
{
view.setBackgroundColor(Color.parseColor("#F4FA58"));
}else
{
view.setBackgroundColor(Color.parseColor("#DA81F5"));
}
// getting values from selected ListItem
String name = ((TextView) view.findViewById(R.id.name))
.getText().toString();
String cost = ((TextView) view.findViewById(R.id.email))
.getText().toString();
String description = ((TextView) view.findViewById(R.id.mobile))
.getText().toString();
// Starting single contact activity
Intent in = new Intent(getApplicationContext(),
SingleContactActivity.class);
in.putExtra(TAG_NAME, name);
in.putExtra(TAG_EMAIL, cost);
in.putExtra(TAG_PHONE_MOBILE, description);
startActivity(in);
}
});
// Calling async task to get json
new GetContacts().execute();
}
private void Btnfooter()
{
int val = TOTAL_LIST_ITEMS%NUM_ITEMS_PAGE;
val = val==0?0:1;
noOfBtns=TOTAL_LIST_ITEMS/NUM_ITEMS_PAGE+val;
LinearLayout ll = (LinearLayout)findViewById(R.id.btnLay);
btns =new Button[noOfBtns];
for(int i=0;i<noOfBtns;i++)
{
btns[i] = new Button(this);
btns[i].setBackgroundColor(getResources().getColor(android.R.color.transparent));
btns[i].setText(""+(i+1));
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
ll.addView(btns[i], lp);
final int j = i;
btns[j].setOnClickListener(new OnClickListener() {
public void onClick(View v)
{
new GetContacts().execute();
CheckBtnBackGroud(j);
}
});
}
}
private void CheckBtnBackGroud(int index)
{
title.setText("Page "+(index+1)+" of "+noOfBtns);
for(int i=0;i<noOfBtns;i++)
{
if(i==index)
{
btns[index].setBackgroundDrawable(getResources().getDrawable(R.drawable.box_green));
btns[i].setTextColor(getResources().getColor(android.R.color.white));
}
else
{
btns[i].setBackgroundColor(getResources().getColor(android.R.color.transparent));
btns[i].setTextColor(getResources().getColor(android.R.color.black));
}
}
}
private class GetContacts extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected 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(gotourl(), ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
int number = 0;
int start = number * NUM_ITEMS_PAGE;
// looping through All Contacts
// Getting JSON Array node
contacts = jsonObj.getJSONArray("result");
// looping through All Contacts
//for (int i = 0; i < contacts.length(); i++) {
for(int i=start;i<(start)+NUM_ITEMS_PAGE;i++) {
Integer a = contacts.length();
Log.d("loop", a.toString());
JSONObject c = contacts.getJSONObject(i);
String id = c.getString("npi");
String name = c.getString("first_name");
String email = c.getString("last_name");
String gender = c.getString("type");
// tmp hashmap for single contact
HashMap<String, String> contact = new HashMap<String, String>();
// adding each child node to HashMap key => value
contact.put("npi", id);
contact.put("first_name", name);
contact.put("last_name", email);
//contact.put(TAG_PHONE_MOBILE, mobile);
contact.put("type", gender);
// adding contact to contact list
contactList.add(contact);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.d("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
MainActivity.this, contactList,
R.layout.list_item, new String[] { "first_name", "last_name",
"type" }, new int[] { R.id.name,
R.id.email, R.id.mobile });
setListAdapter(adapter);
}
}}
Below is my code to show list view with pagination. There is two blue button for change pages.
You can customize according to you need.
Create UserCategory.java
package com.UserCategory;
import java.net.URL;
import java.util.ArrayList;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import android.app.Activity;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.ArrayAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
public class UserCategory extends Activity implements OnClickListener{
private final int PAGE_SIZE = 5;
private int StartingIndex = 0;
ArrayList<String> userClass=new ArrayList<String>();
int textlength=0;
private String lv_arr[];
private ListView lv1;
EditText searchText;
//Button Previous;
private String Machine[]={"Machine 1","Machine 2","Machine 3","Machine 4","Machine 5","Machine 6","Machine 7","Machine 8","Machine 9","Machine 10","Machine 11","Machine 12","Machine 1","Machine 2","Machine 3","Machine 4","Machine 5","Machine 6","Machine 7","Machine 8","Machine 9","Machine 10","Machine 11","Machine 12"};
ImageView next,Previous;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.getWindow().requestFeature(Window.FEATURE_NO_TITLE);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
setContentView(R.layout.main);
lv1=(ListView)findViewById(R.id.ListView01);
searchText=(EditText)findViewById(R.id.et_Serchlist);
next=(ImageView)findViewById(R.id.btn_next);
Previous=(ImageView)findViewById(R.id.btn_previous);
next.setOnClickListener(this);
Previous.setOnClickListener(this);
//parsing();
lv1.setAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1 , Machine));
changeListViewModel(0);
}
private void changelist(int startingIndex) {
if(startingIndex < 0) {
Previous=(ImageView)findViewById(R.id.btn_previous);
ImageView back=(ImageView)findViewById(R.id.btn_Whiteprevious);
back.setVisibility(1);
Previous.setVisibility(4);
startingIndex = 0;
}else if(startingIndex >= userClass.size())
startingIndex -= PAGE_SIZE;
StartingIndex = startingIndex;
int endingIndex = startingIndex + PAGE_SIZE;
System.out.println("ending index"+endingIndex);
if(StartingIndex!=0){
Previous=(ImageView)findViewById(R.id.btn_previous);
ImageView back=(ImageView)findViewById(R.id.btn_Whiteprevious);
back.setVisibility(4);
Previous.setVisibility(1);
}
if(endingIndex == userClass.size()){
ImageView Forward=(ImageView)findViewById(R.id.btn_grewforward);
Forward.setVisibility(1);
next=(ImageView)findViewById(R.id.btn_next);
next.setVisibility(4);
}
if(endingIndex != userClass.size()){
ImageView Forward=(ImageView)findViewById(R.id.btn_grewforward);
Forward.setVisibility(4);
next=(ImageView)findViewById(R.id.btn_next);
next.setVisibility(1);
}
if(endingIndex > userClass.size()) endingIndex = userClass.size();
try {
String[] subSet = getDataSubset1(startingIndex, endingIndex);
System.out.println("subSet array"+subSet);
lv1.setAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1 , subSet));
} catch (Exception e) {
e.printStackTrace();
}
}
private String[] getDataSubset1(int startingIndex, int endingIndex){
String[] changeList = new String[endingIndex - startingIndex];
int index = -1;
for(int x = startingIndex; x < endingIndex; x++)
changeList[++index] = userClass.get(x);
return changeList;
}
private void changeListViewModel(int startingIndex){
if(startingIndex < 0) {
Previous=(ImageView)findViewById(R.id.btn_previous);
ImageView back=(ImageView)findViewById(R.id.btn_Whiteprevious);
back.setVisibility(1);
Previous.setVisibility(4);
startingIndex = 0;
}
else if(startingIndex >= Machine.length){
startingIndex -= PAGE_SIZE;
}
System.out.println("strating"+startingIndex);
System.out.println("startingIndex"+startingIndex);
StartingIndex = startingIndex;
int endingIndex = startingIndex + PAGE_SIZE;
System.out.println("endingIndex"+endingIndex);
if(StartingIndex!=0)
{
Previous=(ImageView)findViewById(R.id.btn_previous);
ImageView back=(ImageView)findViewById(R.id.btn_Whiteprevious);
back.setVisibility(4);
Previous.setVisibility(1);
}
if(endingIndex == userClass.size()){
ImageView Forward=(ImageView)findViewById(R.id.btn_grewforward);
Forward.setVisibility(1);
next=(ImageView)findViewById(R.id.btn_next);
next.setVisibility(4);
}
if(endingIndex != userClass.size()){
ImageView Forward=(ImageView)findViewById(R.id.btn_grewforward);
Forward.setVisibility(4);
next=(ImageView)findViewById(R.id.btn_next);
next.setVisibility(1);
}
System.out.println("ending index"+endingIndex);
if(endingIndex > Machine.length) {
endingIndex = Machine.length;
ImageView Forward=(ImageView)findViewById(R.id.btn_grewforward);
Forward.setVisibility(1);
next=(ImageView)findViewById(R.id.btn_next);
next.setVisibility(4);
}
String[] subSet = getDataSubset(startingIndex, endingIndex);
System.out.println("subSet main array"+subSet.length);
lv1.setAdapter(new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1 , subSet));
}
private String[] getDataSubset(int startingIndex, int endingIndex){
String[] toRet = new String[endingIndex - startingIndex];
int index = -1;
System.out.println("index"+index);
for(int x = startingIndex; x < endingIndex; x++)
toRet[++index] = Machine[x];
return toRet;
}
private void parsing() {
// TODO Auto-generated method stub
try {
URL url = new URL("http://10.10.1.100/DogEventsWebService/EventService.svc/categories/1");
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(new InputSource(url.openStream()));
doc.getDocumentElement().normalize();
NodeList nodeList = doc.getElementsByTagName("UserCategory");
Machine = new String[nodeList.getLength()];
for (int i = 0; i < nodeList.getLength(); i++)
{
Node node = nodeList.item(i);
Machine[i] = new String();
Element fstElmnt = (Element) node;
NodeList nameList = fstElmnt.getElementsByTagName("ClassDescription");
Element nameElement = (Element) nameList.item(0);
nameList = nameElement.getChildNodes();
Machine[i]=((Node) nameList.item(0)).getNodeValue();
}
System.out.println("after for loop Machine"+Machine);
} catch (Exception e) {
System.out.println("XML Pasing Excpetion = " + e);
}
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.btn_next:
textlength=searchText.getText().length();
System.out.println("nextbutton"+textlength);
if(textlength==0){
changeListViewModel(StartingIndex + PAGE_SIZE);
}else{
changelist(StartingIndex + PAGE_SIZE);
}
break;
case R.id.btn_previous:
textlength=searchText.getText().length();
if(textlength==0){
changeListViewModel(StartingIndex - PAGE_SIZE);
}else{
changelist(StartingIndex - PAGE_SIZE);
}
break;
default:
break;
}
}
}
create main.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<View android:layout_height="35dp"
android:layout_width="fill_parent"
android:background="#ffffff"/>
<TextView android:id="#+id/tv_header"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/hello"
android:layout_alignParentTop="true"
android:layout_marginLeft="0dp"
android:textSize="25dp"/>
<EditText
android:id="#+id/et_Serchlist"
android:layout_height="35dp"
android:paddingLeft="19dp"
android:layout_marginLeft="60dp"
android:layout_toRightOf="#+id/tv_header"
android:maxLength="20"
android:maxLines="1"
android:inputType="text"
android:hint="Search"
android:textColor="#ffffff"
android:background="#drawable/my_border"
android:layout_width="100dip"/>
<ListView
android:id="#+id/ListView01"
android:layout_width="fill_parent"
android:textSize="4px"
android:layout_below="#+id/tv_header"
android:layout_above="#+id/btn_previous"
android:layout_height="wrap_content" />
<View android:layout_height="55dp"
android:layout_below="#+id/ListView0"
android:layout_alignParentBottom="true"
android:layout_width="fill_parent"
android:background="#ffffff"/>
<ImageView
android:src="#drawable/grewprevious"
android:id="#+id/btn_Whiteprevious"
android:layout_width="wrap_content"
android:layout_marginLeft="12dp"
android:layout_marginBottom="6dp"
android:layout_below="#+id/ListView0"
android:visibility="invisible"
android:layout_alignParentBottom="true"
android:layout_height="wrap_content"/>
<ImageView
android:src="#drawable/right"
android:id="#+id/btn_grewforward"
android:layout_width="wrap_content"
android:layout_marginLeft="259dp"
android:layout_marginBottom="6dp"
android:layout_below="#+id/ListView0"
android:visibility="invisible"
android:layout_alignParentBottom="true"
android:layout_height="wrap_content"/>
<ImageView
android:src="#drawable/backward"
android:id="#+id/btn_previous"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_marginLeft="12dp"
android:layout_marginBottom="6dp"
android:layout_below="#+id/ListView0"
android:onClick="backButtonClicked"/>
<ImageView android:src="#drawable/forward"
android:id="#+id/btn_next"
android:layout_width="80dp"
android:layout_marginBottom="6dp"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_below="#+id/ListView0"
android:layout_marginLeft="249dp"
android:text="Next"
android:onClick="nextButtonClicked"/>
</RelativeLayout>
Create userlist.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView android:id="#+id/tv_className"
android:layout_height="wrap_content"
android:layout_width="wrap_content"/>
</LinearLayout>
Add my_border.xml into Drawable folder:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
<stroke android:width="2dip" android:color="#ee777777" />
<solid android:color="#ee444444"/>
<padding
android:left="20dip"
android:top="2dip"
android:right="20dip"
android:bottom="2dip" />
<corners android:radius="15dip" />
![enter image description here][1]</shape>
If it give error for iamges then use any other images and run application.
Let me know it work for you.
Thanks
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 "