JSON parsing from database - android

I am trying to parse JSON from one of my json created but I am unable to parse it an throws a null pointer exception at the showdata() method. what is it that i am missing.I have checked with the array name and the php script. How do I implement it to solve the problem
parse activity
import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class ParseJSON extends ActionBarActivity implements View.OnClickListener {
private String myJSONString;
private static final String JSON_ARRAY="result";
private static final String ID = "id";
//private static final String NAME ="name";
//private static final String PROFESSION= "profession";
private JSONArray users = null;
private int TRACK= 0;
private EditText editTextId;
private EditText editTextName;
private EditText editTextProf;
Button btnPrev;
Button btnNext;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_parse_json);
Intent intent =getIntent();
myJSONString = intent.getStringExtra(MainActivity.MY_JSON);
editTextId = (EditText)findViewById(R.id.editTextID);
//editTextName=(EditText)findViewById(R.id.editTextUsername);
//editTextProf=(EditText)findViewById(R.id.editTextPassword);
btnNext=(Button)findViewById(R.id.buttonNext);
btnPrev=(Button)findViewById(R.id.buttonPrev);
btnPrev.setOnClickListener(this);
btnNext.setOnClickListener(this);
extractJSON();
showData();
}
private void extractJSON() {
try {
JSONObject jsonObject = new JSONObject();
users = jsonObject.getJSONArray(JSON_ARRAY);
} catch (JSONException e) {
e.printStackTrace();
}
}
private void moveNext(){
if(TRACK<users.length()){
TRACK++;
}
showData();
}
private void movePrev(){
if(TRACK>0){
TRACK--;
}
showData();
}
private void showData(){
try{
JSONObject jsonObject= users.getJSONObject(TRACK);
editTextId.setText(jsonObject.getString(ID));
// editTextName.setText(jsonObject.getString(NAME));
// editTextProf.setText(jsonObject.getString(PROFESSION));
}catch(JSONException e){
e.printStackTrace();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_parse_json, menu);
return true;
}
#Override
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_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onClick(View view) {
if(view==btnNext){
moveNext();
}
else if (view==btnPrev)
movePrev();
}
}
mainactivity
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.text.method.ScrollingMovementMethod;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
public class MainActivity extends ActionBarActivity implements View.OnClickListener {
private TextView textviewJSON;
private Button buttonGet;
private Button buttonParse;
public static final String MY_JSON="MY_JSON";
public static final String JSON_URL="http://www.humanfox.com/capsule/dash.php";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textviewJSON=(TextView)findViewById(R.id.textViewJSON);
textviewJSON.setMovementMethod(new ScrollingMovementMethod());
buttonGet=(Button)findViewById(R.id.buttonGet);
buttonParse=(Button)findViewById(R.id.buttonParse);
buttonGet.setOnClickListener(this);
buttonParse.setOnClickListener(this);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
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_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onClick(View view) {
if (view==buttonGet){
getJSON(JSON_URL);
}
else if(view==buttonParse){
showParseActivity();
}
}
private void showParseActivity() {
Intent intent = new Intent(this, ParseJSON.class);
intent.putExtra(MY_JSON,textviewJSON.getText().toString());
startActivity(intent);
}
private void getJSON(String url){
class GetJSON extends AsyncTask<String, Void, String>{
ProgressDialog loading;
#Override
protected void onPreExecute() {
super.onPreExecute();
loading= ProgressDialog.show(MainActivity.this, "Please Wait.....",null, true , true);
}
#Override
protected String doInBackground(String... params) {
String uri=params[0];
BufferedReader bufferedReader= null;
try{
URL url = new URL(uri);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
StringBuilder sb = new StringBuilder();
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;
}
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
loading.dismiss();
}
}
GetJSON gj = new GetJSON();
gj.execute(url);
}
}

