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 having problem when developing a weather app using Android Studio. The doInBackGround() method requires a return statement, but it shows error when I am returning forecastJsonStr (line no.181) . It says i need to return String[] and not String value. Similar return statement is asked in line 283. It says return statement missing.
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
//import java.sql.Time;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import android.text.format.Time;
import static com.github.afrin14.sunshine.R.id.container;
public class ForecastFragment extends Fragment {
public ForecastFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.forecastfragment, menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_refresh) {
FetchWeatherTask weatherTask = new FetchWeatherTask();
weatherTask.execute("94043");
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup
container, Bundle savedInstanceState) {
String[] forecastArray = {
"Today - Sunny - 88/63",
"Tomorrow - Foggy - 70/40",
"Wed - Cloudy - 72/63",
"Thurs - Asteroids - 75/65",
"Fri - Heavy Rain - 65/56",
"Sat - HELP TRAPPED IN WEATHERSTATION 60/51",
"Sun - Sunny - 80/68",
};
List<String> weekForecast = new ArrayList<String>
(Arrays.asList(forecastArray));
ListAdapter mForecastAdapter = new ArrayAdapter<String>(
getActivity(),
R.layout.list_item_forecast,
R.id.list_item_forecast_textview,
weekForecast);
View rootView = inflater.inflate(R.layout.fragment_main,
container, false);
ListView listView = (ListView)
rootView.findViewById(R.id.listview_forecast);
listView.setAdapter(mForecastAdapter);
return rootView;
}
public class FetchWeatherTask extends AsyncTask<String, Void,
String[]> {
private final String LOG_TAG =
FetchWeatherTask.class.getSimpleName();
#Override
protected String[] doInBackground(String... params) {
if (params.length == 0) {
return null;
}
// These two need to be declared outside the try/catch
// so that they can be closed in the finally block.
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
// Will contain the raw JSON response as a string.
String forecastJsonStr = null;
String forecastsonStr = null;
String format = "json";
String units = "metric";
int numDays = 7;
try {
// Construct the URL for the OpenWeatherMap query
// Possible parameters are avaiable at OWM's forecast
// API page, at
// http://openweathermap.org/API#forecast
final String FORECAST_BASE_URL =
"http://api.openweathermap.org/data/2.5/forecast/daily?";
final String QUERY_PARAM = "q";
final String FORMAT_PARAM = "mode";
final String UNITS_PARAM = "units";
final String DAYS_PARAM = "cnt";
Uri builtUri =
Uri.parse(FORECAST_BASE_URL).buildUpon().appendQueryParameter(QUERY_PARAM, params[0]).appendQueryParameter(FORMAT_PARAM, format).appendQueryParameter(UNITS_PARAM, units).appendQueryParameter(DAYS_PARAM, Integer.toString(numDays)).build();
URL url = new URL("http://api.openweathermap.org/data/2.5/forecast/daily?q=94043&mode=json&units=metric&cnt=7");
Log.v(LOG_TAG, "Buit URI " + builtUri.toString());
// Create the request to OpenWeatherMap, and open the connection
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
// Read the input stream into a String
InputStream inputStream = urlConnection.getInputStream();
StringBuffer buffer = new StringBuffer();
if (inputStream == null) {
// Nothing to do.
return null;
}
reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
// Since it's JSON, adding a newline isn't necessary (it won't affect parsing)
// But it does make debugging a *lot* easier if you print out the completed
// buffer for debugging.
buffer.append(line + "\n");
}
if (buffer.length() == 0) {
// Stream was empty. No point in parsing.
return null;
}
forecastJsonStr = buffer.toString();
Log.v(LOG_TAG, "Forecast JSON String: " + forecastJsonStr);
}
catch (IOException e) {
Log.e(LOG_TAG, "Error ", e);
// If the code didn't successfully get the weather data, there's no point in attemping
// to parse it.
return null;
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
if (reader != null) {
try {
reader.close();
} catch (final IOException e) {
Log.e(LOG_TAG, "Error closing stream", e);
}
}
}
try{
return getWeatherDataFromJson(forecastJsonStr, numDays);
}catch(JSONException e){
Log.e(LOG_TAG, e.getMessage(), e);
e.printStackTrace();
}
return forecastJsonStr;
}
/* The date/time conversion code is going to be moved outside the
*asynctask later,
* so for convenience we're breaking it out into its own method now.
*/
private String getReadableDateString(long time){
// Because the API returns a unix timestamp (measured in seconds),
// it must be converted to milliseconds in order to be converted to
//valid date.
SimpleDateFormat shortenedDateFormat = new SimpleDateFormat("EEE MMM
dd");
return shortenedDateFormat.format(time);
}
/**
* Prepare the weather high/lows for presentation.
*/
private String formatHighLows(double high, double low) {
// For presentation, assume the user doesn't care about tenths of a
//degree.
long roundedHigh = Math.round(high);
long roundedLow = Math.round(low);
String highLowStr = roundedHigh + "/" + roundedLow;
return highLowStr;
}
/**
* Take the String representing the complete forecast in JSON Format and
* pull out the data we need to construct the Strings needed for the
*wireframes.
*
* Fortunately parsing is easy: constructor takes the JSON string and
*converts it
* into an Object hierarchy for us.
*/
private String[] getWeatherDataFromJson(String forecastJsonStr, int
numDays)
throws JSONException {
// These are the names of the JSON objects that need to be
//extracted.
final String OWM_LIST = "list";
final String OWM_WEATHER = "weather";
final String OWM_TEMPERATURE = "temp";
final String OWM_MAX = "max";
final String OWM_MIN = "min";
final String OWM_DESCRIPTION = "main";
JSONObject forecastJson = new JSONObject(forecastJsonStr);
JSONArray weatherArray = forecastJson.getJSONArray(OWM_LIST);
// OWM returns daily forecasts based upon the local time of the city
//that is being
// asked for, which means that we need to know the GMT offset to
//translate this data
// properly.
// Since this data is also sent in-order and the first day is always
//the
// current day, we're going to take advantage of that to get a nice
// normalized UTC date for all of our weather.
Time dayTime = new Time();
dayTime.setToNow();
// we start at the day returned by local time. Otherwise this is a
//mess.
int julianStartDay = Time.getJulianDay(System.currentTimeMillis(),
dayTime.gmtoff);
// now we work exclusively in UTC
dayTime = new Time();
String[] resultStrs = new String[numDays];
for(int i = 0; i < weatherArray.length(); i++) {
// For now, using the format "Day, description, hi/low"
String day;
String description;
String highAndLow;
// Get the JSON object representing the day
JSONObject dayForecast = weatherArray.getJSONObject(i);
// The date/time is returned as a long. We need to convert that
// into something human-readable, since most people won't read
//"1400356800" as
// "this saturday".
long dateTime;
// Cheating to convert this to UTC time, which is what we want
//anyhow
dateTime = dayTime.setJulianDay(julianStartDay+i);
day = getReadableDateString(dateTime);
// description is in a child array called "weather", which is 1
//element long.
JSONObject weatherObject =
dayForecast.getJSONArray(OWM_WEATHER).getJSONObject(0);
description = weatherObject.getString(OWM_DESCRIPTION);
// Temperatures are in a child object called "temp". Try not to
//name variables
// "temp" when working with temperature. It confuses everybody.
JSONObject temperatureObject =
dayForecast.getJSONObject(OWM_TEMPERATURE);
double high = temperatureObject.getDouble(OWM_MAX);
double low = temperatureObject.getDouble(OWM_MIN);
highAndLow = formatHighLows(high, low);
resultStrs[i] = day + " - " + description + " - " +
highAndLow;
}
return resultStrs;
}
#Override
protected String[] doInBackground(String... params){
if(params.length == 0){
return null;
}
}
}
}
The first generic of your AsyncTask is defining what is returned in the doInBackground method. If you want to return a String instead of a String array (String[]) than change the async task to extend:
AsyncTask<String, Void, String>
and change the doInBackground Method to return String. If you don´t want it to return anything change it to "Void".
In your second AsyncTask doInBackground method (Why do you even have two of them?) the problem is that the method only returns something (null) when your if clause is true, otherwise nothing is returned. You should also return something in the else case.
To fully understand what the generics and return types are for I recommend you to read the AsyncTask docummentation
You have initialized Async task with return type String array.
public class FetchWeatherTask extends AsyncTask<String, Void, String[]>
Change the initialization as below to String to make it work.
public class FetchWeatherTask extends AsyncTask<String, Void, String>
change the method like below
#Override
protected String doInBackground(String... params)
Now you won't get this error. Hope it helps :)
You have to call postExecute method to get result from your http call. I have edited your code completely. This will work as you expected.
Your code should be like this.
public class ForecastFragment extends Fragment {
public ForecastFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.forecastfragment, menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_refresh) {
FetchWeatherTask weatherTask = new FetchWeatherTask();
weatherTask.execute("94043");
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup
container, Bundle savedInstanceState) {
String[] forecastArray = {
"Today - Sunny - 88/63",
"Tomorrow - Foggy - 70/40",
"Wed - Cloudy - 72/63",
"Thurs - Asteroids - 75/65",
"Fri - Heavy Rain - 65/56",
"Sat - HELP TRAPPED IN WEATHERSTATION 60/51",
"Sun - Sunny - 80/68",
};
List<String> weekForecast = new ArrayList<String>
(Arrays.asList(forecastArray));
ListAdapter mForecastAdapter = new ArrayAdapter<String>(
getActivity(),
R.layout.list_item_forecast,
R.id.list_item_forecast_textview,
weekForecast);
View rootView = inflater.inflate(R.layout.fragment_main,
container, false);
ListView listView = (ListView)
rootView.findViewById(R.id.listview_forecast);
listView.setAdapter(mForecastAdapter);
return rootView;
}
public class FetchWeatherTask extends AsyncTask<String, Void, String> {
private final String LOG_TAG =
FetchWeatherTask.class.getSimpleName();
private int numDays = 7;
#Override
protected String doInBackground(String... params) {
if (params.length == 0) {
return null;
}
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
String forecastJsonStr = null;
String format = "json";
String units = "metric";
try {
final String FORECAST_BASE_URL =
"http://api.openweathermap.org/data/2.5/forecast/daily?";
final String QUERY_PARAM = "q";
final String FORMAT_PARAM = "mode";
final String UNITS_PARAM = "units";
final String DAYS_PARAM = "cnt";
Uri builtUri = Uri.parse(FORECAST_BASE_URL).buildUpon().appendQueryParameter(QUERY_PARAM, params[0]).appendQueryParameter(FORMAT_PARAM, format).appendQueryParameter(UNITS_PARAM, units).appendQueryParameter(DAYS_PARAM, Integer.toString(numDays)).build();
URL url = new URL("http://api.openweathermap.org/data/2.5/forecast/daily?q=94043&mode=json&units=metric&cnt=7");
Log.v(LOG_TAG, "Buit URI " + builtUri.toString());
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
InputStream inputStream = urlConnection.getInputStream();
StringBuilder builder = new StringBuilder();
if (inputStream == null)
return null;
reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
builder.append(line).append("\n");
}
if (builder.length() == 0)
return null;
forecastJsonStr = builder.toString();
Log.v(LOG_TAG, "Forecast JSON String: " + forecastJsonStr);
} catch (IOException e) {
Log.e(LOG_TAG, "Error ", e);
return null;
} finally {
if (urlConnection != null)
urlConnection.disconnect();
if (reader != null) {
try {
reader.close();
} catch (final IOException e) {
Log.e(LOG_TAG, "Error closing stream", e);
}
}
}
return forecastJsonStr;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
try{
String[] weatherDataFromJson = getWeatherDataFromJson(s);
// do whatever you want with the output.
}catch(JSONException e){
Log.e(LOG_TAG, e.getMessage(), e);
e.printStackTrace();
}
}
private String getReadableDateString(long time) {
SimpleDateFormat shortenedDateFormat = new SimpleDateFormat("EEE MMM dd");
return shortenedDateFormat.format(time);
}
private String formatHighLows(double high, double low) {
// For presentation, assume the user doesn't care about tenths of a
//degree.
long roundedHigh = Math.round(high);
long roundedLow = Math.round(low);
String highLowStr = roundedHigh + "/" + roundedLow;
return highLowStr;
}
private String[] getWeatherDataFromJson(String forecastJsonStr) throws JSONException {
// These are the names of the JSON objects that need to be
//extracted.
final String OWM_LIST = "list";
final String OWM_WEATHER = "weather";
final String OWM_TEMPERATURE = "temp";
final String OWM_MAX = "max";
final String OWM_MIN = "min";
final String OWM_DESCRIPTION = "main";
JSONObject forecastJson = new JSONObject(forecastJsonStr);
JSONArray weatherArray = forecastJson.getJSONArray(OWM_LIST);
Time dayTime = new Time();
dayTime.setToNow();
int julianStartDay = Time.getJulianDay(System.currentTimeMillis(),
dayTime.gmtoff);
dayTime = new Time();
String[] resultStrs = new String[numDays];
for (int i = 0; i < weatherArray.length(); i++) {
String day;
String description;
String highAndLow;
JSONObject dayForecast = weatherArray.getJSONObject(i);
long dateTime;
dateTime = dayTime.setJulianDay(julianStartDay + i);
day = getReadableDateString(dateTime);
JSONObject weatherObject =
dayForecast.getJSONArray(OWM_WEATHER).getJSONObject(0);
description = weatherObject.getString(OWM_DESCRIPTION);
JSONObject temperatureObject =
dayForecast.getJSONObject(OWM_TEMPERATURE);
double high = temperatureObject.getDouble(OWM_MAX);
double low = temperatureObject.getDouble(OWM_MIN);
highAndLow = formatHighLows(high, low);
resultStrs[i] = day + " - " + description + " - " +
highAndLow;
}
return resultStrs;
}
}
}
Hope this help:)
I am trying to post data to mysql data base and it post it. But now i am trying to apply check if the fields in activity are empty - and data isn't posted to database.
public class Accepter extends Activity implements OnClickListener{
private EditText etName,etAge,etCity,etContact,etQuantity;
private Spinner spBloodGroup;
private ImageView imCancel,imSave;
private String message = "POST";
private static String[] BLOOD_GROUPS = {"Select Blood Group","A +Ve","B +Ve","AB +Ve","O +Ve","A -Ve","B -Ve","AB -Ve","O -Ve"};
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.accepter_entry_form);
etName = (EditText)findViewById(R.id.etNameAcc);
etAge = (EditText)findViewById(R.id.etAgeAcc);
etCity = (EditText)findViewById(R.id.etCityAcc);
etContact = (EditText)findViewById(R.id.etPhoneNoAcc);
etQuantity = (EditText)findViewById(R.id.etQuantityAcc);
spBloodGroup = (Spinner)findViewById(R.id.spBloodGroupAcc);
imCancel = (ImageView)findViewById(R.id.imCancelAcc);
imSave = (ImageView)findViewById(R.id.imSaveAcc);
imCancel.setOnClickListener(this);
imSave.setOnClickListener(this);
ArrayAdapter<String> bgAdapter = new ArrayAdapter<String>(Accepter.this,android.R.layout.simple_spinner_item,BLOOD_GROUPS);
bgAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spBloodGroup.setAdapter(bgAdapter);
}
#Override
public void onClick(View v) {
switch(v.getId())
{
case R.id.imSaveAcc:
String name = etName.getText().toString();
String blood = spBloodGroup.getSelectedItem().toString();
String quantity = etQuantity.getText().toString();
String phone = etContact.getText().toString();
int age = Integer.parseInt(etAge.getText().toString());
String city = etCity.getText().toString();
Calendar c = Calendar.getInstance();
int year = c.get(Calendar.YEAR);
int month= c.get(Calendar.MONTH);
int day = c.get(Calendar.DAY_OF_MONTH);
String date = String.valueOf(day) + "-" + String.valueOf(month) + "-" + String.valueOf(year);
if(name.length()>1 && blood.length()>1 && phone.length()>1 && age>15 && city.length()>1)
{
AccepterTask task = new AccepterTask(v.getContext());
task.execute(message ,name, blood, phone, String.valueOf(age),city,quantity,date);
etName.setText("");
spBloodGroup.setSelection(0);
etContact.setText("");
etAge.setText("");
etCity.setText("");
etQuantity.setText("");
finish();
}
else
{
Toast.makeText(Accepter.this, "Any field is empty or invalid", Toast.LENGTH_LONG).show();
}
break;
case R.id.imCancelAcc:
Intent i = new Intent(v.getContext(),MainView.class);
i.putExtra("type", "Accepter");
startActivity(i);
break;
}
}
public class AccepterTask extends AsyncTask<String, Void, String>{
private Context context;
private JSONParser jsonParser = new JSONParser();
private JSONObject json;
private String accepter_url = //"http://192.168.0.6/accepter.php";
"http://10.0.2.2/accepter.php";
private String s;
public AccepterTask(Context c)
{
context = c;
}
#Override
protected String doInBackground(String... params)
{
String message = params[0];
if(message.equals("POST"))
{
List<NameValuePair> list = new ArrayList<NameValuePair>();
final String names = params[1];
final String blood = params[2];
final String phone = params[3];
final String age = params[4];
final String city = params[5];
final String quantity = params[6];
final String date = params[7];
list.add(new BasicNameValuePair("name", names));
list.add(new BasicNameValuePair("blood", blood));
list.add(new BasicNameValuePair("quantity", quantity));
list.add(new BasicNameValuePair("phone", phone));
list.add(new BasicNameValuePair("age", age));
list.add(new BasicNameValuePair("city", city));
list.add(new BasicNameValuePair("date", date));
json = jsonParser.makeHttpRequest(accepter_url, params[0], list);
}
try
{
s = json.getString("message");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return s;
}
#Override
protected void onPostExecute(String result)
{
Toast.makeText(context, result, Toast.LENGTH_LONG).show();
}
}
}
here for updates
i have started learning android not very long ago.. It has only been sometime when this error creeped in haunting me ever since. I am following tutorials to build a weather app named Sunshine. I have double checked the api and it looks good. i have also inherited the AsyncTask class to work on the background thread, overridden the doInBackground() and onPostExecute() method to return to my UI thread successfully(I suppose). I have checked my code ton of times but couldn't resolve the error.
05-20 01:10:04.036 28055-28154/com.example.android.sunshine E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #1
Process: com.example.android.sunshine, PID: 28055
java.lang.RuntimeException: An error occured while executing doInBackground()
at android.os.AsyncTask$3.done(AsyncTask.java:300)
at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
at java.util.concurrent.FutureTask.run(FutureTask.java:242)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:841)
Caused by: java.lang.NullPointerException
at org.json.JSONTokener.nextCleanInternal(JSONTokener.java:116)
at org.json.JSONTokener.nextValue(JSONTokener.java:94)
at org.json.JSONObject.<init>(JSONObject.java:155)
at org.json.JSONObject.<init>(JSONObject.java:172)
at com.example.android.sunshine.ForecastFragment$FetchWeatherTask.getWeatherDataFromJson(ForecastFragment.java:115)
at com.example.android.sunshine.ForecastFragment$FetchWeatherTask.doInBackground(ForecastFragment.java:221)
at com.example.android.sunshine.ForecastFragment$FetchWeatherTask.doInBackground(ForecastFragment.java:89)
at android.os.AsyncTask$2.call(AsyncTask.java:288)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:841)
05-20 01:10:04.826 28055-28055/com.example.android.sunshine D/AbsListView: onDetachedFromWindow
D/AbsListView: onDetachedFromWindow05-20 01:15:04.106 28055-28154/com.example.android.sunshine I/Process: Sending signal. PID: 28055 SIG: 9
forecastfragment file
public class ForecastFragment extends Fragment {
private ArrayAdapter<String> mForecastAdapter;
public ForecastFragment() {
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
}
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
// Inflate the menu; this adds items to the action bar if it is present.
inflater.inflate(R.menu.forecastfragment, menu);
}
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_refresh) {
FetchWeatherTask weatherTask = new FetchWeatherTask();
weatherTask.execute("110025");
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
String[] data = {
"today-sunny - 41/29",
"today-sunny - 41/29",
"today-sunny - 41/29",
"today-sunny - 41/29",
"today-sunny - 41/29",
"today-sunny - 41/29",
"today-sunny - 41/29",
};
List<String> weekForecast = new ArrayList<>(
Arrays.asList(data));
mForecastAdapter = new ArrayAdapter<>(getActivity(), R.layout.list_item_forecast, R.id.list_item_forecast_textview, weekForecast);
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
ListView listView = (ListView) rootView.findViewById(R.id.listview_forecast);
listView.setAdapter(mForecastAdapter);
return rootView;
}
public class FetchWeatherTask extends AsyncTask<String, Void, String[]> {
private final String LOG_TAG = FetchWeatherTask.class.getSimpleName();
public String getReadableDateString(long time) {
Date date = new Date(time * 1000);
SimpleDateFormat format = new SimpleDateFormat("E, MMM d");
return format.format(date).toString();
}
private String formatHighLows(double high, double low) {
long roundedHigh = Math.round(high);
long roundedLow = Math.round(low);
String highLowStr = roundedHigh + "/" + roundedLow;
return highLowStr;
}
private String[] getWeatherDataFromJson(String forecastJsonStr, int days) throws JSONException {
final String OWM_LIST = "list";
final String OWM_WEATHER = "weather";
final String OWM_TEMPERATURE = "temp";
final String OWM_MAX = "max";
final String OWM_MIN = "min";
final String OWM_DATETIME = "dt";
final String OWM_DESCRIPTION = "main";
JSONObject forecastJson = new JSONObject(forecastJsonStr);
JSONArray weatherArray = forecastJson.getJSONArray(OWM_LIST);
String[] resultStrs = new String[days];
for (int i = 0; i < weatherArray.length(); i++) {
String day;
String description;
String highAndLow;
JSONObject dayForecast = weatherArray.getJSONObject(i);
long dateTime = dayForecast.getLong(OWM_DATETIME);
day = getReadableDateString(dateTime);
JSONObject weatherObject = dayForecast.getJSONArray(OWM_WEATHER).getJSONObject(0);
description = weatherObject.getString(OWM_DESCRIPTION);
JSONObject TemperatureObject = dayForecast.getJSONObject(OWM_TEMPERATURE);
double high = TemperatureObject.getDouble(OWM_MAX);
double low = TemperatureObject.getDouble(OWM_MIN);
highAndLow = formatHighLows(high, low);
resultStrs[i] = day + " - " + description + " - " + highAndLow;
}
for (String s : resultStrs) {
Log.v(LOG_TAG, "forecast entry:" + s);
}
return resultStrs;
}
#Override
protected String[] doInBackground(String... params) {
// These two need to be declared outside the try/catch
// so that they can be closed in the finally block.
HttpURLConnection urlConnection = null;
BufferedReader reader = null;
// Will contain the raw JSON response as a string.
String forecastJsonStr = null;
String format = "json";
String units = "metric";
int days = 7;
try {
// Construct the URL for the OpenWeatherMap query
// Possible parameters are avaiable at OWM's forecast API page, at
// http://openweathermap.org/API#forecast
final String FORECAST_BASE_URL = "http://api.openweathermap.org/data/2.5/forecast/daily?&APPID=bab4c81d2c0f80d573a3c37211c3353e";
final String QUERY_PARAM = "q";
final String FORMAT_PARAM = "mode";
final String UNITS_PARAM = "units";
final String DAYS_PARAM = "cnt";
Uri builtUri = Uri.parse(FORECAST_BASE_URL).buildUpon()
.appendQueryParameter(QUERY_PARAM, params[0])
.appendQueryParameter(FORMAT_PARAM, format)
.appendQueryParameter(UNITS_PARAM, units)
.appendQueryParameter(DAYS_PARAM, Integer.toString(days))
.build();
URL url = new URL(builtUri.toString());
// Create the request to OpenWeatherMap, and open the connection
urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.connect();
// Read the input stream into a String
InputStream inputStream = urlConnection.getInputStream();
StringBuffer buffer = new StringBuffer();
if (inputStream == null) {
// Nothing to do.
forecastJsonStr = null;
}
reader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
// Since it's JSON, adding a newline isn't necessary (it won't affect parsing)
// But it does make debugging a *lot* easier if you print out the completed
// buffer for debugging.
buffer.append(line + "\n");
}
if (buffer.length() == 0) {
// Stream was empty. No point in parsing.
forecastJsonStr = null;
}
forecastJsonStr = buffer.toString();
Log.v(LOG_TAG, "Forecast JSON string:" + forecastJsonStr);
} catch (IOException e) {
Log.e("PlaceholderFragment", "Error ", e);
// If the code didn't successfully get the weather data, there's no point in attemping
// to parse it.
forecastJsonStr = null;
} finally {
if (urlConnection != null) {
urlConnection.disconnect();
}
if (reader != null) {
try {
reader.close();
} catch (final IOException e) {
Log.e("PlaceholderFragment", "Error closing stream", e);
}
}
}
try {
return getWeatherDataFromJson(forecastJsonStr, days);
} catch (JSONException e) {
Log.e(LOG_TAG, e.getMessage(), e);
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String[] result) {
if (result != null){
mForecastAdapter.clear();
for (String dayForecastStr : result){
mForecastAdapter.add(dayForecastStr);
}
}
}
}
}
I am a noob at this and it has been 2 days and i still couldn't trace the problem. All help is appreciated. Thanks in advance.
Did you get thr correct forecastJsonStr ? Maybe it's null;
I tried to access the url ,it's response like this
What's your Log.v(LOG_TAG, "Forecast JSON string:" + forecastJsonStr); output?
earlier my code was this
String format = "json";
String units = "metric";
int days = 7;
try {
// Construct the URL for the OpenWeatherMap query
// Possible parameters are avaiable at OWM's forecast API page, at
// http://openweathermap.org/API#forecast
final String FORECAST_BASE_URL = "http://api.openweathermap.org/data/2.5/forecast/daily?&APPID=bab4c81d2c0f80d573a3c37211c3353e";
final String QUERY_PARAM = "q";
final String FORMAT_PARAM = "mode";
final String UNITS_PARAM = "units";
final String DAYS_PARAM = "cnt";
Uri builtUri = Uri.parse(FORECAST_BASE_URL).buildUpon()
.appendQueryParameter(QUERY_PARAM, params[0])
.appendQueryParameter(FORMAT_PARAM, format)
.appendQueryParameter(UNITS_PARAM, units)
.appendQueryParameter(DAYS_PARAM, Integer.toString(days))
.build();
furthermore i have declared a string q = "110025" as it was not initialised anywhere before and i passed it in the parameters of .appendQueryParameter(QUERY_PARAM,q) like this and voila, itworked.
now the code looks like
String format = "json";
String units = "metric";
q="110025";
int days = 7;
try {
// Construct the URL for the OpenWeatherMap query
// Possible parameters are avaiable at OWM's forecast API page, at
// http://openweathermap.org/API#forecast
final String FORECAST_BASE_URL = "http://api.openweathermap.org/data/2.5/forecast/daily?&APPID=bab4c81d2c0f80d573a3c37211c3353e";
final String QUERY_PARAM = "q";
final String FORMAT_PARAM = "mode";
final String UNITS_PARAM = "units";
final String DAYS_PARAM = "cnt";
Uri builtUri = Uri.parse(FORECAST_BASE_URL).buildUpon()
.appendQueryParameter(QUERY_PARAM, q)
.appendQueryParameter(FORMAT_PARAM, format)
.appendQueryParameter(UNITS_PARAM, units)
.appendQueryParameter(DAYS_PARAM, Integer.toString(days))
.build();
i think the problem was in the formation of the URL only where the value of q was not initialized before because of which there was a null pointer exception.
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 "