How to set background drawable, when clicking a dynamically created button like this :
I am using above code to create dynamic button and track click of specific button :
for (int i = 1; i<8; i++)
{
if(i==7)
{
btn = custom.myButton(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT), null, i+30, "...");
btn.setTag(i);
linear_paging.addView(btn);
}
else
{
btn = custom.myButton(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT), null, i+30, ""+i);
btn.setTag(i);
linear_paging.addView(btn);
}
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(Earned_New.this, v.getTag()+" clicked", Toast.LENGTH_SHORT).show();
v.setBackgroundDrawable(getResources().getDrawable(R.drawable.black_rounded_background));
}
});
}
Finally I have got the solution. Please follow the below process to achieve the task and modify this according to your requirement, it will definitely help you:
1.) Do this in onResume() method :
new AsynDriverEarned().execute();
2.) CONST.EARNED_LISTVIEW_SIZE = 10// Number of records in a single page
3.) This is the inner class(AsyncTask)
class AsynDriverEarned extends AsyncTask<String, Void, String>{
ProgressDialog dialog=null;
JSONObject jsonObject;
JSONObject jsonUserDetail;
String response="";
String result="";
SharedPreferences settingPref;
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
dialog=new ProgressDialog(Earned_New.this);
dialog.setMessage("Loading...");
// dialog.setCancelable(false);
dialog.setCanceledOnTouchOutside(false);
dialog.show();
}
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
Log.i("DRIVER_ID", CONST.LOGIN_ID);
postParameters.add(new BasicNameValuePair("DRIVER_ID", CONST.LOGIN_ID));
try{
response=CustomHttpClient.executeHttpPost(CUSTOM_URL.Common_Url+"mobile_driver_earned.php", postParameters);
Log.i("response:", ""+response);
result = "OK";
if(response!=null){
try {
jsonObject = new JSONObject(response);
if(jsonObject.getBoolean("SUCCESS")){
pound_value_string = jsonObject.getString("TOTAL_EARNING");
result = "OK";
JSONArray jsonDriverArray = jsonObject.getJSONArray("DRIVER_ARRAY");
Log.i("jsonDriverArray:", ""+jsonDriverArray);
date_time_list = new ArrayList<String>();
drop_loc_list = new ArrayList();
passenger_names_list = new ArrayList();
total_earn_list = new ArrayList();
for (int i = 0; i < jsonDriverArray.length(); i++)
{
date_time_list.add(jsonDriverArray.getJSONObject(i).getString("BOOKING_DATE"));
drop_loc_list.add(jsonDriverArray.getJSONObject(i).getString("PASSENGER_DROP_LOCATION"));
passenger_names_list.add(jsonDriverArray.getJSONObject(i).getString("PASSENGER_NAME"));
total_earn_list.add(jsonDriverArray.getJSONObject(i).getString("EARNING"));
}
}
else{
result="FAILURE";
earner_error_message = jsonObject.getString("ERROR");
Log.i("earner_error_message", earner_error_message);
}
}
catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
result = e.getMessage();
}
}else{
result = "Timed Out!";
}
}catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
// result = e.getMessage();
}
return result;
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
dialog.dismiss();
if(result.equalsIgnoreCase("OK"))
{
pound_value.setText(pound_value_string);
ArrayList<String> temp_date_time_list = new ArrayList<String>();
ArrayList<String> temp_drop_loc_list = new ArrayList();
ArrayList<String> temp_passenger_names_list = new ArrayList();
ArrayList<String> temp_total_earn_list = new ArrayList();
int start_number_of_records = (CONST.EARNED_LISTVIEW_SIZE*(1-1)); // no_of_records*tag_value
Log.i("start_number_of_records", ""+start_number_of_records);
int end_number_of_records = (((CONST.EARNED_LISTVIEW_SIZE*(1-1))+CONST.EARNED_LISTVIEW_SIZE)-1); //(no_of_records*tag_value+no_of_records)-1
Log.i("end_number_of_records", ""+end_number_of_records);
if (end_number_of_records<date_time_list.size())
{
Log.i("ENTER:", "FIRST");
for (int j = start_number_of_records; j < end_number_of_records+1; j++)
{
temp_date_time_list.add(date_time_list.get(j));
temp_drop_loc_list.add(drop_loc_list.get(j));
temp_passenger_names_list.add(passenger_names_list.get(j));
temp_total_earn_list.add(total_earn_list.get(j));
}
Log.i("temp_date_time_list.size()", ""+temp_date_time_list.size());
setListAdapter(temp_date_time_list,temp_drop_loc_list,temp_passenger_names_list,temp_total_earn_list);
adapter.notifyDataSetChanged();
}
else
{
Log.i("ENTER:", "SECOND");
for (int j = start_number_of_records; j < date_time_list.size(); j++)
{
temp_date_time_list.add(date_time_list.get(j));
temp_drop_loc_list.add(drop_loc_list.get(j));
temp_passenger_names_list.add(passenger_names_list.get(j));
temp_total_earn_list.add(total_earn_list.get(j));
}
Log.i("temp_date_time_list.size()", ""+temp_date_time_list.size());
setListAdapter(temp_date_time_list,temp_drop_loc_list,temp_passenger_names_list,temp_total_earn_list);
adapter.notifyDataSetChanged();
}
int num = date_time_list.size();
Log.i("num", ""+num);
int counter=1;
while(num>CONST.EARNED_LISTVIEW_SIZE)
{
num = num-CONST.EARNED_LISTVIEW_SIZE; // num = 32-5==27
counter++;
Log.i("counter", ""+counter);
continue;
}
for (int i = 1; i<counter+1; i++)
{
btn = custom.myButton(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT), null, i+30, ""+i);
btn.setTag(i);
linear_paging.addView(btn);
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
v.setBackgroundDrawable(getResources().getDrawable(R.drawable.button_selector));
ArrayList<String> temp_date_time_list = new ArrayList<String>();
ArrayList<String> temp_drop_loc_list = new ArrayList();
ArrayList<String> temp_passenger_names_list = new ArrayList();
ArrayList<String> temp_total_earn_list = new ArrayList();
int start_number_of_records = (CONST.EARNED_LISTVIEW_SIZE*((Integer) v.getTag()-1)); // no_of_records*tag_value
// Log.i("start_number_of_records", ""+start_number_of_records);
int end_number_of_records = (((CONST.EARNED_LISTVIEW_SIZE*((Integer) v.getTag()-1))+CONST.EARNED_LISTVIEW_SIZE)-1); //(no_of_records*tag_value+no_of_records)-1
// Log.i("end_number_of_records", ""+end_number_of_records);
if (end_number_of_records<date_time_list.size())
{
Log.i("ENTER:", "FIRST");
for (int j = start_number_of_records; j < end_number_of_records+1; j++)
{
temp_date_time_list.add(date_time_list.get(j));
temp_drop_loc_list.add(drop_loc_list.get(j));
temp_passenger_names_list.add(passenger_names_list.get(j));
temp_total_earn_list.add(total_earn_list.get(j));
}
Log.i("temp_date_time_list.size()", ""+temp_date_time_list.size());
setListAdapter(temp_date_time_list,temp_drop_loc_list,temp_passenger_names_list,temp_total_earn_list);
adapter.notifyDataSetChanged();
}
else
{
Log.i("ENTER:", "SECOND");
for (int j = start_number_of_records; j < date_time_list.size(); j++)
{
temp_date_time_list.add(date_time_list.get(j));
temp_drop_loc_list.add(drop_loc_list.get(j));
temp_passenger_names_list.add(passenger_names_list.get(j));
temp_total_earn_list.add(total_earn_list.get(j));
}
Log.i("temp_date_time_list.size()", ""+temp_date_time_list.size());
setListAdapter(temp_date_time_list,temp_drop_loc_list,temp_passenger_names_list,temp_total_earn_list);
adapter.notifyDataSetChanged();
}
}
});
}
}
else
{
AlertDialog.Builder builder = new AlertDialog.Builder(Earned_New.this);
builder.setMessage(earner_error_message);
builder.setCancelable(false);
LayoutInflater inflater = getLayoutInflater();
View vw = inflater.inflate(R.layout.custom_title, null);
builder.setCustomTitle(vw);
builder.setNeutralButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
dialog.dismiss();
finish();
}
});
builder.show();
}
}
}
You can use the selector as drawable to that view.
Here is sample..
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="#android:color/darker_gray" android:state_pressed="true"></item>
<item android:drawable="#android:color/darker_gray" android:state_selected="true"></item>
<item android:drawable="#android:color/darker_gray" android:state_checked="true"></item>
<item android:drawable="#android:color/transparent" ></item>
</selector>
You can change the colors in the above.
easily you can acheive this by taking RadioButton instead of Button. I will provide more info if you are unable to do that.
Related
I am making a quiz app in android studio. I am facing an issue which is that I have hundreds of questions with four options, and also next and previous buttons in that. For options, I am using radio buttons. I want that after the user selects an option for the first question, goes to the next question and selects an option for the second question, he will be able to go to the previous question, and there the radio button will be checked with the option the user has been selected earlier.
How can I do that? please help!
This is my code:
public class MainActivity extends AppCompatActivity {
int score;
float percentage;
int answerSelected;
private TextView quizQuestion,questionNumber;
private RadioGroup radioGroup;
private RadioButton optionOne;
private RadioButton optionTwo;
private RadioButton optionThree;
private RadioButton optionFour;
private ImageView question_image;
private int currentQuizQuestion;
private int quizCount;
private QuizWrapper firstQuestion;
private List<QuizWrapper> parsedObject;
private boolean mIsDestroyed;
private ProgressDialog progressDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
score = 0;
quizQuestion = (TextView)findViewById(R.id.quiz_question);
questionNumber = (TextView)findViewById(R.id.question_number);
radioGroup = (RadioGroup)findViewById(R.id.radioGroup);
optionOne = (RadioButton)findViewById(R.id.radio0);
optionTwo = (RadioButton)findViewById(R.id.radio1);
optionThree = (RadioButton)findViewById(R.id.radio2);
optionFour = (RadioButton)findViewById(R.id.radio3);
question_image = (ImageView)findViewById(R.id.question_image);
final Button previousButton = (Button)findViewById(R.id.previousquiz);
final Button nextButton = (Button)findViewById(R.id.nextquiz);
AsyncJsonObject asyncObject = new AsyncJsonObject();
asyncObject.execute("");
nextButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int radioSelected = radioGroup.getCheckedRadioButtonId();
int userSelection = getSelectedAnswer(radioSelected);
int correctAnswerForQuestion = firstQuestion.getIs_correct();
if(userSelection == correctAnswerForQuestion){
// correct answer
score++;
// Toast.makeText(MainActivity.this, "You got the answer correct", Toast.LENGTH_LONG).show();
currentQuizQuestion++;
if(currentQuizQuestion >= quizCount){
previousButton.setVisibility(View.VISIBLE);
AlertDialog.Builder alertConfirm = new AlertDialog.Builder(MainActivity.this);
alertConfirm.setTitle("Confirm Submission");
alertConfirm.setMessage("Do you want to submit quiz?");
alertConfirm.setCancelable(true);
alertConfirm.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
alertConfirm.setPositiveButton("Submit", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// submit(view);
}
});
AlertDialog dialog = alertConfirm.create();
dialog.show();
Toast.makeText(MainActivity.this, "End of the Quiz Questions", Toast.LENGTH_LONG).show();
return;
}
else{
previousButton.setVisibility(View.VISIBLE);
// uncheckedRadioButton();
firstQuestion = parsedObject.get(currentQuizQuestion);
questionNumber.setText(Integer.toString(firstQuestion.getQuestion_number()));
quizQuestion.setText(firstQuestion.getQuestions());
if(firstQuestion.getQuestion_image().isEmpty()){
// Picasso.get().load(firstQuestion.getQuestion_image()).into(question_image);
question_image.setVisibility(View.GONE);
}else{
Picasso.get().load(firstQuestion.getQuestion_image()).into(question_image);
question_image.setVisibility(View.VISIBLE);
}
// String[] possibleAnswers = firstQuestion.get.split(",");
optionOne.setText(firstQuestion.getOption_a());
optionTwo.setText(firstQuestion.getOption_b());
optionThree.setText(firstQuestion.getOption_c());
optionFour.setText(firstQuestion.getOption_d());
}
}
else{
currentQuizQuestion++;
// failed question
// Toast.makeText(MainActivity.this, "You chose the wrong answer", Toast.LENGTH_LONG).show();
if( currentQuizQuestion<quizCount) {
previousButton.setVisibility(View.VISIBLE);
// uncheckedRadioButton();
firstQuestion = parsedObject.get(currentQuizQuestion);
questionNumber.setText(Integer.toString(firstQuestion.getQuestion_number()));
quizQuestion.setText(firstQuestion.getQuestions());
if(firstQuestion.getQuestion_image().isEmpty()){
// Picasso.get().load(firstQuestion.getQuestion_image()).into(question_image);
question_image.setVisibility(View.GONE);
}else{
Picasso.get().load(firstQuestion.getQuestion_image()).into(question_image);
question_image.setVisibility(View.VISIBLE);
}
// String[] possibleAnswers = firstQuestion.get.split(",");
optionOne.setText(firstQuestion.getOption_a());
optionTwo.setText(firstQuestion.getOption_b());
optionThree.setText(firstQuestion.getOption_c());
optionFour.setText(firstQuestion.getOption_d());
}else {
AlertDialog.Builder alertConfirm = new AlertDialog.Builder(MainActivity.this);
alertConfirm.setTitle("Confirm Submission");
alertConfirm.setMessage("Do you want to submit quiz?");
alertConfirm.setCancelable(true);
alertConfirm.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
}
});
alertConfirm.setPositiveButton("Submit", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// submit(view);
submit();
}
});
AlertDialog dialog = alertConfirm.create();
dialog.show();
// Toast.makeText(MainActivity.this, "End of the Quiz Questions", Toast.LENGTH_LONG).show();
return;
}
}
}
});
previousButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (currentQuizQuestion <= 0) {
previousButton.setVisibility(View.INVISIBLE);
}else {
currentQuizQuestion--;
firstQuestion = parsedObject.get(currentQuizQuestion);
questionNumber.setText(Integer.toString(firstQuestion.getQuestion_number()));
quizQuestion.setText(firstQuestion.getQuestions());
if (firstQuestion.getQuestion_image().isEmpty()) {
// Picasso.get().load(firstQuestion.getQuestion_image()).into(question_image);
question_image.setVisibility(View.GONE);
} else {
Picasso.get().load(firstQuestion.getQuestion_image()).into(question_image);
question_image.setVisibility(View.VISIBLE);
}
// String[] possibleAnswers = firstQuestion.getAnswers().split(",");
optionOne.setText(firstQuestion.getOption_a());
optionTwo.setText(firstQuestion.getOption_b());
optionThree.setText(firstQuestion.getOption_c());
optionFour.setText(firstQuestion.getOption_d());
// AlertDialog.Builder alertConfirm = new AlertDialog.Builder(MainActivity.this);
// alertConfirm.setTitle("Finish Test");
// alertConfirm.setMessage("You cannot resume once you submit.Are you sure you want to submit this test?");
// alertConfirm.setCancelable(true);
// alertConfirm.setNegativeButton("RESUME", new DialogInterface.OnClickListener() {
// #Override
// public void onClick(DialogInterface dialog, int which) {
//
// }
// });
// alertConfirm.setPositiveButton("Submit", new DialogInterface.OnClickListener() {
// #Override
// public void onClick(DialogInterface dialog, int which) {
// // submit(view);
// submit();
// }
// });
// AlertDialog dialog = alertConfirm.create();
// dialog.show();
//
}
}
});
}
#Override
protected void onDestroy() {
super.onDestroy();
mIsDestroyed = true;
if (progressDialog != null && progressDialog.isShowing()) {
progressDialog.dismiss();
}
}
private class AsyncJsonObject extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... params) {
HttpClient httpClient = new DefaultHttpClient(new BasicHttpParams());
String url = "";
HttpPost httpPost = new HttpPost(url);
String jsonResult = "";
try {
HttpResponse response = httpClient.execute(httpPost);
jsonResult = inputStreamToString(response.getEntity().getContent()).toString();
System.out.println("Returned Json object " + jsonResult.toString());
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return jsonResult;
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
progressDialog = ProgressDialog.show(MainActivity.this, "Loading Quiz","Wait....", true);
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
System.out.println("Resulted Value: " + result);
progressDialog.dismiss();
parsedObject = returnParsedJsonObject(result);
if(parsedObject == null){
return;
}
quizCount = parsedObject.size();
firstQuestion = parsedObject.get(0);
questionNumber.setText(Integer.toString(firstQuestion.getQuestion_number()));
quizQuestion.setText(firstQuestion.getQuestions());
if(firstQuestion.getQuestion_image().isEmpty()){
// Picasso.get().load(firstQuestion.getQuestion_image()).into(question_image);
question_image.setVisibility(View.GONE);
}else {
Picasso.get().load(firstQuestion.getQuestion_image()).into(question_image);
question_image.setVisibility(View.VISIBLE);
}
// String[] possibleAnswers = firstQuestion.getAnswers().split(",");
optionOne.setText(firstQuestion.getOption_a());
optionTwo.setText(firstQuestion.getOption_b());
optionThree.setText(firstQuestion.getOption_c());
optionFour.setText(firstQuestion.getOption_d());
}
private StringBuilder inputStreamToString(InputStream is) {
String rLine = "";
StringBuilder answer = new StringBuilder();
BufferedReader br = new BufferedReader(new InputStreamReader(is));
try {
while ((rLine = br.readLine()) != null) {
answer.append(rLine);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return answer;
}
}
private List<QuizWrapper> returnParsedJsonObject(String result){
List<QuizWrapper> jsonObject = new ArrayList<QuizWrapper>();
JSONObject resultObject = null;
JSONArray jsonArray = null;
QuizWrapper newItemObject = null;
try {
resultObject = new JSONObject(result);
System.out.println("Testing the water " + resultObject.toString());
String test = "";
jsonArray = resultObject.optJSONArray(test);
} catch (JSONException e) {
e.printStackTrace();
}
for(int i = 0; i < jsonArray.length(); i++){
JSONObject jsonChildNode = null;
try {
jsonChildNode = jsonArray.getJSONObject(i);
int id = jsonChildNode.getInt("id");
String answera = jsonChildNode.getString("option_a");
String answerb = jsonChildNode.getString("option_b");
String answerc = jsonChildNode.getString("option_c");
String answerd = jsonChildNode.getString("option_d");
int correctAnswer = jsonChildNode.getInt("is_correct");
int questionnumber = jsonChildNode.getInt("question_number");
String question = jsonChildNode.getString("questions");
String questionimage = jsonChildNode.getString("question_image");
newItemObject = new QuizWrapper(id, answera,answerb,answerc,answerd, correctAnswer,questionnumber,question,questionimage);
jsonObject.add(newItemObject);
} catch (JSONException e) {
e.printStackTrace();
}
}
return jsonObject;
}
private int getSelectedAnswer(int radioSelected){
answerSelected = 0;
radioGroup.clearCheck();
if(radioSelected == R.id.radio0){
answerSelected = 1;
}
if(radioSelected == R.id.radio1){
answerSelected = 2;
}
if(radioSelected == R.id.radio2){
answerSelected = 3;
}
if(radioSelected == R.id.radio3){
answerSelected = 4;
}
return answerSelected;
}
private void uncheckedRadioButton() {
optionOne.setChecked(false);
optionTwo.setChecked(false);
optionThree.setChecked(false);
optionFour.setChecked(false);
}
#Override
public void onBackPressed() {
Toast.makeText(this, "Back Press is not allowed", Toast.LENGTH_LONG).show();
}
private void submit(){
// if (submit)
// checkScore();
// submit = false;
percentage = (float) (score * 100) /parsedObject.size();
//.setVisibility(View.INVISIBLE);
optionOne.setClickable(false);
optionTwo.setClickable(false);
optionThree.setClickable(false);
optionFour.setClickable(false);
LayoutInflater inflater = getLayoutInflater();
View alertLayout = inflater.inflate(R.layout.alert_dialog, null);
final ProgressBar progressBar = alertLayout.findViewById(R.id.circularProgressbar);
final TextView textView = alertLayout.findViewById(R.id.tv);
Drawable drawable = getResources().getDrawable(R.drawable.circular);
progressBar.setMax(parsedObject.size());
progressBar.setSecondaryProgress(parsedObject.size());
progressBar.setProgress(score);
progressBar.setProgressDrawable(drawable);
textView.setText((int) percentage + "%");
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle("RESULT");
alert.setMessage("You scored " + score + " out of " + parsedObject.size() );
alert.setView(alertLayout);
alert.setCancelable(false);
alert.setNegativeButton("Exit", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
moveTaskToBack(true);
android.os.Process.killProcess(android.os.Process.myPid());
System.exit(1);
}
});
alert.setPositiveButton("View Solutions", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//clickSolutions();
Intent intent = new Intent(MainActivity.this,SolutionActivity.class);
startActivity(intent);
}
});
AlertDialog dialog = alert.create();
dialog.show();
}
}
This is Kotlin, but it's the same way to write in Java.
ShareReference Function:
private val sharedPreferences = context.getSharedPreferences("YourFile", Context.MODE_PRIVATE)
Functions:
fun setInt(key: String, value: Int) {
with(sharedPreferences.edit()) {
putInt(key, value)
apply()
}
}
fun getInt(key: String): Int {
return sharedPreferences.getInt(key, -1)
}
Save the checked one:
// save to sharedPreferences
val CHECKED = "checkedRadio"
val checkedButtonId = radioGroup.checkedRadioButtonId
setInt(CHECKED, checkedButtonId)
Load the checked one:
val mRatioId = getInt(CHECKED)
radioGroup.check(mRatioId)
Let's use it in the listener:
val mRadioGroup = view?.findViewById<RadioGroup>(R.id...)
mRadioGroup?.setOnCheckedChangeListener { _, checkedId ->
setInt(checkedId)
}
Once you click any radio button, its radio-group will save the option to the shared preference. This code is saving R.id. But you can convert the id to ABCD.
static variables:
const val aRb = R.id.aRb
const val bRb = R.id.bRb
const val cRb = R.id.cRb
const val dRb = R.id.dRb
Instead saving integer. You can save it in string.
fun setString(key: String, value: String) {
with(sharedPreferences.edit()) {
putString(key, value)
apply()
}
}
fun getString(key: String): String {
return sharedPreferences.getString(key, "")!!
}
Selection for Question # 12 as example:
when (checkedId) {
aRb -> setString("Q12", 'a')
bRb -> setString("Q12", 'b')
cRb -> setString("Q12", 'c')
dRb -> setString("Q12", 'd')
}
I have custom alert dailog with list and check i am trying to store selected checkbox in pref,how to store selected item in shared preference,i am able to select values from list?can any one help me with this?
class LoadAlldata extends AsyncTask<String, String, ArrayList<HashMap<String, String>>> {
ArrayAdapter<String> adapterallstates;
private ProgressDialog pDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(TestCountry.this);
pDialog.setMessage("Please..");
pDialog.setIndeterminate(true);
// pDialog.setIndeterminateDrawable(getResources().getDrawable(R.drawable.custom_progress));
pDialog.setCancelable(true);
pDialog.show();
}
protected ArrayList<HashMap<String, String>> doInBackground(String... args) {
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
statedata = new ArrayList<HashMap<String, String>>();
String jsonStr = sh.makeServiceCall(STATE_URL, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
jsonObj = new JSONArray(jsonStr);
// state_list = jsonObj.getJSONArray(COUNTRY_LIST);
// looping through All Contacts
for (int i = 0; i < jsonObj.length(); i++) {
JSONObject c = jsonObj.getJSONObject(i);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
map.put(STATE_ID, c.getString(STATE_ID));
map.put(STATE_NAME, c.getString(STATE_NAME));
statedata.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return statedata;
}
protected void onPostExecute(ArrayList<HashMap<String, String>> result) {
super.onPostExecute(result);
pDialog.dismiss();
final String[] arrallstates = new String[statedata.size()];
checked_state=new boolean[statedata.size()];
for (int index = 0; index < statedata.size(); index++) {
HashMap<String, String> map = statedata.get(index);
arrallstates[index] = map.get(STATE_NAME);
}
txtvw.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View w) {
new AlertDialog.Builder(TestCountry.this)
.setTitle("Choose a Days")
.setMultiChoiceItems(arrallstates, null, new DialogInterface.OnMultiChoiceClickListener() {
#Override
public void onClick(DialogInterface dialog, int which, boolean isChecked) {
// TODO Auto-generated method stub
//storing the checked state of the items in an array
checked_state[which] = isChecked;
}
})
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
String display_checked_days = "";
for (int i = 0; i < arrallstates.length; i++) {
if (checked_state[i] == true) {
display_checked_days = display_checked_days + " " + arrallstates[i];
}
}
Toast.makeText(TestCountry.this, "The selected is" + display_checked_days, Toast.LENGTH_SHORT).show();
//clears the array used to store checked state
for (int i = 0; i < checked_state.length; i++) {
if (checked_state[i] == true) {
checked_state[i] = false;
}
}
//used to dismiss the dialog upon user selection.
dialog.dismiss();
}
}).create().show();;
}
});
}
}
First write a method to setSelection mannually in Adapter.
private int selectedItem = -1;
public void setSelectedItem(int position) {
selectedItem = position;
notifyDataSetChanged();
} // Here selectedItem is global variable
In onBindViewHolder add this code :
if (position == selectedItem){
viewHolder.chkSelected.setChecked(stList.get(position));
viewHolder.chkSelected.setTag(stList.get(position));
} else {
viewHolder.chkSelected.setChecked(stList.get(position).isselected());
viewHolder.chkSelected.setTag(stList.get(position));
}
From your Activity you have to call setSelectedItem(position) from your adapter insance. For getting position you have already know the chekbox Id so you can get position of that Id from List.
To get position from List:
private int getSelectedItem(List<String> stList, String name) {
int pos = -1;
for(int i=0; i<stList.size(); i++) {
if(name.equals(stList.get(i)){
pos = i;
break;
}
}
return pos;
}
Try like this:
First make model class with getter setter:
private boolean checked;
public boolean isChecked() {
return checked;
}
public void setChecked(boolean checked) {
this.checked = checked;
}
And in Adapter Class in getview write Code like this.
FilterModelClass model=stList.get(position);
viewHolder.chkbox.setOnCheckedChangeListener(new CheckUpdateListener(model));
Make class like below to handle checkedChangedListener
/*******************
* Checkbox Checked Change Listener
********************/
private final class CheckUpdateListener implements CompoundButton.OnCheckedChangeListener {
private final FilterModelClass model;
private CheckUpdateListener(FilterModelClass model) {
this.model = model;
}
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
Log.i("onCheckedChanged", "isChecked: " + isChecked);
model.setChecked(isChecked);
notifyDataSetChanged();
}
}
i am new to develop staggered grid view . i have a problem in staggered grid view. when we scroll from top to bottom it is scrolled. but again go to bottom to top grid view start image is bank. i am sending screen short for that.. thanks advance.
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
boolforprogressdialogmyfeed=true;
BugSenseHandler.initAndStartSession(getApplicationContext(), "ab5c30f1 ");
setContentView(R.layout.activity_activitynewstagredgridview);
mystream=(LinearLayout)findViewById(R.id.mystream);
featured=(LinearLayout)findViewById(R.id.featured);
all=(LinearLayout)findViewById(R.id.popular);
search=(ImageView)findViewById(R.id.search);
mystream_text=(TextView)findViewById(R.id.mystream_text);
featured_text=(TextView)findViewById(R.id.featured_text);
popular_text=(TextView)findViewById(R.id.popular_text);
mystream.setBackgroundResource(R.drawable.shape_tab_left);
featured.setBackgroundColor(Color.parseColor("#3a404c"));
all.setBackgroundColor(Color.TRANSPARENT);
mystream_text.setTextColor(Color.parseColor("#BFC9CB"));
featured_text.setTextColor(Color.parseColor("#BFC9CB"));
popular_text.setTextColor(Color.parseColor("#3a404c"));
mystream.setOnClickListener(this);
featured.setOnClickListener(this);
all.setOnClickListener(this);
search.setOnClickListener(this);
ptrstaggredview=(PullToRefreshStaggeredGridView)findViewById(R.id.staggeredGridView1);
ptrstaggredview.setMode(PullToRefreshBase.Mode.PULL_FROM_START);
popular_Adapter = new ImageBOStaggredAdapter(getParent(),mystreamList.size(),parent, mystreamList);
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
footerView = inflater.inflate(R.layout.layout_loading_footer, null);
ptrstaggredview.getRefreshableView().setFooterView(footerView);
ptrstaggredview.setAdapter(popular_Adapter);
strcurrenttab="all";
new Load(intstartValue).execute();
popular_Adapter.notifyDataSetChanged();
ptrstaggredview.setOnLoadmoreListener(new StaggeredGridView.OnLoadmoreListener() {
#Override
public void onLoadmore() {
//ptrstaggredview.SMOOTH_SCROLL_LONG_DURATION_MS=BIND_ADJUST_WITH_ACTIVITY;
//dialog=MyProgressDialog.show(getParent(),null,null);
intstartValue=intstartValue+10;
new Load(intstartValue).execute();
//
}
});
/*ObjectAnimator animator=ObjectAnimator.ofInt(yourHorizontalScrollView, "scrollX",targetXScroll );
animator.start();*/
ptrstaggredview.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener<StaggeredGridView>() {
#Override
public void onRefresh(PullToRefreshBase<StaggeredGridView> refreshView) {
boolpulltorefresh=true;
intstartValue=0;
// if(strcurrenttab.equals("mys"))
new Load(intstartValue).execute();
popular_Adapter.notifyDataSetChanged();
ptrstaggredview.onRefreshComplete();
}
});
}
#Override
public void onClick(View v) {
if(v==mystream){
Log.e("onclick for mystream","onclick mystream");
strcurrenttab="mystream"; boolforprogressdialogmyfeed=true;
// ptrstaggredview.removeAllViewsInLayout();
intstartValue=0;
mystream.setBackgroundColor(Color.TRANSPARENT);
featured.setBackgroundColor(Color.parseColor("#3a404c"));
all.setBackgroundResource(R.drawable.shape_tab_right);
mystream_text.setTextColor(Color.parseColor("#3a404c"));
featured_text.setTextColor(Color.parseColor("#BFC9CB"));
popular_text.setTextColor(Color.parseColor("#BFC9CB"));
ptrstaggredview.setMode(PullToRefreshBase.Mode.PULL_FROM_START);
mystreamList.clear();
ImageBOStaggredAdapter.views.clear();
new Load(intstartValue).execute();
popular_Adapter.notifyDataSetChanged();
popular_Adapter = new ImageBOStaggredAdapter(getParent(),mystreamList.size(),parent, mystreamList);
//
//
// LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
// footerView = inflater.inflate(R.layout.layout_loading_footer, null);
// ptrstaggredview.getRefreshableView().setFooterView(footerView);
ptrstaggredview.setAdapter(popular_Adapter);
}else if(v==featured){
Log.e("onclick for featured","onclick featured");
strcurrenttab="featured"; boolforprogressdialogmyfeed=true;
intstartValue=0;
mystream.setBackgroundResource(R.drawable.shape_tab_left);
featured.setBackgroundColor(Color.TRANSPARENT);
all.setBackgroundResource(R.drawable.shape_tab_right);
mystream_text.setTextColor(Color.parseColor("#BFC9CB"));
featured_text.setTextColor(Color.parseColor("#3a404c"));
popular_text.setTextColor(Color.parseColor("#BFC9CB"));
ptrstaggredview.setMode(PullToRefreshBase.Mode.PULL_FROM_START);
mystreamList.clear();
ImageBOStaggredAdapter.views.clear();
new Load(intstartValue).execute();
popular_Adapter.notifyDataSetChanged();
popular_Adapter = new ImageBOStaggredAdapter(getParent(),mystreamList.size(),parent, mystreamList);
//
//
// LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
// footerView = inflater.inflate(R.layout.layout_loading_footer, null);
// ptrstaggredview.getRefreshableView().setFooterView(footerView);
ptrstaggredview.setAdapter(popular_Adapter);
}else if(v==all){
Log.e("onclick for all","onclick all");
strcurrenttab="all"; boolforprogressdialogmyfeed=true;
intstartValue=0;
// ptrstaggredview.removeAllViewsInLayout();
mystream.setBackgroundResource(R.drawable.shape_tab_left);
featured.setBackgroundColor(Color.parseColor("#3a404c"));
all.setBackgroundColor(Color.TRANSPARENT);
mystream_text.setTextColor(Color.parseColor("#BFC9CB"));
featured_text.setTextColor(Color.parseColor("#BFC9CB"));
popular_text.setTextColor(Color.parseColor("#3a404c"));
ptrstaggredview.setMode(PullToRefreshBase.Mode.PULL_FROM_START);
mystreamList.clear();ImageBOStaggredAdapter.views.clear();
new Load(intstartValue).execute();
popular_Adapter.notifyDataSetChanged();
popular_Adapter = new ImageBOStaggredAdapter(getParent(),mystreamList.size(),parent, mystreamList);
//
//
// LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
// footerView = inflater.inflate(R.layout.layout_loading_footer, null);
// ptrstaggredview.getRefreshableView().setFooterView(footerView);
ptrstaggredview.setAdapter(popular_Adapter);
}else if(v==search)
{
// here is the codr for intigrating tabs,..
// Log.e("userrrrrr",""+Logined_User.getId());
View vi =TabActivityActivity.group.getLocalActivityManager()
.startActivity("Items", new Intent(getApplicationContext(),SearchActivity.class)
// .putExtra("imageBo", ""+gson.toJson(imagesBO))
.putExtra("parent", "Activity")
.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP))
.getDecorView();
TabActivityActivity.group.replaceView(vi);
}
}
class Load extends AsyncTask<URL, Integer, Long>
{
/*MyProgressDialog dialog;
JSONObject jobjectsee=null;JSONArray jarray=null;
String jsonresult="";
*/
// Log.e("current before webservice","current time service time"+);
MyProgressDialog dialog;
int strat;
public Load(int strat) {
super();
this.strat = strat;
}
String strjsonresult="";
protected void onPreExecute()
{
if(boolforprogressdialogmyfeed==true){
dialog=MyProgressDialog.show(getParent(), null, null);
dialog.getWindow().setGravity(Gravity.CENTER);
footerView.setVisibility(View.GONE);
// ptrstaggredview.getRefreshableView().re
// ptrstaggredview.h
}else{
footerView.setVisibility(View.VISIBLE);
}
}
#Override
protected Long doInBackground(URL... arg0) {
try {
if(strcurrenttab.equals("mystream")){
Log.e("onpost execute"," on doin of the mystream");
// Log.e("url is...",""+DataUrl.getHomePageByUSer(LogindUser.getUser().getUserId(), strat));
// strjsonresult=Netcon.getValuefromUrl(DataUrl.getHomePageByUSer(LogindUser.getUser().getUserId(), strat));
strjsonresult=Netcon.getValuefromUrl("http://166.78.178.47:8080/json/pinboard?userMystream.userID="+LogindUser.getUser().getUserId()+"&userMystream.start="+strat);
Log.e(" mystream response is ","<><><><<>"+"http://166.78.178.47:8080/json/pinboard?userMystream.userID="+LogindUser.getUser().getUserId()+"&userMystream.start="+strat);
}else if(strcurrenttab.equals("featured"))
{
Log.e("onpost execute"," on do in execut of the featured");
Log.e("url is...",""+DataUrl.getFeaturedImages(strat, LogindUser.getUser().getUserId()));
// featuredList_temp.clear();
strjsonresult=Netcon.getValuefromUrl(DataUrl.getFeaturedImages(strat, LogindUser.getUser().getUserId()));
}else if(strcurrenttab.equals("all"))
{
Log.e("onpost execute"," on doinback execut of the all");
Log.e("url is...",""+DataUrl.getHomePageByCategory(strat, 0, LogindUser.getUser().getUserId()));
// popularList_temp.clear();
strjsonresult=Netcon.getValuefromUrl(DataUrl.getHomePageByCategory(strat, 0, LogindUser.getUser().getUserId()));
}
//this for pulltorefresh
if(boolpulltorefresh==true){
mystreamList.clear();
ImageBOStaggredAdapter.views.clear();
boolpulltorefresh=false;
}
} catch (Exception e1) {
e1.printStackTrace();
}
return null;
}
#SuppressLint("NewApi")
protected void onPostExecute(Long result) {
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
getParent().runOnUiThread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
//calling();
try {
if(boolforprogressdialogmyfeed==true){
boolforprogressdialogmyfeed=false;
try{
dialog.dismiss();
}catch(Exception e){e.printStackTrace();}
}
if(strcurrenttab.equals("mystream")){
Log.e("onpost execute"," on post execut of the mystream");
/*JSONObject object = new JSONObject(strjsonresult);
if(object.getBoolean("statusFlag"))
{
JSONArray array= object.getJSONArray("homePageImages");
for(int i=0;i<array.length();i++)
{
ImagesBO imagesBO = new ImagesBO();
imagesBO= gson.fromJson(array.getJSONObject(i).toString(), ImagesBO.class);
// mystreamList.add(imagesBO); // commented by Ramesh for endlesscroll
mystreamList.add(imagesBO);
// popular_Adapter.notifyDataSetChanged();
}
}*/
JSONObject jsonObject = new JSONObject(strjsonresult);
JSONArray array = jsonObject.getJSONArray("images");
Log.e("Array size is","<>"+array.length());
for(int i=0;i<array.length();i++)
{
ImagesBO imagesBO = new ImagesBO();
imagesBO= gson.fromJson(array.getJSONObject(i).toString(), ImagesBO.class);
mystreamList.add(imagesBO);
// popularList.add(imagesBO); // added by Ramesh for endlessscroll
// Log.e("userid is","<><>"+imagesBO.getUserId()+imagesBO.getUsername());
}
}else if(strcurrenttab.equals("featured")){
Log.e("onpost execute"," on post execut of the featured");
JSONObject object = new JSONObject(strjsonresult);
JSONArray array= object.getJSONArray("featuredImages");
for(int i=0;i<array.length();i++)
{
ImagesBO imagesBO = new ImagesBO();
imagesBO= gson.fromJson(array.getJSONObject(i).toString(), ImagesBO.class);
// featuredList.add(imagesBO);
mystreamList.add(imagesBO); // added by Ramesh for endlessscroll
// popular_Adapter.notifyDataSetChanged();
}
}else if(strcurrenttab.equals("all")){
Log.e("onpost execute"," on post execut of the all");
JSONObject jsonObject = new JSONObject(strjsonresult);
JSONArray array = jsonObject.getJSONArray("homePageImages");
Log.e("Array size is","<>"+array.length());
for(int i=0;i<array.length();i++)
{
ImagesBO imagesBO = new ImagesBO();
imagesBO= gson.fromJson(array.getJSONObject(i).toString(), ImagesBO.class);
// popularList.add(imagesBO); // added by Ramesh for endlessscroll
mystreamList.add(imagesBO);
// popular_Adapter.notifyDataSetChanged();
// views_popular.add(popularimagelist);
}
}
popular_Adapter.notifyDataSetChanged();
Log.e("Sizeee","<>"+mystreamList.size());
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//
}
});
// dialog.dismiss();
}
}, 20000);
Set some minimum height android:minHeight="100dp" for your ImageView in the adapter xml.
I am developing one application in that I can shows route between source and destination And display some description about that route. Now I am trying to download that description in to my mobile. I am searched so such but I did not find any related example. please share any example for this
myCode
private class GetRouteTask extends AsyncTask<String, Void, String>{
private ProgressDialog pDialog;
String response="";
private WeakReference<ShowRoutesInMap> weakRef;
//public ArrayList<String> alter;
public ArrayList<String> route1;
public ArrayList<String> route2;
public ArrayList<String> route3;
PolylineOptions rectLine = null;
PolylineOptions rectLine1 = null;
PolylineOptions rectLine2 = null;
PolylineOptions rectLine3 = null;
public ArrayList<LatLng> directionPoint;
private ArrayList<String> alter;
public GetRouteTask(ShowRoutesInMap context){
this.weakRef =new WeakReference<ShowRoutesInMap>(context);
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
pDialog = new ProgressDialog(ShowRoutesInMap.this);
if(!isFinishing()){
pDialog.setMessage("Please wait For TrafficJam Route...");
pDialog.setCancelable(false);
pDialog.show();
}
}
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
try{
if(sourcePosition!=null && destinationPostion!=null){
document = v2GetRouteDirection.getDocument(sourcePosition, destinationPostion,GMapV2Direction.MODE_DRIVING);
}
}
catch(Exception e){
return "exception caught";
}
response = "Success";
return response;
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
// if(!isFinishing()){
pDialog.dismiss();
// }
route1 = new ArrayList<String>();
route2 = new ArrayList<String>();
route3 = new ArrayList<String>();
if(result.equalsIgnoreCase("exception caught")){
Toast.makeText(getApplicationContext(), "INVALID VALUES", Toast.LENGTH_LONG).show();
}
else{
if (weakRef.get() != null && ! weakRef.get().isFinishing()){
// if(response.equalsIgnoreCase("Success")){
alter = v2GetRouteDirection.getAlternativeRoutes(document);
int duration = v2GetRouteDirection.getDurationValue(document);
Log.e("TRAFFIC DURATIONTIME",""+duration);
int trfficClearTime = v2GetRouteDirection.getDistanceValue(document);
Log.e("TRAFFIC TIME", ""+trfficClearTime);
for( j=0;j<alter.size();j++){
directionPoint =v2GetRouteDirection.getDirection(document, j);
ArrayList<String> desc = v2GetRouteDirection.getDescription(document,j);
if(j==0){
for(int l=0;l<desc.size();l++){
route1.add(desc.get(l));
Log.e("ROUTE1", desc.get(l).replace("\\<.*?>",""));
}
}
else if(j==1){
for(int l=0;l<desc.size();l++){
route2.add(desc.get(l));
Log.e("ROTE2", desc.get(l).replace("\\<.*?>",""));
}
}
else if(j==2){
for(int l=0;l<desc.size();l++){
route3.add(desc.get(l));
Log.e("ROTE2", desc.get(l).replace("\\<.*?>",""));
}
}
rectLine = new PolylineOptions().width(5).color(Color.RED).geodesic(true);
for (int i = 0; i < directionPoint.size(); i++) {
rectLine.add(directionPoint.get(i));
}
googleMap.addPolyline(rectLine);
getMarkersOnMap(googleMap);
alterRoutes1.setText("");
if(alter.size()==1){
alterRoutes1.setText(alter.get(0));
}
else if(alter.size()>=1 && alter.size()<=2){
alterRoutes1.setText(alter.get(0));
alterRoutes2.setText(alter.get(1));
}
else if(alter.size()>=1 && alter.size()<=3){
alterRoutes1.setText(alter.get(0));
alterRoutes2.setText(alter.get(1));
alterRoutes3.setText(alter.get(2));
}
}
}
alterRoutes1.setOnClickListener(new OnClickListener() {
private ArrayList<LatLng> directionPoint1;
#Override
public void onClick(View v) { // TODO Auto-generated method stub
googleMap.clear();
// ArrayList<String> alter = v2GetRouteDirection.getAlternativeRoutes(document);
rectLine1 = new PolylineOptions().width(5).color(Color.GREEN).geodesic(true);
for( int k=0;k<alter.size();k++){
directionPoint1 =v2GetRouteDirection.getDirection(document, k);
for (int i = 0; i < directionPoint1.size(); i++) {
if(k==0){
rectLine1.add(directionPoint1.get(i));
}
}
googleMap.addPolyline(rectLine1);
getMarkersOnMap(googleMap);
}
for(int i=0;i<route1.size();i++){
showDirection.append(route1.get(i).replaceAll("\\<.*?>",""));
}
}
});
alterRoutes2.setOnClickListener(new OnClickListener() {
private ArrayList<LatLng> directionPoint2;
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
googleMap.clear();
showDirection.setText("");
rectLine2 = new PolylineOptions().width(5).color(Color.MAGENTA).geodesic(true);
for( int k=0;k<alter.size();k++){
directionPoint2 =v2GetRouteDirection.getDirection(document, k);
for (int i = 0; i < directionPoint2.size(); i++) {
if(k==1){
rectLine2.add(directionPoint2.get(i));
}
}
googleMap.addPolyline(rectLine2);
getMarkersOnMap(googleMap);
}
for(int i=0;i<route2.size();i++){
showDirection.append(route2.get(i).replaceAll("\\<.*?>",""));
}
}
});
alterRoutes3.setOnClickListener(new OnClickListener() {
private ArrayList<LatLng> directionPoint3;
int count=0;
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
googleMap.clear();
showDirection.setText("");
rectLine3 = new
PolylineOptions().width(5).color(Color.BLUE).geodesic(true);
for( int k=0;k<alter.size();k++){
directionPoint3
=v2GetRouteDirection.getDirection(document, k);
for (int i = 0; i < directionPoint3.size(); i++) {
if(k==2){
rectLine3.add(directionPoint3.get(i));
}
}
googleMap.addPolyline(rectLine3);
getMarkersOnMap(googleMap);
}
for(int i=0;i<route3.size();i++){
showDirection.append(""+ ++count);
showDirection.append(route3.get(i).replaceAll("\\<.*?
>",""));
}
}
});
}
}
}
public void getMarkersOnMap(GoogleMap gmap){
Markeropition1.position(sourcePosition).icon(BitmapDescriptorFactory
.defaultMarker(BitmapDescriptorFactory.HUE_AZURE))
.flat(true);
Markeropition2.position(destinationPostion).icon(BitmapDescriptorFactory
.defaultMarker(BitmapDescriptorFactory.HUE_AZURE))
.flat(true);
Markeropition1.draggable(true);
Markeropition2.draggable(true);
gmap.moveCamera(CameraUpdateFactory.newLatLngZoom(sourcePosition,10));
gmap.addMarker(Markeropition1);
gmap.addMarker(Markeropition2);
}
It is possible to generate pdf document in android from Api level 19. You can take reference from this link http://developer.android.com/reference/android/graphics/pdf/package-summary.html
I have customized the code of EndlessAdapter in my app but one mistake done by me as this Endless Adapter always download data in the background instead it should download the same after user scroll downs the list and I unable to find the same mistake in our project. Due to this mistake my app sometimes returns OutOfMemoryException which is not acceptable.
Please suggest me any solution regarding the same.
Code:
*MyEndlessAdapter:*
class DemoAdapterCat extends EndlessAdapter {
private RotateAnimation rotate=null;
ArrayList<String> tempListNamesCat = new ArrayList<String>();
ArrayList<String> tempListImagesCat = new ArrayList<String>();
ArrayList<String> tempListYearCat1 = new ArrayList<String>();
ArrayList<String> tempListYearCat2 = new ArrayList<String>();
ArrayList<String> tempListmpgCat1 = new ArrayList<String>();
ArrayList<String> tempListmpgCat2 = new ArrayList<String>();
ArrayList<String> tempListpriceCat1 = new ArrayList<String>();
ArrayList<String> tempListpriceCat2 = new ArrayList<String>();
ArrayList<String> tempListRatingCat1 = new ArrayList<String>();
ArrayList<String> tempListRatingCat2 = new ArrayList<String>();
DemoAdapterCat() {
super(new CategoryListLazyAdapter(ResearchList.this, countriesSubCat, imagesSubCat, YearSubCat1,YearSubCat2, mpgSubCat1,mpgSubCat2, priceSubCat1,priceSubCat2, ratingSubCat1, ratingSubCat2));
Utility util = new Utility();
util.setListViewHeightBasedOnChildren(lvCategory);
rotate=new RotateAnimation(0f, 360f, Animation.RELATIVE_TO_SELF,
0.5f, Animation.RELATIVE_TO_SELF,
0.5f);
rotate.setDuration(600);
rotate.setRepeatMode(Animation.RESTART);
rotate.setRepeatCount(Animation.INFINITE);
}
/*
#Override
public int getCount()
{
//return brandList.getDisplayNames().size();
return countriesSubCat.size();
}*/
#Override
protected View getPendingView(ViewGroup parent) {
row=getLayoutInflater().inflate(R.layout.categorylist, null);
child=row.findViewById(R.id.tv_CategoryItem_Name);
child.setVisibility(View.GONE);
child = row.findViewById(R.id.tv_CategoryItem_MPG1);
child.setVisibility(View.GONE);
child = row.findViewById(R.id.tv_CategoryItem_MPG2);
child.setVisibility(View.GONE);
child = row.findViewById(R.id.tv_CategoryItem_Price1);
child.setVisibility(View.GONE);
child = row.findViewById(R.id.tv_CategoryItem_Price2);
child.setVisibility(View.GONE);
child = row.findViewById(R.id.tv_CategoryItem_Rating1);
child.setVisibility(View.GONE);
child = row.findViewById(R.id.tv_CategoryItem_Rating2);
child.setVisibility(View.GONE);
child = row.findViewById(R.id.tv_CategoryItem_Year1);
child.setVisibility(View.GONE);
child = row.findViewById(R.id.tv_CategoryItem_Year2);
child.setVisibility(View.GONE);
/*child = row.findViewById(R.id.img_CategoryItem);
child.setVisibility(View.GONE);
child = row.findViewById(R.id.img_CategoryItem_Arrow);
child.setVisibility(View.GONE);*/
/*child = row.findViewById(R.id.linear_main_MPG);
child.setVisibility(View.GONE);*/
child=row.findViewById(R.id.throbber);
child.setVisibility(View.VISIBLE);
child.startAnimation(rotate);
return(row);
}
#Override
protected boolean cacheInBackground() {
SystemClock.sleep(10000);
tempListNamesCat.clear();
tempListImagesCat.clear();
tempListmpgCat1.clear();
tempListmpgCat2.clear();
tempListpriceCat1.clear();
tempListpriceCat2.clear();
tempListYearCat1.clear();
tempListYearCat2.clear();
tempListRatingCat1.clear();
tempListRatingCat2.clear();
int lastOffset = getLastOffset();
if(lastOffset < LIST_SIZE){
int limit = lastOffset + BATCH_SIZE;
for(int i=(lastOffset+1); (i<=limit && i<LIST_SIZE); i++){
tempListNamesCat.add(coll.getDisplayNames().get(i));
tempListImagesCat.add(coll.getImages().get(i));
tempListmpgCat1.add(coll.getMpg().get(i));
tempListmpgCat2.add(coll.getMpg().get(i+1));
tempListpriceCat1.add(coll.getPrice().get(i));
tempListpriceCat2.add(coll.getPrice().get(i+1));
tempListRatingCat1.add(coll.getRating().get(i));
tempListRatingCat2.add(coll.getRating().get(i+1));
tempListYearCat1.add(coll.getYears().get(i));
tempListYearCat2.add(coll.getYears().get(i+1));
}
setLastOffset(limit);
if(limit<LIST_SIZE){
//return true;
return(getWrappedAdapter().getCount()<coll.getDisplayNames().size());
} else {
return false;
}
} else {
return false;
}
}
#Override
protected void appendCachedData() {
#SuppressWarnings("unchecked")
//Activity activity = this;
//ArrayAdapter<String> arrAdapterNew = (ArrayAdapter<String>)getWrappedAdapter();
CategoryListLazyAdapter arrAdapterNewCategory = (CategoryListLazyAdapter)getWrappedAdapter();
//int listLen = tempList.size();
// int listLen = tempListNames.size();
countriesSubCat.addAll(tempListNamesCat);
imagesSubCat.addAll(tempListImagesCat);
mpgSubCat1.addAll(tempListmpgCat1);
mpgSubCat2.addAll(tempListmpgCat2);
priceSubCat1.addAll(tempListpriceCat1);
priceSubCat2.addAll(tempListpriceCat2);
ratingSubCat1.addAll(tempListRatingCat1);
ratingSubCat2.addAll(tempListRatingCat2);
YearSubCat1.addAll(tempListYearCat1);
YearSubCat2.addAll(tempListYearCat2);
arrAdapterNewCategory.notifyDataSetChanged();
Utility util = new Utility();
util.setListViewHeightBasedOnChildren(lvCategory);
/* for(int i=0; i<listLen; i++){
// arrAdapterNew.add(tempList.get(i));
}*/
}
}
Set Demoadapter to the list:
public void setValuesInCategoryChildSortByAZ(String url,final String filter, final String from, final String to)
{
if(isOnline())
{
final ProgressDialog dialog = ProgressDialog.show(
ResearchList.this, "Research List ",
"Please wait... ", true);
final Handler handler = new Handler() {
public void handleMessage(Message msg) {
// System.out.println("The id after Save:"+id.get(0).toString());
// catagory.addAll(keyword_vector1);
linear_Category_Child.setVisibility(View.GONE);
linear_Category_Child_Child.setVisibility(View.VISIBLE);
//tv_Child_Header.setText("Volvo");
/*adapter = new CategoryListLazyAdapter(
ResearchList.this);
lvCategory.setAdapter(adapter);*/
demoAdapterCat.notifyDataSetChanged();
Utility util = new Utility();
util.setListViewHeightBasedOnChildren(lvCategory);
dialog.dismiss();
}
};
final Thread checkUpdate = new Thread() {
public void run() {
try {
String sortEncode = URLEncoder.encode("alpha");
String filterEncode = URLEncoder.encode(filter);
String clientEncode = URLEncoder.encode("10030812");
String fromEncode = URLEncoder.encode(from);
String toEncode = URLEncoder.encode(to);
String catUrl = "/v1/vehicles/get-make-models.json?sort="+sortEncode+"&filter="+filterEncode+"&client-id="+clientEncode+"&from="+fromEncode;
genSig = new GetSignature(catUrl, "acura");
try {
signature = genSig.getUrlFromString();
} catch (InvalidKeyException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (NoSuchAlgorithmException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
// jsonString =
// getJsonSring("http://api.highgearmedia.com/v1/vehicles/get-models.json?make=acura&client-id=10030812&signature=LWQbdAlJVxlXZ1VO2mfqAA==");
//String signatureEncode = URLEncoder.encode(signature);
String urlEncode = URLEncoder.encode(catUrl+"&signature="+signature);
jsonString = getJsonSring("http://apibeta.highgearmedia.com"+catUrl+"&signature="+signature);
System.out.println("The json category:===>"+jsonString);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (URISyntaxException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
JsonParse json = new JsonParse(jsonString);
json.parseCat();
handler.sendEmptyMessage(0);
}
};
checkUpdate.start();
}else
{
AlertDialog.Builder builder = new Builder(ResearchList.this);
builder.setTitle("Attention!");
builder.setMessage("Network Connection unavailable.");
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
}
});
builder.create().show();
}
}
Thanks in advance.
I unable to find the same mistake in our project
The EndlessAdapter sample app is here: https://github.com/commonsguy/cwac-endless/tree/master/demo.
If you look at that sample app, you will notice that it does not fork any threads.
If you read the EndlessAdapter documentation, you will see:
Your EndlessAdapter subclass also needs to implement cacheInBackground(). This method will be called from a background thread, and it needs to download more data that will eventually be added to the ListAdapter you used in the constructor. While the demo application simply sleeps for 10 seconds, a real application might make a Web service call or otherwise load in more data.
Since this method is called on a background thread, you do not need to fork your own thread. However, at the same time, do not try to update the UI directly.
So, change your project to not fork your own thread, but instead do your work in cacheInBackground() to retrieve and add the next batch of data.
If that approach does not fit the way your app needs to run, that is fine, but you may have difficulty in using EndlessAdapter.