I believe the issue is with the way you are trying to iterate through the JSONArray list, try this code it is also available on Github
public class ParseJSONActivity extends AppCompatActivity {
private Button button;
private Button previous_Button;
private Button next_Button;
private ListView listView;
private ArrayList<People> peoples;
private MyAdapter adapter;
private int TRACK = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_parse_json);
Toolbar toolbar = (Toolbar) findViewById(R.id.my_custom_toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
initializeUI();
}
private void initializeUI() {
button = (Button) findViewById(R.id.ParseJSONActivity_ok_button);
previous_Button = (Button) findViewById(R.id.ParseJSONActivity_Previous_button);
previous_Button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (peoples != null) {
if (peoples.size() > 0) {
if ((TRACK < peoples.size() - 1) && (TRACK >= 1)) {
People people = (People) listView.getItemAtPosition(--TRACK);
for (People single_item : peoples) {
single_item.setSelected(false);
}
people.setSelected(true);
adapter.notifyDataSetChanged();
}else{
TRACK = 0;
}
}
}
}
});
next_Button = (Button) findViewById(R.id.ParseJSONActivity_next_button);
next_Button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (peoples != null) {
if (peoples.size() > 0) {
if (TRACK < peoples.size() - 2) {
People people = (People) listView.getItemAtPosition(++TRACK);
for (People single_item : peoples) {
single_item.setSelected(false);
}
people.setSelected(true);
adapter.notifyDataSetChanged();
}else {
System.out.println("TRACK: "+TRACK);
TRACK = 0;
}
}
}else{
System.out.println("peoples is null");
}
}
});
listView = (ListView) findViewById(R.id.ParseJSONActivity_listView);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if (peoples != null) {
if (peoples.size() > 0) {
TRACK = position;
People people = (People) listView.getItemAtPosition(position);
for (People single_item : peoples) {
single_item.setSelected(false);
}
people.setSelected(true);
adapter.notifyDataSetChanged();
}
}
}
});
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new DownloadJSON().execute();
}
});
}
private class DownloadJSON extends AsyncTask<Void, Void, Void> {
#Override
protected Void doInBackground(Void... params) {
try {
URL url = new URL("http://www.humanfox.com/capsule/dash.php");
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.connect();
String result = IOUtils.toString(httpURLConnection.getInputStream());
System.out.println("" + result);
if (result != null) {
JSONObject result_jsonObject = new JSONObject(result);
JSONArray result_JsonArray = result_jsonObject.getJSONArray("result");
if (result_JsonArray != null) {
if (result_JsonArray.length() > 0) {
peoples = new ArrayList<>();
for (int i = 0; i < result_JsonArray.length(); i++) {
People people = new People();
JSONObject jsonObject = result_JsonArray.getJSONObject(i);
people.setId("" + jsonObject.getString("id"));
people.setName("" + jsonObject.getString("Name"));
people.setProfession("" + jsonObject.getString("profession"));
people.setImage("" + jsonObject.getString("image"));
peoples.add(people);
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
if (peoples != null) {
if (peoples.size() > 0) {
adapter = new MyAdapter(getApplicationContext(), R.layout.single_item_custom_one, peoples);
listView.setAdapter(adapter);
adapter.notifyDataSetChanged();
}
}
}
}
private class MyAdapter extends ArrayAdapter {
private ArrayList<People> a_productInfos;
private Context a_context;
private LayoutInflater a_layoutInflater;
public MyAdapter(Context context, int resource, ArrayList<People> a_productInfos) {
super(context, resource, a_productInfos);
this.a_productInfos = a_productInfos;
this.a_context = context;
a_layoutInflater = LayoutInflater.from(this.a_context);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
ViewHolder holder = null;
if (row == null) {
row = a_layoutInflater.inflate(R.layout.single_item_custom_one, parent, false);
holder = new ViewHolder();
holder.product_name = (TextView) row.findViewById(R.id.single_item_custom_one_textView);
holder.item_LinearLayout = (LinearLayout) row.findViewById(R.id.single_item_custom_one_linearLayout);
row.setTag(holder);
} else {
holder = (ViewHolder) row.getTag();
}
final People productInfo = a_productInfos.get(position);
holder.product_name.setText("" + productInfo.getName());
if (productInfo.isSelected) {
holder.item_LinearLayout.setBackgroundColor(Color.parseColor("#ff44ff"));
} else {
holder.item_LinearLayout.setBackgroundColor(Color.parseColor("#ffffff"));
}
return row;
}
class ViewHolder {
TextView product_name;
LinearLayout item_LinearLayout;
}
}
private class People {
private String id;
private String Name;
private String profession;
private String image;
boolean isSelected;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public String getProfession() {
return profession;
}
public void setProfession(String profession) {
this.profession = profession;
}
public String getImage() {
return image;
}
public void setImage(String image) {
this.image = image;
}
public boolean isSelected() {
return isSelected;
}
public void setSelected(boolean selected) {
isSelected = selected;
}
}
}
Output:

Related

Quiz app Randomize answers on Android studio

I bought in courses on creating android application "Quiz app". But in this course, a random order of answers is not implemented. I'm a beginner programmer without any technical education I know that I need to insert somewhere in the code
"Collections.shuffle (list)" but I can not yet figure out where. Help please. I'm making an application for students that would make life easier for them. Helping me you are helping them.
QUIZ ACTIVITY
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.support.v4.app.FragmentManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Html;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import com.vn.iambulance.prototype_20.R;
import com.vn.iambulance.prototype_20.adapters.QuizAdapter;
import com.vn.iambulance.prototype_20.constants.AppConstants;
import com.vn.iambulance.prototype_20.data.preference.AppPreference;
import com.vn.iambulance.prototype_20.listeners.ListItemClickListener;
import com.vn.iambulance.prototype_20.models.quiz.QuizModel;
import com.vn.iambulance.prototype_20.models.quiz.ResultModel;
import com.vn.iambulance.prototype_20.utilities.ActivityUtilities;
import com.vn.iambulance.prototype_20.utilities.BeatBox;
import com.vn.iambulance.prototype_20.utilities.DialogUtilities;
import com.vn.iambulance.prototype_20.utilities.SoundUtilities;
public class QuizActivity extends BaseActivity implements DialogUtilities.OnCompleteListener {
private Activity mActivity;
private Context mContext;
private ImageButton btnSpeaker;
private Button btnNext;
private RecyclerView mRecyclerQuiz;
private TextView tvQuestionText;
private TextView tvQuestionTitle;
private ImageView imgFirstLife, imgSecondLife, imgThirdLife, imgFourthLife, imgFifthLife;
private QuizAdapter mAdapter = null;
private List<QuizModel> mItemList;
ArrayList<String> mOptionList;
ArrayList<String> mBackgroundColorList;
private int mQuestionPosition = 0;
private int mQuestionsCount = 0;
private int mScore = 0, mWrongAns = 0, mSkip = 0;
private int mLifeCounter = 5;
private boolean mUserHasPressed = false;
private boolean mIsSkipped = false, mIsCorrect = false;
private String mQuestionText, mGivenAnsText, mCorrectAnsText, mCategoryId;
private ArrayList<ResultModel> mResultList;
private BeatBox mBeatBox;
private List<SoundUtilities> mSounds;
private boolean isSoundOn;
#RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//TODO: initializeRewardedAds();
//TODO: loadRewardedVideoAds();
initVar();
initView();
loadData();
initListener();
}
private void initVar() {
mActivity = QuizActivity.this;
mContext = mActivity.getApplicationContext();
Intent intent = getIntent();
if (intent != null) {
mCategoryId = intent.getStringExtra(AppConstants.BUNDLE_KEY_INDEX);
}
mItemList = new ArrayList<>();
mOptionList = new ArrayList<>();
mBackgroundColorList = new ArrayList<>();
mResultList = new ArrayList<>();
mBeatBox = new BeatBox(mActivity);
mSounds = mBeatBox.getSounds();
}
private void initView() {
setContentView(R.layout.activity_quiz);
imgFirstLife = (ImageView) findViewById(R.id.firstLife);
imgSecondLife = (ImageView) findViewById(R.id.secondLife);
imgThirdLife = (ImageView) findViewById(R.id.thirdLife);
imgFourthLife = (ImageView) findViewById(R.id.fourthLife);
imgFifthLife = (ImageView) findViewById(R.id.fifthLife);
btnSpeaker = (ImageButton) findViewById(R.id.btnSpeaker);
btnNext = (Button) findViewById(R.id.btnNext);
tvQuestionText = (TextView) findViewById(R.id.tvQuestionText);
tvQuestionTitle = (TextView) findViewById(R.id.tvQuestionTitle);
mRecyclerQuiz = (RecyclerView) findViewById(R.id.rvQuiz);
mRecyclerQuiz.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
mAdapter = new QuizAdapter(mContext, mActivity, mOptionList, mBackgroundColorList);
mRecyclerQuiz.setAdapter(mAdapter);
initToolbar(true);
setToolbarTitle(getString(R.string.quiz));
enableUpButton();
initLoader();
}
#RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
private void loadData() {
showLoader();
isSoundOn = AppPreference.getInstance(mActivity).getBoolean(AppConstants.KEY_SOUND, true);
setSpeakerImage();
loadJson();
}
#RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
private void setSpeakerImage() {
if (isSoundOn) {
btnSpeaker.setImageResource(R.drawable.ic_speaker);
} else {
btnSpeaker.setImageResource(R.drawable.ic_speaker_not);
}
}
public void initListener() {
btnSpeaker.setOnClickListener(new View.OnClickListener() {
#RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
#Override
public void onClick(View view) {
isSoundOn = !isSoundOn;
AppPreference.getInstance(mActivity).setBoolean(AppConstants.KEY_SOUND, isSoundOn);
setSpeakerImage();
}
});
btnNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (!mUserHasPressed) {
FragmentManager manager = getSupportFragmentManager();
DialogUtilities dialog = DialogUtilities.newInstance(getString(R.string.skip_text), getString(R.string.skip_prompt), getString(R.string.yes), getString(R.string.no), AppConstants.BUNDLE_KEY_SKIP_OPTION);
dialog.show(manager, AppConstants.BUNDLE_KEY_DIALOG_FRAGMENT);
} else {
updateResultSet();
setNextQuestion();
}
}
});
mAdapter.setItemClickListener(new ListItemClickListener() {
#Override
public void onItemClick(int position, View view) {
if (!mUserHasPressed) {
int clickedAnswerIndex = position;
if (mItemList.get(mQuestionPosition).getCorrectAnswer() != -1) {
for (int currentItemIndex = 0; currentItemIndex < mOptionList.size(); currentItemIndex++) {
if (currentItemIndex == clickedAnswerIndex && currentItemIndex == mItemList.get(mQuestionPosition).getCorrectAnswer()) {
mBackgroundColorList.set(currentItemIndex, AppConstants.COLOR_GREEN);
mScore++;
mIsCorrect = true;
if (isSoundOn) {
mBeatBox.play(mSounds.get(AppConstants.BUNDLE_KEY_ZERO_INDEX));
}
} else if (currentItemIndex == clickedAnswerIndex && !(currentItemIndex == mItemList.get(mQuestionPosition).getCorrectAnswer())) {
mBackgroundColorList.set(currentItemIndex, AppConstants.COLOR_RED);
mWrongAns++;
if (isSoundOn) {
mBeatBox.play(mSounds.get(AppConstants.BUNDLE_KEY_SECOND_INDEX));
}
decreaseLifeAndStatus();
} else if (currentItemIndex == mItemList.get(mQuestionPosition).getCorrectAnswer()) {
mBackgroundColorList.set(currentItemIndex, AppConstants.COLOR_GREEN);
((LinearLayoutManager) mRecyclerQuiz.getLayoutManager()).scrollToPosition(currentItemIndex);
}
}
} else {
mBackgroundColorList.set(clickedAnswerIndex, AppConstants.COLOR_GREEN);
mScore++;
mIsCorrect = true;
mBeatBox.play(mSounds.get(AppConstants.BUNDLE_KEY_ZERO_INDEX));
}
mGivenAnsText = mItemList.get(mQuestionPosition).getAnswers().get(clickedAnswerIndex);
mCorrectAnsText = mItemList.get(mQuestionPosition).getAnswers().get(mItemList.get(mQuestionPosition).getCorrectAnswer());
mUserHasPressed = true;
mAdapter.notifyDataSetChanged();
}
}
});
}
public void decreaseLifeAndStatus() {
mLifeCounter--;
setLifeStatus();
}
void increaseLifeAndStatus() {
if (mLifeCounter < AppConstants.BUNDLE_KEY_MAX_LIFE) {
mLifeCounter++;
setLifeStatus();
}
}
public void setLifeStatus() {
switch (mLifeCounter) {
case 1:
imgFirstLife.setVisibility(View.VISIBLE);
imgSecondLife.setVisibility(View.GONE);
imgThirdLife.setVisibility(View.GONE);
imgFourthLife.setVisibility(View.GONE);
imgFifthLife.setVisibility(View.GONE);
break;
case 2:
imgFirstLife.setVisibility(View.VISIBLE);
imgSecondLife.setVisibility(View.VISIBLE);
imgThirdLife.setVisibility(View.GONE);
imgFourthLife.setVisibility(View.GONE);
imgFifthLife.setVisibility(View.GONE);
break;
case 3:
imgFirstLife.setVisibility(View.VISIBLE);
imgSecondLife.setVisibility(View.VISIBLE);
imgThirdLife.setVisibility(View.VISIBLE);
imgFourthLife.setVisibility(View.GONE);
imgFifthLife.setVisibility(View.GONE);
break;
case 4:
imgFirstLife.setVisibility(View.VISIBLE);
imgSecondLife.setVisibility(View.VISIBLE);
imgThirdLife.setVisibility(View.VISIBLE);
imgFourthLife.setVisibility(View.VISIBLE);
imgFifthLife.setVisibility(View.GONE);
break;
case 5:
imgFirstLife.setVisibility(View.VISIBLE);
imgSecondLife.setVisibility(View.VISIBLE);
imgThirdLife.setVisibility(View.VISIBLE);
imgFourthLife.setVisibility(View.VISIBLE);
imgFifthLife.setVisibility(View.VISIBLE);
break;
default:
imgFirstLife.setVisibility(View.GONE);
imgSecondLife.setVisibility(View.GONE);
imgThirdLife.setVisibility(View.GONE);
imgFourthLife.setVisibility(View.GONE);
imgFifthLife.setVisibility(View.GONE);
break;
}
}
public void setNextQuestion() {
if (isSoundOn) {
mBeatBox.play(mSounds.get(AppConstants.BUNDLE_KEY_FIRST_INDEX));
}
mUserHasPressed = false;
if (mQuestionPosition < mItemList.size() - 1 && mLifeCounter > 0) {
mQuestionPosition++;
updateQuestionsAndAnswers();
} else if (mQuestionPosition < mItemList.size() - 1 && mLifeCounter == 0) {
FragmentManager manager = getSupportFragmentManager();
DialogUtilities dialog = DialogUtilities.newInstance(getString(R.string.reward_dialog_title), getString(R.string.reward_dialog_message), getString(R.string.yes), getString(R.string.no), AppConstants.BUNDLE_KEY_REWARD_OPTION);
dialog.show(manager, AppConstants.BUNDLE_KEY_DIALOG_FRAGMENT);
} else {
ActivityUtilities.getInstance().invokeScoreCardActivity(mActivity, ScoreCardActivity.class, mQuestionsCount, mScore, mWrongAns, mSkip, mCategoryId, mResultList, true);
AppPreference.getInstance(mActivity).setQuizResult(mCategoryId, mScore);
}
}
public void updateQuestionsAndAnswers() {
mOptionList.clear();
mBackgroundColorList.clear();
((LinearLayoutManager) mRecyclerQuiz.getLayoutManager()).scrollToPosition(AppConstants.BUNDLE_KEY_ZERO_INDEX);
mOptionList.addAll(mItemList.get(mQuestionPosition).getAnswers());
mBackgroundColorList.addAll(mItemList.get(mQuestionPosition).getBackgroundColors());
mAdapter.notifyDataSetChanged();
mQuestionText = mItemList.get(mQuestionPosition).getQuestion();
tvQuestionText.setText(Html.fromHtml(mQuestionText));
tvQuestionTitle.setText(getString(R.string.quiz_question_title, mQuestionPosition + 1, mQuestionsCount));
}
public void quizActivityClosePrompt() {
FragmentManager manager = getSupportFragmentManager();
DialogUtilities dialog = DialogUtilities.newInstance(getString(R.string.exit), getString(R.string.cancel_prompt), getString(R.string.yes), getString(R.string.no), AppConstants.BUNDLE_KEY_CLOSE_OPTION);
dialog.show(manager, AppConstants.BUNDLE_KEY_DIALOG_FRAGMENT);
}
private void loadJson() {
StringBuffer sb = new StringBuffer();
BufferedReader br = null;
try {
br = new BufferedReader(new InputStreamReader(getAssets().open(AppConstants.QUESTION_FILE)));
String temp;
while ((temp = br.readLine()) != null)
sb.append(temp);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
br.close();
} catch (Exception e) {
e.printStackTrace();
}
}
parseJson(sb.toString());
}
public void parseJson(String jsonData) {
try {
JSONObject jsonObjMain = new JSONObject(jsonData);
JSONArray jsonArray = jsonObjMain.getJSONArray(AppConstants.JSON_KEY_QUESTIONNAIRY);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObj = jsonArray.getJSONObject(i);
String question = jsonObj.getString(AppConstants.JSON_KEY_QUESTION);
int correctAnswer = Integer.parseInt(jsonObj.getString(AppConstants.JSON_KEY_CORRECT_ANS));
String categoryId = jsonObj.getString(AppConstants.JSON_KEY_CATEGORY_ID);
Log.d("TAG", categoryId.toString());
JSONArray jsonArray2 = jsonObj.getJSONArray(AppConstants.JSON_KEY_ANSWERS);
ArrayList<String> contents = new ArrayList<>();
ArrayList<String> backgroundColors = new ArrayList<>();
for (int j = 0; j < jsonArray2.length(); j++) {
String item_title = jsonArray2.get(j).toString();
contents.add(item_title);
backgroundColors.add(AppConstants.COLOR_WHITE);
}
if (mCategoryId.equals(categoryId)) {
mItemList.add(new QuizModel(question, contents, correctAnswer, categoryId, backgroundColors));
}
}
mQuestionsCount = mItemList.size();
Collections.shuffle(mItemList);
hideLoader();
updateQuestionsAndAnswers();
} catch (JSONException e) {
e.printStackTrace();
showEmptyView();
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
quizActivityClosePrompt();
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onBackPressed() {
quizActivityClosePrompt();
}
#Override
public void onComplete(Boolean isOkPressed, String viewIdText) {
if (isOkPressed) {
if (viewIdText.equals(AppConstants.BUNDLE_KEY_CLOSE_OPTION)) {
ActivityUtilities.getInstance().invokeNewActivity(mActivity, MainActivity.class, true);
} else if (viewIdText.equals(AppConstants.BUNDLE_KEY_SKIP_OPTION)) {
mSkip++;
mIsSkipped = true;
mGivenAnsText = getResources().getString(R.string.skipped_text);
mCorrectAnsText = mItemList.get(mQuestionPosition).getAnswers().get(mItemList.get(mQuestionPosition).getCorrectAnswer());
updateResultSet();
setNextQuestion();
} else if (viewIdText.equals(AppConstants.BUNDLE_KEY_REWARD_OPTION)) {
//TODO: mRewardedVideoAd.show();
}
} else if (!isOkPressed && viewIdText.equals(AppConstants.BUNDLE_KEY_REWARD_OPTION)) {
ActivityUtilities.getInstance().invokeScoreCardActivity(mActivity, ScoreCardActivity.class, mQuestionsCount, mScore, mWrongAns, mSkip, mCategoryId, mResultList, true);
AppPreference.getInstance(mContext).setQuizResult(mCategoryId, mScore);
AppPreference.getInstance(mContext).setQuizQuestionsCount(mCategoryId, mQuestionsCount);
}
}
public void updateResultSet() {
mResultList.add(new ResultModel(mQuestionText, mGivenAnsText, mCorrectAnsText, mIsCorrect, mIsSkipped));
mIsCorrect = false;
mIsSkipped = false;
}
#Override
protected void onDestroy() {
super.onDestroy();
mBeatBox.release();
}
}
QUIZ ADAPTER
import android.app.Activity;
import android.content.Context;
import android.support.v7.widget.CardView;
import android.support.v7.widget.RecyclerView;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import java.util.ArrayList;
import com.vn.iambulance.prototype_20.R;
import com.vn.iambulance.prototype_20.listeners.ListItemClickListener;
public class QuizAdapter extends RecyclerView.Adapter<QuizAdapter.ViewHolder> {
private Context mContext;
private Activity mActivity;
private ArrayList<String> mItemList;
private ArrayList<String> mColorList;
private ListItemClickListener mItemClickListener;
public QuizAdapter (Context mContext, Activity mActivity, ArrayList<String> mItemList, ArrayList<String> mColorList) {
this.mContext = mContext;
this.mActivity = mActivity;
this.mItemList = mItemList;
this.mColorList = mColorList;
}
public void setItemClickListener(ListItemClickListener itemClickListener) {
this.mItemClickListener = itemClickListener;
}
#Override
public QuizAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_quiz, parent, false);
return new QuizAdapter.ViewHolder(view, viewType, mItemClickListener);
}
public static class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
private TextView tvItemTitle;
private CardView lytContainer;
private ListItemClickListener itemClickListener;
public ViewHolder(View itemView, int viewType, ListItemClickListener itemClickListener) {
super(itemView);
this.itemClickListener = itemClickListener;
// Find all views ids
tvItemTitle = itemView.findViewById(R.id.answer_text);
lytContainer = itemView.findViewById(R.id.card_view);
lytContainer.setOnClickListener(this);
}
#Override
public void onClick(View view) {
if (itemClickListener != null) {
itemClickListener.onItemClick(getLayoutPosition(), view);
}
}
}
#Override
public int getItemCount() {
return (null != mItemList ? mItemList.size() : 0);
}
#Override
public void onBindViewHolder(QuizAdapter.ViewHolder mainHolder, int position) {
final String model = mItemList.get(position);
final String model1 = mColorList.get(position);
// setting data over views
mainHolder.tvItemTitle.setText(Html.fromHtml(model));
mainHolder.tvItemTitle.setBackgroundResource(mActivity.getResources().getIdentifier(model1, "drawable", mActivity.getPackageName()));
}
}
QUIZ MODEL
import android.os.Parcel;
import android.os.Parcelable;
import java.util.ArrayList;
public class QuizModel implements Parcelable {
String question;
ArrayList<String> answers;
int correctAnswer;
String questinCategoryId;
ArrayList<String> backgroundColors;
public QuizModel (String question, ArrayList<String> answers, int correctAnswer, String questinCategoryId, ArrayList<String> backgroundColors) {
this.question = question;
this.correctAnswer = correctAnswer;
this.answers = answers;
this.questinCategoryId = questinCategoryId;
this.backgroundColors = backgroundColors;
}
public String getQuestion() {
return question;
}
public int getCorrectAnswer() {
return correctAnswer;
}
public ArrayList<String> getAnswers() {
return answers;
}
public String getQuestingCategoryId() {
return questinCategoryId;
}
public void setBackgroundColors(ArrayList<String> backgroundColors) {
this.backgroundColors = backgroundColors;
}
public ArrayList<String> getBackgroundColors() {
return backgroundColors;
}
#Override
public int describeContents() {
return 0;
}
#Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(question);
dest.writeList(answers);
dest.writeInt(correctAnswer);
dest.writeString(questinCategoryId);
dest.writeList(backgroundColors);
}
protected QuizModel (Parcel in) {
question = in.readString();
in.readList(answers, QuizModel.class.getClassLoader());
correctAnswer = in.readInt();
questinCategoryId = in.readString();
in.readList(backgroundColors, QuizModel.class.getClassLoader());
}
public static Creator<QuizModel> getCREATOR() {
return CREATOR;
}
public static final Creator<QuizModel> CREATOR = new Creator<QuizModel>() {
#Override
public QuizModel createFromParcel(Parcel source) {
return new QuizModel(source);
}
#Override
public QuizModel[] newArray(int size) {
return new QuizModel[size];
}
};
}
and JSON database
{
"question": "Тривале перебування в умовах спеки викликало у людини спрагу. Сигналiзацiя вiд яких рецепторiв, перш за все, зумовила її розвиток? ",
"answers": [
" Натрiєвi рецептори гiпоталамусу",
" Осморецептори печiнки",
" Глюкорецептори гiпоталамусу",
" Барорецептори дуги аорти",
" Осморецептори гiпоталамусу"
],
"correct_answer":4,
"question_category":"1"
},
Source code
https://drive.google.com/open?id=1zJ-dap6zvThs4lnj8ujwG0qTBjkT_WbD
Thank you!!!
You can place Collections.shuffle (list) directly in the constructor something like that:
public QuizModel (String question, ArrayList<String> answers, int correctAnswer, String questinCategoryId, ArrayList<String> backgroundColors) {
this.question = question;
this.correctAnswer = correctAnswer;
this.answers = answers;
Collections.shuffle(this.answers);
this.questinCategoryId = questinCategoryId;
this.backgroundColors = backgroundColors;
}
Or else you can define a separate method for this purpose:
public void shuffleAnswers() {
Collections.shuffle(this.answers);
}
And call it from any place in your code where you've instantiated QuizModel:
quizModel.shuffleAnswers();
public class QuizModel implements Parcelable {
String question;
ArrayList<String> answers;
int correctAnswer;
String questinCategoryId;
ArrayList<String> backgroundColors;
String trueAnswer;
public QuizModel (String question, ArrayList<String> answers, int correctAnswer, String questinCategoryId, ArrayList<String> backgroundColors) {
this.question = question;
this.correctAnswer = correctAnswer;
this.answers = answers;
shuffleAnswers();
this.questinCategoryId = questinCategoryId;
this.backgroundColors = backgroundColors;
this.trueAnswer = answers.get(correctAnswer);
}
private void shuffleAnswers() {
Collections.shuffle(answers);
correctAnswer = answers.indexOf(trueAnswer);
}
public boolean isCorrect(String answer) {
return trueAnswer.equals(answer);
}

SearchView Filter, get correct position in listview

How to get the correct item when the filtered result display in the ListView and when the filtered result is selected it will display the correct output in another fragment, so far this is my current codes.
Current Problem Output:
My codes so far:
YourGroup.java
package com.findforme.www.myapplication;
import android.content.Context;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Filter;
import android.widget.ListView;
import android.widget.SearchView;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
public class YourGroup extends Fragment implements SearchView.OnQueryTextListener,SearchView.OnCloseListener{
private String TAG = YourGroup.class.getSimpleName();
private ListView gridView;
private SearchView mSearchView;
ListAdapterShowGroups adapter;
ArrayList<your_groups> your_groupList;
public static YourGroup newInstance() {
YourGroup fragment = new YourGroup();
return fragment;
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
public void findViews(View view) {
your_groupList = new ArrayList<>();
mSearchView = view.findViewById(R.id.floating_search_view);
mSearchView.setOnQueryTextListener(this);
mSearchView.setOnCloseListener(this);
gridView = view.findViewById(R.id.lv_showGroup);
gridView.setTextFilterEnabled(false);
new GetGroups().execute();
}
#Override
public boolean onClose() {
final FilterHelper filterHelper = new FilterHelper(your_groupList,adapter,getActivity());
adapter = new ListAdapterShowGroups(filterHelper.currentList,getActivity());
gridView.setAdapter(adapter);
return false;
}
#Override
public boolean onQueryTextSubmit(String s) {
adapter.getFilter().filter(s);
return false;
}
#Override
public boolean onQueryTextChange(String query) {
adapter.getFilter().filter(query);
return false;
}
public static class FilterHelper extends Filter{
ArrayList<your_groups> currentList;
ListAdapterShowGroups adapter;
Context c;
FilterHelper(ArrayList<your_groups> currentList, ListAdapterShowGroups adapter, Context c){
this.currentList = currentList;
this.adapter = adapter;
this.c = c;
}
#Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults filterResults = new FilterResults();
if(constraint != null && constraint.length()>0){
constraint = constraint.toString().toLowerCase();
ArrayList<your_groups> foundFilters = new ArrayList<>();
your_groups your_group = null;
for (int i=0;i<currentList.size();i++){
your_group = currentList.get(i);
if(your_group.GroupName.toLowerCase().contains(constraint)){
foundFilters.add(your_group);
}
}
filterResults.count=foundFilters.size();
filterResults.values=foundFilters;
} else {
filterResults.count =currentList.size();
filterResults.values=currentList;
}
return filterResults;
}
#Override
protected void publishResults(CharSequence charSequence, FilterResults filterResults) {
if(filterResults.count == 0){
adapter.invalidate();
} else {
adapter.setYourGroups((ArrayList<your_groups>)filterResults.values);
adapter.refresh();
}
}
}
private class GetGroups extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
//Toast.makeText(getActivity(), "Retrieving data", Toast.LENGTH_SHORT).show();
}
#Override
protected Void doInBackground(Void... voids) {
HttpHandler sh = new HttpHandler();
int id = MainActivity.user.getId();
String user_id = Integer.toString(id);
//String url = "https://findforme2018.000webhostapp.com/show_groups_joined.php?id="+user_id;
String url = "http://192.168.211.1/Capstone%202018/FindForMe/show_groups_joined.php?id="+user_id;
String jsonStr = sh.makeServiceCall(url);
Log.e(TAG, "Response from url: " + jsonStr);
if( jsonStr != null){
try{
JSONObject jsonObj = new JSONObject(jsonStr);
JSONArray groups = jsonObj.getJSONArray("group_join");
your_groups your_groups;
your_groupList = new ArrayList<>();
for (int i = 0; i < groups.length(); i++){
JSONObject c = groups.getJSONObject(i);
your_groups = new your_groups();
your_groups.setGroupName(c.getString("group_name"));
your_groups.setId(c.getInt("group_id"));
your_groupList.add(your_groups);
}
}catch (final JSONException e){
Log.e(TAG, "Error: " + e.getMessage());
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getActivity(),
"No groups join yet",
Toast.LENGTH_LONG).show();
}
});
}
}
else {
Log.e(TAG, "Couldn't get json from server.");
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getActivity(),
"Couldn't get json from server. Check LogCat for possible errors!",
Toast.LENGTH_LONG).show();
}
});
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
adapter = new ListAdapterShowGroups(your_groupList,getActivity());
gridView.setAdapter(adapter);
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
int id = your_groupList.get(i).id;
String group_id = Integer.toString(id);
String groupname = your_groupList.get(i).GroupName;
Bundle args = new Bundle();
args.putString("group_id", group_id);
args.putString("groupname", groupname);
SelectedGroup fragment = new SelectedGroup();
fragment.setArguments(args);
Toast.makeText(getActivity(),
groupname,
Toast.LENGTH_LONG).show();
FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.content_main
, fragment).addToBackStack(null).commit();
}
});
}
}
View myView;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
myView = inflater.inflate(R.layout.fragment_your_group, container, false);
findViews(myView);
return myView;
}
}
This is the adapter that display the data in listview and its filter
package com.findforme.www.myapplication;
import android.app.Activity;
import android.content.Context;
import android.database.Cursor;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.ImageView;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import java.util.ArrayList;
public class ListAdapterShowGroups extends BaseAdapter implements Filterable{
Context context;
private ArrayList<your_groups> valueList;
private YourGroup.FilterHelper filterHelper;
ListAdapterShowGroups(ArrayList<your_groups> listValue, Context context)
{
this.context = context;
this.valueList = listValue;
}
#Override
public int getCount()
{
return this.valueList.size();
}
#Override
public Object getItem(int position)
{
return this.valueList.get(position);
}
#Override
public long getItemId(int position)
{
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent)
{
ListAdapterShowGroups.ViewItem viewItem;
if(convertView == null)
{
viewItem = new ListAdapterShowGroups.ViewItem();
LayoutInflater layoutInflater = (LayoutInflater)this.context.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
convertView = layoutInflater.inflate(R.layout.customgroup_layout,null);
viewItem.image = convertView.findViewById(R.id.groupImage);
viewItem.groupname = convertView.findViewById(R.id.tv_groupName);
convertView.setTag(viewItem);
}
else
{
viewItem = (ListAdapterShowGroups.ViewItem)convertView.getTag();
}
viewItem.groupname.setText(valueList.get(position).getGroupName());
String img = valueList.get(position).getGroupName();
//Glide.with(this.context).load("https://findforme2018.000webhostapp.com/Group_Image/"+img+".jpg").asBitmap().into(viewItem.image);
Glide.with(this.context).load("http://192.168.211.1/Capstone%202018/FindForMe/Group_Image/"+img+".jpg").asBitmap().into(viewItem.image);
return convertView;
}
public void setYourGroups(ArrayList<your_groups> filteredYourGroups){
this.valueList = filteredYourGroups;
}
#Override
public Filter getFilter() {
if(filterHelper == null){
filterHelper = new YourGroup.FilterHelper(valueList,this,context);
}
return filterHelper;
}
public void refresh(){
notifyDataSetChanged();
}
public void invalidate(){
notifyDataSetInvalidated();
}
class ViewItem {
Integer id;
TextView groupname;
ImageView image;
}
}
your_groups.java
package com.findforme.www.myapplication;
public class your_groups {
public String GroupName;
public Integer id;
public int getId(){
return id;
}
public void setId(int id) {
this.id = id;
}
public String getGroupName(){
return GroupName;
}
public void setGroupName(String GroupName){
this.GroupName = GroupName;
}
}
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// TODO Auto-generated method stub
text_view.setText(adapter.getItem(position - 1) + "");
}
});
Refer this code and change according your code..
public class IndexItemAdapter extends RecyclerView.Adapter<IndexItemAdapter.ItemViewHolder> implements Filterable {
private List<UserData> userVoList = new ArrayList<>();
private List<UserData> filterUserVoList = new ArrayList<>();
private Context context;
private String userId;
onItemClickListener onItemClickListener;
public void setOnItemClickListener(IndexItemAdapter.onItemClickListener onItemClickListener) {
this.onItemClickListener = onItemClickListener;
}
public IndexItemAdapter(Context context, List<UserData> userVoList, String userId) {
this.userVoList = userVoList;
this.context = context;
this.userId = userId;
this.filterUserVoList = userVoList;
}
#Override
public Filter getFilter() {
return new Filter() {
#Override
protected FilterResults performFiltering(CharSequence charSequence) {
String charString = charSequence.toString();
if (charString.isEmpty()) {
filterUserVoList = userVoList;
} else {
ArrayList<UserData> filteredList = new ArrayList<>();
for (UserData userData : userVoList) {
if (userData.getSubject().toLowerCase().contains(charString) || userData.getName().toLowerCase().contains(charString) || userData.getMessages().toLowerCase().contains(charString)) {
filteredList.add(userData);
}
}
filterUserVoList = filteredList;
}
FilterResults filterResults = new FilterResults();
filterResults.values = filterUserVoList;
return filterResults;
}
#Override
protected void publishResults(CharSequence charSequence, FilterResults filterResults) {
filterUserVoList = (ArrayList<UserData>) filterResults.values;
notifyDataSetChanged();
}
};
}
public interface onItemClickListener {
void onItemClick(UserData userData);
}
#NonNull
#Override
public ItemViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.index_row_layout, parent, false);
return new ItemViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull ItemViewHolder holder, int position) {
final UserData userData = filterUserVoList.get(position);
holder.tvName.setText(CommonUtils.checkForNullValue(userData.getSubject()));
holder.tvContent.setText(CommonUtils.checkForNullValue(userData.getMessages()));
if (userData.getUserVo() != null) {
holder.tvEmail.setText(userData.getUserVo().getEmail());
Glide.with(context).load(CommonUtils.checkForNullValue(userData.getUserVo().getPhoto())).apply(RequestOptions.circleCropTransform())
.apply(RequestOptions.diskCacheStrategyOf(DiskCacheStrategy.ALL))
.apply(RequestOptions.placeholderOf(R.drawable.big_user))
.into(holder.ivUserImage);
if (userId.equals(userData.getReceiverId())) {
holder.ivRecivedIcon.setImageResource(R.drawable.forward);
} else {
holder.ivRecivedIcon.setImageResource(R.drawable.reply);
}
}
}
private void changeTextColor(TextView textView, int color) {
textView.setTextColor(color);
}
#Override
public int getItemCount() {
return filterUserVoList.size();
}
public class ItemViewHolder extends RecyclerView.ViewHolder {
#BindView(R.id.irlIvUserImage)
ImageView ivUserImage;
#BindView(R.id.irlTvName)
TextView tvName;
#BindView(R.id.irlTvEmail)
TextView tvEmail;
#BindView(R.id.irlTvDes)
TextView tvContent;
#BindView(R.id.irlTvTime)
TextView tvTime;
#BindView(R.id.irlIvGetImage)
ImageView ivRecivedIcon;
public ItemViewHolder(View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
}
}
}
and search view in.. make sure your adapter not null
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
indexItemAdapter.getFilter().filter(newText.toLowerCase());
indexItemAdapter.notifyDataSetChanged();
return true;
}
});

Why is my ListView not showing anything?

// I have a Custom ListView in android and have set a adapter . My problem is //that the list view does not show anything, regardless of the adapter, note I'm //retrieving information from a Backendless services . please help
// adapter Code
package za.ac.cut.afinal;
import android.content.Context;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
/**
* Created by User on 2017/09/12.
*/
public class StudentAdapter extends ArrayAdapter<Student_Class> {
private final Context context;
private final List<Student_Class> values;
TextView tvName, tvSurname,tvGender,tvRace;
public StudentAdapter(Context context, List<Student_Class> list)
{
super(context,R.layout.custom_student_row_layout);
this.context = context;
this.values = list;
}
#Override
public long getItemId(int position) {
return super.getItemId(position);
}
#Nullable
#Override
public Student_Class getItem(int position) {
return values.get(position);
}
#Override
public int getCount() {
return values == null ? 0 : values.size();
}
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
View rowView = convertView;
LayoutInflater inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
rowView = inflater.inflate(R.layout.custom_student_row_layout,parent,false);
tvName = (TextView) rowView.findViewById(R.id.customSNmae);
tvSurname = (TextView) rowView.findViewById(R.id.tv_customSSurname);
tvGender = (TextView) rowView.findViewById(R.id.customSGender);
tvRace = (TextView) rowView.findViewById(R.id.customSRace);
Toast.makeText(context, "help" + values.get(position).getL_fname(), Toast.LENGTH_SHORT).show();
Toast.makeText(context, "help2" + values.get(position).getL_lname(), Toast.LENGTH_SHORT).show();
Toast.makeText(context, "help3" + values.get(position).getL_gender(), Toast.LENGTH_SHORT).show();
Toast.makeText(context, "help4" + values.get(position).getL_race(), Toast.LENGTH_SHORT).show();
tvName.setText(values.get(position).getL_fname());
tvSurname.setText(values.get(position).getL_lname());
tvGender.setText(values.get(position).getL_gender());
tvRace.setText(values.get(position).getL_race());
return rowView ;
}
}
// class Listview
package za.ac.cut.afinal;
import android.content.Context;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Adapter;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.Toast;
import com.backendless.Backendless;
import com.backendless.async.callback.AsyncCallback;
import com.backendless.exceptions.BackendlessFault;
import com.backendless.persistence.BackendlessDataQuery;
import com.backendless.persistence.DataQueryBuilder;
import com.backendless.persistence.QueryOptions;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import weborb.client.ant.wdm.View;
public class Student_List extends AppCompatActivity {
ListView lv;
List<Student_Class> StudentsList;
Student_Class student ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_student_list);
lv = (ListView)findViewById(R.id.lvStudentDetails1);
retrieveStudent();
}
#Override
protected void onResume() {
super.onResume();
retrieveStudent();
}
private void retrieveStudent()
{
// progressBar.setVisibility(android.view.View.VISIBLE);
if(StudentsList != null)
{
StudentsList.clear();
}
String whereClause = "u_Name = '12'";
DataQueryBuilder queryBuilder = DataQueryBuilder.create();
queryBuilder.setWhereClause(whereClause);
queryBuilder.setPageSize(100);
queryBuilder.setSortBy("l_fname");
Backendless.Persistence.of(Student_Class.class).find(queryBuilder, new AsyncCallback<List<Student_Class>>() {
#Override
public void handleResponse(List<Student_Class> response) {
for (int x = 0; x < response.size(); x++) {
student = new Student_Class(response.get(x).getL_IDNo(), response.get(x).getL_fname(), response.get(x).getL_lname(),
response.get(x).getL_className(), response.get(x).getL_gender(),
response.get(x).getL_race(), response.get(x).getL_DOB(),
response.get(x).getL_classLang(), response.get(x).getL_fullOrhalfday(),
response.get(x).getL_DOE(), response.get(x).getL_address(),
response.get(x).getL_mGardian(), response.get(x).getL_fGardian(),
response.get(x).getL_mGardianEmail(), response.get(x).getL_fGardianEmail(),
response.get(x).getL_mGardianCell(), response.get(x).getL_fGardianCell(),
response.get(x).getL_doc(),
response.get(x).getL_doctCell(), response.get(x).getL_medicalAid(),
response.get(x).getL_medicalAidPlan(), response.get(x).getL_medicalAidPlanNo(),
response.get(x).getL_allergies(), response.get(x).getL_tuckshopBalance()
, response.get(x).getCreated(), response.get(x).getUpdated(),
response.get(x).getObjectID());
}
StudentsList.add(student);
if (StudentsList != null) {
StudentAdapter adapter = new StudentAdapter(Student_List.this,StudentsList);
lv.setAdapter(adapter);
Helper_Class.ShowToast(Student_List.this,"WTF");
}else {
// tv_emptyList.setVisibility(View.VISIBLE);
Helper_Class.ShowToast(Student_List.this,"No Learners enrolled for this class");
}
}
#Override
public void handleFault(BackendlessFault fault) {
}
});
}
}
// Student Class
package za.ac.cut.afinal;
import java.util.Date;
/**
* Created by User on 2017/09/10.
*/
public class Student_Class {
private Date created;
private Date updated;
private String objectID;
private String l_IDNo;
private String l_fname;
private String l_lname;
private String l_className;
private String l_gender;
private String l_race;
private String l_DOB;
private String l_classLang;
private String l_fullOrhalfday;
private String l_DOE;
private String l_address;
private String l_mGardian;
private String l_fGardian;
private String l_mGardianEmail;
private String l_fGardianEmail;
private String l_mGardianCell;
private String l_fGardianCell;
private String l_doc;
private String l_doctCell;
private String l_medicalAid;
private String l_medicalAidPlan;
private String l_medicalAidPlanNo;
private String l_allergies;
private String l_tuckshopBalance;
public Student_Class(String l_fname, String l_lname, String l_gender, String l_race) {
this.l_fname = l_fname;
this.l_lname = l_lname;
this.l_gender = l_gender;
this.l_race = l_race;
}
public Student_Class() {
l_IDNo = null;
l_fname = null;
l_lname = null;
l_className = null;
l_gender = null;
l_race = null;
l_DOB = null;
l_classLang = null;
l_fullOrhalfday = null;
l_DOE = null;
l_address = null;
l_mGardian = null;
l_fGardian = null;
l_mGardianEmail = null;
l_fGardianEmail = null;
l_mGardianCell = null;
l_fGardianCell = null;
l_doc = null;
l_doctCell = null;
l_medicalAid = null;
l_medicalAidPlan = null;
l_medicalAidPlanNo = null;
l_allergies = null;
l_tuckshopBalance = null;
created = null;
updated = null;
objectID = null;
}
public Student_Class(String l_IDNo, String l_fname, String l_lname, String l_className, String l_gender, String l_race, String l_DOB, String l_classLang, String l_fullOrhalfday, String l_DOE, String l_address, String l_mGardian, String l_fGardian, String l_mGardianEmail, String l_fGardianEmail, String l_mGardianCell, String l_fGardianCell, String l_doc, String l_doctCell, String l_medicalAid, String l_medicalAidPlan, String l_medicalAidPlanNo, String l_allergies, String l_tuckshopBalance,Date created, Date updated, String objectID) {
this.created = created;
this.updated = updated;
this.objectID = objectID;
this.l_IDNo = l_IDNo;
this.l_fname = l_fname;
this.l_lname = l_lname;
this.l_className = l_className;
this.l_gender = l_gender;
this.l_race = l_race;
this.l_DOB = l_DOB;
this.l_classLang = l_classLang;
this.l_fullOrhalfday = l_fullOrhalfday;
this.l_DOE = l_DOE;
this.l_address = l_address;
this.l_mGardian = l_mGardian;
this.l_fGardian = l_fGardian;
this.l_mGardianEmail = l_mGardianEmail;
this.l_fGardianEmail = l_fGardianEmail;
this.l_mGardianCell = l_mGardianCell;
this.l_fGardianCell = l_fGardianCell;
this.l_doc = l_doc;
this.l_doctCell = l_doctCell;
this.l_medicalAid = l_medicalAid;
this.l_medicalAidPlan = l_medicalAidPlan;
this.l_medicalAidPlanNo = l_medicalAidPlanNo;
this.l_allergies = l_allergies;
this.l_tuckshopBalance = l_tuckshopBalance;
}
public Date getCreated() {
return created;
}
public void setCreated(Date created) {
this.created = created;
}
public Date getUpdated() {
return updated;
}
public void setUpdated(Date updated) {
this.updated = updated;
}
public String getObjectID() {
return objectID;
}
public void setObjectID(String objectID) {
this.objectID = objectID;
}
public String getL_IDNo() {
return l_IDNo;
}
public void setL_IDNo(String l_IDNo) {
this.l_IDNo = l_IDNo;
}
public String getL_fname() {
return l_fname;
}
public void setL_fname(String l_fname) {
this.l_fname = l_fname;
}
public String getL_lname() {
return l_lname;
}
public void setL_lname(String l_lname) {
this.l_lname = l_lname;
}
public String getL_className() {
return l_className;
}
public void setL_className(String l_className) {
this.l_className = l_className;
}
public String getL_gender() {
return l_gender;
}
public void setL_gender(String l_gender) {
this.l_gender = l_gender;
}
public String getL_race() {
return l_race;
}
public void setL_race(String l_race) {
this.l_race = l_race;
}
public String getL_DOB() {
return l_DOB;
}
public void setL_DOB(String l_DOB) {
this.l_DOB = l_DOB;
}
public String getL_classLang() {
return l_classLang;
}
public void setL_classLang(String l_classLang) {
this.l_classLang = l_classLang;
}
public String getL_fullOrhalfday() {
return l_fullOrhalfday;
}
public void setL_fullOrhalfday(String l_fullOrhalfday) {
this.l_fullOrhalfday = l_fullOrhalfday;
}
public String getL_DOE() {
return l_DOE;
}
public void setL_DOE(String l_DOE) {
this.l_DOE = l_DOE;
}
public String getL_address() {
return l_address;
}
public void setL_address(String l_address) {
this.l_address = l_address;
}
public String getL_mGardian() {
return l_mGardian;
}
public void setL_mGardian(String l_mGardian) {
this.l_mGardian = l_mGardian;
}
public String getL_fGardian() {
return l_fGardian;
}
public void setL_fGardian(String l_fGardian) {
this.l_fGardian = l_fGardian;
}
public String getL_mGardianEmail() {
return l_mGardianEmail;
}
public void setL_mGardianEmail(String l_mGardianEmail) {
this.l_mGardianEmail = l_mGardianEmail;
}
public String getL_fGardianEmail() {
return l_fGardianEmail;
}
public void setL_fGardianEmail(String l_fGardianEmail) {
this.l_fGardianEmail = l_fGardianEmail;
}
public String getL_mGardianCell() {
return l_mGardianCell;
}
public void setL_mGardianCell(String l_mGardianCell) {
this.l_mGardianCell = l_mGardianCell;
}
public String getL_fGardianCell() {
return l_fGardianCell;
}
public void setL_fGardianCell(String l_fGardianCell) {
this.l_fGardianCell = l_fGardianCell;
}
public String getL_doc() {
return l_doc;
}
public void setL_doc(String l_doc) {
this.l_doc = l_doc;
}
public String getL_doctCell() {
return l_doctCell;
}
public void setL_doctCell(String l_doctCell) {
this.l_doctCell = l_doctCell;
}
public String getL_medicalAid() {
return l_medicalAid;
}
public void setL_medicalAid(String l_medicalAid) {
this.l_medicalAid = l_medicalAid;
}
public String getL_medicalAidPlan() {
return l_medicalAidPlan;
}
public void setL_medicalAidPlan(String l_medicalAidPlan) {
this.l_medicalAidPlan = l_medicalAidPlan;
}
public String getL_medicalAidPlanNo() {
return l_medicalAidPlanNo;
}
public void setL_medicalAidPlanNo(String l_medicalAidPlanNo) {
this.l_medicalAidPlanNo = l_medicalAidPlanNo;
}
public String getL_allergies() {
return l_allergies;
}
public void setL_allergies(String l_allergies) {
this.l_allergies = l_allergies;
}
public String getL_tuckshopBalance() {
return l_tuckshopBalance;
}
public void setL_tuckshopBalance(String l_tuckshopBalance) {
this.l_tuckshopBalance = l_tuckshopBalance;
}
}
set adapter.notifyDataSetChanged(); after retrieving data from backend.
Info data variable must be same reference adress, I mean do not malloc again etc. after retrieving data.
there are some errors:
1) StudentsList is never istanciated (always null)
2) StudentsList.add(student); cannot work because SutendList is null
3) StudentsList.add(student); should be called inside for loop, why are you calling it outside?
Everything was working fine, i mistakenly typed in the wrong string here "String whereClause = "u_Name = '12'";"
36 hours when the problem was a string!

android xml: Error inflating class fragment

I am having problem with fragments.I am developing an app like 360 security and i am having problem implementing fragments ,getting "Binary XML file line #1: Error inflating class fragment".
Here is my xml file.I have tried every solution please help me.
Thanks in advance.
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/item_list"
android:name="sabby.completesecurity.MainListFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".ItemListActivity"
tools:layout="#android:layout/list_content" />
This is my activity file:
package sabby.completesecurity;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.FrameLayout;
import android.widget.ImageView;
import sabby.completesecurity.R;
public class MainActivityCache extends FragmentActivity implements sabby.completesecurity.MainCallbacks {
private boolean mIsDualPane;
private boolean mIsArtShowed = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_cache);
mIsDualPane = findViewById(R.id.item_detail_container) != null;
//Show an art when no fragment is showed, we make sure no detail fragment is present.
if (mIsDualPane && getFragmentManager().findFragmentByTag(sabby.completesecurity.DetailFragment.FRAGMENT_TAG) == null) {
ImageView imageView = new ImageView(this);
imageView.setImageResource(R.mipmap.ic_launcher);
imageView.setScaleType(ImageView.ScaleType.FIT_CENTER);
((FrameLayout) findViewById(R.id.item_detail_container)).addView(imageView);
mIsArtShowed = true;
}
}
#Override
public void onItemSelected(String packageName) {
if (mIsDualPane) {
//Hide art when a fragment is showed.
if (mIsArtShowed) {
((FrameLayout) findViewById(R.id.item_detail_container)).removeAllViews();
mIsArtShowed = false;
}
getFragmentManager()
.beginTransaction()
.replace(R.id.item_detail_container, DetailFragment.getInstance(packageName), DetailFragment.FRAGMENT_TAG)
.commit();
} else {
Intent intent = new Intent(this, DetailActivity.class);
intent.putExtra(DetailFragment.EXTRA_PACKAGE_NAME, packageName);
startActivity(intent);
}
}
#Override
protected void onStart() {
super.onStart();
registerReceiver(receiver, getIntentFilter());
}
#Override
protected void onStop() {
super.onStop();
unregisterReceiver(receiver);
}
private void showAboutDialog() {
new AlertDialog.Builder(this)
.setTitle("About")
.setView(getLayoutInflater().inflate(R.layout.about_dialog_message, null))
.setNegativeButton(android.R.string.ok, null)
.show();
}
/**
* Used to update the list if a package is added or removed.
*/
private IntentFilter getIntentFilter() {
IntentFilter filter = new IntentFilter();
filter.addDataScheme("package");
filter.addAction(Intent.ACTION_PACKAGE_CHANGED);
filter.addAction(Intent.ACTION_PACKAGE_REPLACED);
filter.addAction(Intent.ACTION_PACKAGE_FULLY_REMOVED);
filter.addAction(Intent.ACTION_PACKAGE_ADDED);
return filter;
}
enter code here
BroadcastReceiver receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
MainListFragment mainListFragment = (MainListFragment) getFragmentManager().findFragmentById(R.id.item_list);
if (mainListFragment != null)
mainListFragment.loadList();
}
};
}
MainListFragment.java
package sabby.completesecurity;
import android.app.ActionBar;
import android.app.Activity;
import android.app.ListFragment;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.IPackageStatsObserver;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageStats;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.RemoteException;
import android.text.format.Formatter;
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.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.SectionIndexer;
import android.widget.Spinner;
import android.widget.TextView;
import sabby.completesecurity.utils.Utils;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;
public class MainListFragment extends ListFragment implements AdapterView.OnItemClickListener, AdapterView.OnItemSelectedListener {
private static final int SORT_NAME = 0;
private static final int SORT_PKG = 1;
private static final int SORT_DOMAIN = 2;
private static final int SORT_INSTALLATION = 3;
private static final int SORT_SIZE = 4;
private static final String INSTANCE_STATE_SORT_BY = "sort_by";
private Adapter mAdapter;
private List<Item> mItemList = new ArrayList<Item>();
private int mOnSizeFinishedItemCount;
private PackageManager mPackageManager;
private ProgressDialog mProgressDialog;
private LayoutInflater mLayoutInflater;
private MainCallbacks mCallbacks;
private Context mContext;
private Async mAsyncLoader;
private Spinner mSpinner;
private boolean mSpinnerListenerAuthorized;
private SimpleDateFormat mSimpleDateFormat;
private int mSortBy = 0;
class Item {
ApplicationInfo applicationInfo;
String label;
Long date;
Long size = -1L;
}
private int mColorGrey1;
private int mColorGrey2;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
mProgressDialog = new ProgressDialog(mContext);
mProgressDialog.setTitle(R.string.loading_apps);
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
mProgressDialog.setCancelable(false);
//Used to prevent message not showing later
mProgressDialog.setMessage("");
mPackageManager = mContext.getPackageManager();
mSimpleDateFormat = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss");
mColorGrey1 = getResources().getColor(R.color.grey_1);
mColorGrey2 = getResources().getColor(R.color.grey_2);
ActionBar actionBar = getActivity().getActionBar();
actionBar.setDisplayShowCustomEnabled(true);
mSpinner = new Spinner(actionBar.getThemedContext());
SpinnerAdapter spinnerAdapter = new SpinnerAdapter(actionBar.getThemedContext(),
R.array.sort_spinner_items, android.R.layout.simple_list_item_1);
mSpinner.setAdapter(spinnerAdapter);
mSpinnerListenerAuthorized = false;
mSpinner.setOnItemSelectedListener(this);
ActionBar.LayoutParams layoutParams = new ActionBar.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT);
actionBar.setCustomView(mSpinner, layoutParams);
if (savedInstanceState != null)
setSortBy(savedInstanceState.getInt(INSTANCE_STATE_SORT_BY, -1), false);
}
#Override
public void onStart() {
super.onStart();
mSpinner.setSelection(mSortBy);
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt(INSTANCE_STATE_SORT_BY, mSortBy);
}
private void onTaskEnded(List<Item> list) {
RetainedFragment retainedFragment = (RetainedFragment) getFragmentManager().findFragmentByTag(RetainedFragment.FRAGMENT_TAG);
retainedFragment.setList(list);
mItemList = list;
mAdapter.notifyDataSetChanged();
if (getListView().getAdapter() == null)
setListAdapter(mAdapter);
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
getListView().setOnItemClickListener(this);
getListView().setFastScrollEnabled(true);
mAdapter = new Adapter();
RetainedFragment retainedFragment = (RetainedFragment) getFragmentManager()
.findFragmentByTag(RetainedFragment.FRAGMENT_TAG);
if (retainedFragment == null) {
retainedFragment = new RetainedFragment();
getFragmentManager()
.beginTransaction()
.add(retainedFragment, RetainedFragment.FRAGMENT_TAG)
.commit();
}
if (retainedFragment.getList() != null) {
onTaskEnded(retainedFragment.getList());
mOnSizeFinishedItemCount = mItemList.size();
//Notify spinner that size sort is available
SpinnerAdapter adapter = (SpinnerAdapter) mSpinner.getAdapter();
adapter.notifyDataSetChanged();
} else
loadList();
}
public void loadList() {
mAsyncLoader = new Async();
mAsyncLoader.execute();
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
mCallbacks = (MainCallbacks) activity;
mContext = activity;
mLayoutInflater = activity.getLayoutInflater();
}
#Override
public void onDetach() {
super.onDetach();
if (mAsyncLoader != null)
mAsyncLoader.cancel(true);
mCallbacks = null;
mContext = null;
mLayoutInflater = null;
}
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
if (mCallbacks != null)
mCallbacks.onItemSelected(mItemList.get(i).applicationInfo.packageName);
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.fragment_main_list, menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_refresh:
loadList();
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
if (mSpinnerListenerAuthorized)
setSortBy(i, true);
mSpinnerListenerAuthorized = true;
}
/**
* Sort main list if provided value is valid.
* #param sort Must be one of SORT_*
* #param checkViews Set if views have to be updated, eg. when restoring state, views aren't
* created yet, so value must be false
*/
public void setSortBy(int sort, boolean checkViews) {
if (sort >= SORT_NAME && sort <= SORT_SIZE) {
mSortBy = sort;
if (checkViews) {
checkFastScroll();
sortApplicationList(mItemList, mSortBy);
mAdapter.notifyDataSetChanged();
}
}
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
private void checkFastScroll() {
getListView().setFastScrollEnabled(mSortBy == SORT_NAME);
}
public void sortApplicationList(List<Item> list, final int sortBy) {
Collections.sort(list, new Comparator<Item>() {
#Override
public int compare(Item item1, Item item2) {
switch (sortBy) {
case SORT_NAME:
return item1.label.compareTo(item2.label);
case SORT_PKG:
return item1.applicationInfo.packageName.compareTo(item2.applicationInfo.packageName);
case SORT_DOMAIN:
boolean isSystem1 = (item1.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
boolean isSystem2 = (item2.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
return Utils.compareBooleans(isSystem1, isSystem2);
case SORT_INSTALLATION:
//Sort in decreasing order
return -item1.date.compareTo(item2.date);
case SORT_SIZE:
return -item1.size.compareTo(item2.size);
default:
return 0;
}
}
});
}
/**
* This method is called by each item when it has finished retrieving its size
* When all items have finished, we set size sort available in spinner, and invalidate
* main list to display sizes in UI.
*/
private void onItemFinishedSizeProcess() {
mOnSizeFinishedItemCount ++;
if (mOnSizeFinishedItemCount == mItemList.size()) {
getActivity().runOnUiThread(new Runnable() {
#Override
public void run() {
SpinnerAdapter adapter = (SpinnerAdapter) mSpinner.getAdapter();
adapter.notifyDataSetChanged();
mAdapter.notifyDataSetChanged();
}
});
}
}
class Adapter extends BaseAdapter implements SectionIndexer {
class ViewHolder {
ImageView icon;
TextView label;
TextView packageName;
TextView version;
TextView isSystemApp;
TextView date;
TextView size;
IconAsyncTask iconLoader;
}
String sections = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
#Override
public int getCount() {
return mItemList.size();
}
#Override
public Object getItem(int i) {
return mItemList.get(i);
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
ViewHolder holder;
if (view == null) {
view = mLayoutInflater.inflate(R.layout.main_list_item, null);
holder = new ViewHolder();
holder.icon = (ImageView) view.findViewById(R.id.icon);
holder.label = (TextView) view.findViewById(R.id.label);
holder.packageName = (TextView) view.findViewById(R.id.packageName);
holder.version = (TextView) view.findViewById(R.id.version);
holder.isSystemApp = (TextView) view.findViewById(R.id.isSystem);
holder.date = (TextView) view.findViewById(R.id.date);
holder.size = (TextView) view.findViewById(R.id.size);
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
holder.iconLoader.cancel(true);
}
view.setBackgroundColor(i % 2 == 0 ? mColorGrey2 : mColorGrey1);
Item item = mItemList.get(i);
ApplicationInfo info = item.applicationInfo;
try {
PackageInfo packageInfo = mPackageManager.getPackageInfo(info.packageName, 0);
holder.version.setText(packageInfo.versionName);
Date date = new Date(packageInfo.firstInstallTime);
holder.date.setText(mSimpleDateFormat.format(date));
} catch (PackageManager.NameNotFoundException e) {
//Do nothing
}
holder.iconLoader = new IconAsyncTask(holder.icon, info);
holder.iconLoader.execute();
holder.label.setText(info.loadLabel(mPackageManager));
holder.packageName.setText(info.packageName);
boolean isSystemApp = (info.flags & ApplicationInfo.FLAG_SYSTEM) != 0;
holder.isSystemApp.setText(isSystemApp ? getString(R.string.system) : getString(R.string.user));
if (item.size != -1L)
holder.size.setText(Formatter.formatFileSize(getActivity(), item.size));
return view;
}
#Override
public int getPositionForSection(int section) {
for (int i = 0; i < this.getCount(); i++) {
String item = mItemList.get(i).label;
if (item.charAt(0) == sections.charAt(section))
return i;
}
return 0;
}
#Override
public int getSectionForPosition(int i) {
return 0;
}
#Override
public Object[] getSections() {
String[] sectionsArr = new String[sections.length()];
for (int i = 0; i < sections.length(); i++)
sectionsArr[i] = "" + sections.charAt(i);
return sectionsArr;
}
class IconAsyncTask extends AsyncTask<Void, Integer, Drawable> {
ImageView imageView;
ApplicationInfo info;
IconAsyncTask(ImageView imageView, ApplicationInfo info) {
this.imageView = imageView;
this.info = info;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
imageView.setVisibility(View.INVISIBLE);
}
#Override
protected Drawable doInBackground(Void... voids) {
if (!isCancelled())
return info.loadIcon(mPackageManager);
return null;
}
#Override
protected void onPostExecute(Drawable drawable) {
super.onPostExecute(drawable);
imageView.setImageDrawable(drawable);
imageView.setVisibility(View.VISIBLE);
}
}
}
class SpinnerAdapter extends BaseAdapter {
private Context mContext;
private int mLayoutResId;
private String[] mItems;
public SpinnerAdapter(Context themedContext, int arrayResId, int layoutResId) {
mContext = themedContext;
mItems = themedContext.getResources().getStringArray(arrayResId);
mLayoutResId = layoutResId;
}
#Override
public int getCount() {
return mItems.length;
}
#Override
public Object getItem(int i) {
return null;
}
#Override
public long getItemId(int i) {
return 0;
}
//It make no sense to implement recycled view system because there is only 5 items in list
#Override
public View getView(int i, View view, ViewGroup viewGroup) {
view = View.inflate(mContext, mLayoutResId, null);
if (view instanceof TextView)
((TextView) view).setText(mItems[i]);
return view;
}
/**
* Set sort_by_size item disabled if all items haven't retrieved them size.
*/
#Override
public boolean isEnabled(int position) {
return position != SORT_SIZE || mItemList != null && mOnSizeFinishedItemCount == mItemList.size();
}
}
class Async extends AsyncTask<Void, Async.Progress, List<Item>> {
class Progress {
String label;
int totalSize;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
mProgressDialog.show();
}
#Override
protected List<Item> doInBackground(Void... voids) {
List<ApplicationInfo> applicationInfos = mPackageManager.getInstalledApplications(PackageManager.GET_META_DATA);
Progress progress = new Progress();
progress.totalSize = applicationInfos.size();
List<Item> itemList = new ArrayList<Item>(applicationInfos.size());
mOnSizeFinishedItemCount = 0;
for (ApplicationInfo applicationInfo : applicationInfos) {
if (isCancelled())
break;
Item item = new Item();
item.applicationInfo = applicationInfo;
String label = applicationInfo.loadLabel(mPackageManager).toString();
item.label = label;
try {
item.date = mPackageManager.getPackageInfo(applicationInfo.packageName, 0).firstInstallTime;
} catch (PackageManager.NameNotFoundException e) {
item.date = 0L;
}
itemList.add(item);
getItemSize(item);
progress.label = label;
publishProgress(progress);
}
sortApplicationList(itemList, mSortBy);
return itemList;
}
private void getItemSize(final Item item) {
try {
Method getPackageSizeInfo = mPackageManager.getClass().getMethod(
"getPackageSizeInfo", String.class, IPackageStatsObserver.class);
getPackageSizeInfo.invoke(mPackageManager, item.applicationInfo.packageName, new IPackageStatsObserver.Stub() {
#Override
public void onGetStatsCompleted(final PackageStats pStats, boolean succeeded)
throws RemoteException {
if (succeeded)
item.size = pStats.codeSize + pStats.cacheSize + pStats.dataSize
+ pStats.externalCodeSize + pStats.externalCacheSize + pStats.externalDataSize
+ pStats.externalMediaSize + pStats.externalObbSize;
else
item.size = -1L;
onItemFinishedSizeProcess();
}
});
} catch (NoSuchMethodException e) {
e.printStackTrace();
onItemFinishedSizeProcess();
} catch (IllegalAccessException e) {
e.printStackTrace();
onItemFinishedSizeProcess();
} catch (InvocationTargetException e) {
e.printStackTrace();
onItemFinishedSizeProcess();
}
}
#Override
protected void onProgressUpdate(Progress... values) {
super.onProgressUpdate(values);
Progress progress = values[0];
mProgressDialog.setMessage(progress.label);
if (mProgressDialog.getMax() == 100)
mProgressDialog.setMax(progress.totalSize);
mProgressDialog.incrementProgressBy(1);
}
#Override
protected void onPostExecute(List<Item> list) {
super.onPostExecute(list);
mProgressDialog.hide();
onTaskEnded(list);
}
#Override
protected void onCancelled(List<Item> list) {
super.onCancelled(list);
mProgressDialog.hide();
}
}
}
In the xml that you have posted,replace the TAG <Fragment> with <LinearLayout> or <RelativeLayout> and inside this you simply show what you want to display in you UI
Make sure you extend Fragment class in you fragment activity
Could you post the code for your fragment? The problem could be with your import statements. You have 'import android.support.v4.app.FragmentActivity'. Do you have 'import android.support.v4.app.Fragment' in your fragment file?

android issues updating Listview due to filtering, with a custom base adapter

I'm facing issue by implementing a search mechanism on a ListView in Android.
I currently display a list of companies in a ListView
The ListView is linked to a custom BaseAdapter that ref a data model
The data model handle the data gathering thru HTTP requests.
I succeed partly filtering : the identified companies are identified in the listview, but the rest of the companies (the ones that not match the searching constraint are still there), even if I removed them
Here is the code :
package org.x.activites;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.x.R;
import org.x.activites.utils.Analytics;
import org.x.adapters.listview.AbstractDynamicModel;
import org.x.adapters.listview.AbstractExtendedDynamicViewAdapter;
import org.x.adapters.listview.ViewHolder;
import org.x.application.Application;
import org.x.http.HTTPRequest;
import org.x.list.adapters.PartnerViewHolder;
import org.x.model.Partner;
import android.app.AlertDialog;
import android.app.SearchManager;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.Settings;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Filter;
import android.widget.Filterable;
import android.widget.ListView;
import com.actionbarsherlock.app.SherlockActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.widget.SearchView;
public class GeoPartnerActivity extends SherlockActivity {
private ListView listView;
PartnersModel partnersModel;
PartnerListAdapter partnerAdpt;
private SearchManager searchManager;
private SearchView searchView;
public GeoPartnerActivity() {
}
#Override
protected void onDestroy() {
super.onDestroy();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_partner);
listView = (ListView) findViewById(R.id.partnerList);
partnersModel = new PartnersModel();
partnerAdpt = new PartnerListAdapter(partnersModel);
listView.setAdapter(partnerAdpt);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getSupportMenuInflater().inflate(R.menu.activity_partners, menu);
searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
searchView = (SearchView) menu.findItem(R.id.menu_search).getActionView();
if (null != searchView) {
searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
searchView.setIconifiedByDefault(false);
}
SearchView.OnQueryTextListener queryTextListener = new SearchView.OnQueryTextListener() {
public boolean onQueryTextChange(String newText) {
return false;
}
public boolean onQueryTextSubmit(String query) {
if (TextUtils.isEmpty(query)) {
listView.clearTextFilter();
}
else {
listView.setFilterText(query);
}
partnerAdpt.getFilter().filter(query);
return true;
}
};
searchView.setOnQueryTextListener(queryTextListener);
searchView.setQueryHint("Salut StackExchange");
return super.onCreateOptionsMenu(menu);
}
public class PartnersModel extends AbstractDynamicModel<Partner> {
public PartnersModel() {
}
private HTTPRequest createRequest() {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("currentIndex", getElements().size() + ""));
nameValuePairs.add(new BasicNameValuePair("partnersNumber", "5"));
return new HTTPRequest("http://xxxxxxxxxxxxxxxx/partners", nameValuePairs);
}
#Override
protected BackgroundTask createBackgroundTask() {
BackgroundTask backgroundTask = new BackgroundTask(GeoPartnerActivity.this, createRequest()) {
List<Partner> lastLoaded = new ArrayList<Partner>();
#Override
protected List<Partner> getLoadedElements() {
return lastLoaded;
}
#Override
protected void handleSuccess(Object object) {
lastLoaded.clear();
try {
JSONArray array = (JSONArray) object;
for (int i = 0; i < array.length(); i++) {
JSONObject jsonObject = (JSONObject) array.get(i);
Partner partner = new Partner(jsonObject);
lastLoaded.add(partner);
}
}
catch (JSONException e) {
e.printStackTrace();
}
}
};
return backgroundTask;
}
#Override
public List<Partner> getElements() {
return super.getElements();
}
#Override
protected Context getContext() {
return GeoPartnerActivity.this;
}
}
private class PartnerListAdapter extends AbstractExtendedDynamicViewAdapter<Partner> implements Filterable {
private PartnersModel partnerList, partnerFullList;
private PartnerFilter partnerFilter;
public PartnerListAdapter(PartnersModel model) {
super(GeoPartnerActivity.this, model);
partnerList = model;
partnerFullList = new PartnersModel();
}
#Override
public Filter getFilter() {
if (partnerFilter == null) {
partnerFilter = new PartnerFilter();
}
return partnerFilter;
}
public void notifyDataSetChanged() {
super.notifyDataSetChanged();
}
#Override
protected int getResourceID() {
return PartnerViewHolder.ResourceId;
}
#Override
protected ViewHolder createViewHolder(View convertView) {
return new PartnerViewHolder(convertView);
}
public class PartnerFilter extends Filter {
#Override
protected FilterResults performFiltering(CharSequence constraint) {
FilterResults results = new FilterResults();
List<Partner> partnerFilteredList = new ArrayList<Partner>();
for (Iterator<Partner> iterator = partnerList.iterator(); iterator.hasNext();) {
Partner partner = iterator.next();
partnerFullList.getElements().add(partner);
if (false == partner.getName().toUpperCase().contains(constraint.toString().toUpperCase())) {
partnerFilteredList.add(partner);
}
}
results.values = partnerFilteredList;
results.count = partnerFilteredList.size();
return results;
}
#SuppressWarnings("unchecked")
#Override
protected void publishResults(CharSequence constraint, FilterResults results) {
if (results.count == 0)
partnerAdpt.notifyDataSetInvalidated();
else {
for (Iterator<Partner> iterator = ((List<Partner>) results.values).iterator(); iterator.hasNext();) {
Partner p = (Partner) iterator.next();
if (partnerAdpt.partnerList.getElements().remove(p));
p.setName("del-> " + p.getName());
}
//listView.setAdapter(null);
//listView.setAdapter(new PartnerListAdapter(partnerList));
((PartnerListAdapter) listView.getAdapter()).notifyDataSetChanged();
listView.refreshDrawableState();
listView.invalidateViews();
}
}
}
}
}
Here is the menu layout
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<item
android:id="#+id/menu_search"
android:actionViewClass="com.actionbarsherlock.widget.SearchView"
android:icon="#drawable/toolbar_find"
android:showAsAction="always"
android:title="Search">
</item>
</menu>
And here is screenshot before filtering :
And after :
I have tagged the name of the items with a "del->", so all of them are identified, but not removed from the list !!!
Edit :
Here is the top adapter AbstractDynamicViewAdapter:
public abstract class AbstractDynamicViewAdapter extends BaseAdapter {
protected final Context _context;
protected final ArrayList<AdapterItem> _list;
private final LayoutInflater _inflater;
private final int _progressResourceId;
private final int _unavailableResourceId;
private final int _emptyResourceId;
protected boolean _isInitialization = false;
protected boolean _isRequestSubmited = false;
public AbstractDynamicViewAdapter(Context context, int progressResourceId, int unavailableResourceId,
int emptyResourceId) {
_context = context;
_inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
_list = new ArrayList<AdapterItem>();
_progressResourceId = progressResourceId;
_unavailableResourceId = unavailableResourceId;
_emptyResourceId = emptyResourceId;
}
protected abstract View onDataView(int position, AdapterItem item, View convertView, ViewGroup parent);
protected abstract void onDataLoad();
protected abstract boolean isMoreToLoad();
protected abstract void onSubmitDataRequest();
#Override
public int getCount() {
return _list.size();
}
#Override
public Object getItem(int position) {
Object result = null;
if (position < _list.size()) {
result = _list.get(position);
}
return result;
}
#Override
/* Override this method when implementing stable id */
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if (_list.size() > position) {
AdapterItem item = _list.get(position);
if (item.viewType == ViewType.Data) {
convertView = onDataView(position, item, convertView, parent);
}
else {
int resourceid = getResourceByViewType(item.viewType);
convertView = tryInflateView(convertView, resourceid, parent);
tryCreateViewHolder(convertView, item, resourceid);
if (!_isRequestSubmited && item.viewType == ViewType.Progress) {
submitDataRequest();
}
}
}
return convertView;
}
protected int getResourceByViewType(ViewType expectedType) {
int result = 0;
switch (expectedType) {
case Progress:
result = _progressResourceId;
break;
case Unavailable:
result = _unavailableResourceId;
break;
case Empty:
result = _emptyResourceId;
break;
default:
break;
}
return result;
}
protected void tryCreateViewHolder(View viewSource, AdapterItem item, int resourceId) {
ViewHolder viewItem = (ViewHolder) viewSource.getTag();
if (viewItem == null) {
viewItem = new ViewHolder(viewSource, resourceId);
}
}
protected View tryInflateView(View viewSource, int resourceId, ViewGroup parent) {
View result = null;
if (viewSource != null && viewSource.getTag() != null) {
ViewHolder viewItem = (ViewHolder) viewSource.getTag();
// try to re-use view if it has the same type
if (viewItem != null && viewItem.resourceId == resourceId) {
result = viewSource;
}
}
if (result == null) {
// create new view
result = _inflater.inflate(resourceId, parent, false);
}
return result;
}
protected void addItem(Object value, Object tag) {
AdapterItem item = new AdapterItem(value, tag);
_list.add(item);
}
protected void removeItem(Object item) {
_list.remove(item);
}
protected void addUnavailableItem() {
AdapterItem item = new AdapterItem(ViewType.Unavailable);
_list.add(item);
}
protected void submitDataRequest() {
showProgress();
onSubmitDataRequest();
_isRequestSubmited = true;
}
protected void setDataCompleted() {
_list.clear();
onDataLoad();
if (isMoreToLoad()) {
showProgress();
}
notifyDataSetChanged();
_isRequestSubmited = false;
}
private void removeAnyBut(ViewType type) {
if (type != ViewType.Progress) {
tryEndProgress();
}
if (type != ViewType.Empty) {
tryEndEmpty();
}
if (type != ViewType.Unavailable) {
tryEndUnavailable();
}
}
private void tryShowItem(ViewType type) {
removeAnyBut(type);
if (_list.size() == 0 || _list.get(_list.size() - 1).viewType != type) {
_list.add(new AdapterItem(type));
}
notifyDataSetChanged();
}
protected void showUnavailable() {
tryShowItem(ViewType.Unavailable);
}
protected void showProgress() {
tryShowItem(ViewType.Progress);
}
protected void showEmpty() {
tryShowItem(ViewType.Empty);
}
private void tryRemoveItem(ViewType type) {
if (_list.size() > 0 && _list.get(_list.size() - 1).viewType == type) {
_list.remove(_list.size() - 1);
}
}
protected void tryEndProgress() {
tryRemoveItem(ViewType.Progress);
}
protected void tryEndUnavailable() {
tryRemoveItem(ViewType.Unavailable);
}
protected void tryEndEmpty() {
tryRemoveItem(ViewType.Empty);
}
}
And the middle adapter AbstractExtendedDynamicViewAdapter :
public abstract class AbstractExtendedDynamicViewAdapter<T> extends AbstractDynamicViewAdapter {
private final AbstractDynamicModel<T> _model;
private boolean offlineModedataLoaded = false;
private Handler handler = new Handler() {
#Override
public void dispatchMessage(Message msg) {
setDataCompleted();
}
};
public AbstractExtendedDynamicViewAdapter(Context context, AbstractDynamicModel<T> model) {
super(context, R.layout.progress_item, R.layout.unavailable_item, R.layout.empty_item);
_model = model;
_model.setLoadCompleted(handler);
submitDataRequest();
}
#Override
public View onDataView(int position, AdapterItem item, View convertView, ViewGroup parent) {
convertView = tryInflateView(convertView, getResourceID(), parent);
ViewHolder viewHolder = (ViewHolder) convertView.getTag();
if (viewHolder == null) {
viewHolder = createViewHolder(convertView);
}
viewHolder.render(item);
return convertView;
}
public boolean removeElement(Object obj) {
//return _list.remove(obj);
return _model.getElements().remove(obj);
}
protected abstract int getResourceID();
protected abstract ViewHolder createViewHolder(View convertView);
#Override
protected boolean isMoreToLoad() {
if (Utils.isConnected(_context)) {
offlineModedataLoaded = true;
return true;
}
else
if (false == offlineModedataLoaded) {
offlineModedataLoaded = true;
return true;
}
return false;
}
#Override
protected void onDataLoad() {
if (_model.getElements().isEmpty()) {
addUnavailableItem();
showUnavailable();
}
else {
for (int i = 0; i < _model.getElements().size(); i++) {
addItem(_model.getElements().get(i), null);
}
}
}
#Override
protected void onSubmitDataRequest() {
_model.loadMore();
}
}
if (partnerAdpt.partnerList.getElements().remove(p));
p.setName("del-> " + p.getName());
With this code you only update filtered result. You should remove this values from the list you put in adapter with this code:
super(GeoPartnerActivity.this, model);
Try to get "model" data from adapter (not from abstract) and remove "p".

Categories

Resources