I'm trying to create an app that shows some questions and EditText fields in front of the each of the question for an answer with CountDownTimer, the problem I have is I'm trying to stop the running CountDownTimer on the last entered answer and save those seconds next to user's name but not sure how? I know questionTimer.cancel() would stop the timer but it has to be done on the last entered answer in last EditText.
This is the MainActivity.java file:
public class MainActivity extends AppCompatActivity {
CountDownTimer questionTimer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnStart = (Button) findViewById(R.id.start);
btnStart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
setQuestions();
timer();
}
});
}//End of create()
public void timer() {
questionTimer = new CountDownTimer(30000, 1000) {
public void onTick(long millisUntilFinished) {
timer = (TextView) findViewById(R.id.timer);
timer.setText("Seconds Remaining: " + millisUntilFinished / 1000);
}
public void onFinish() {
timer.setText("Done!");
}
}.start();
}
public void setQuestions() {
ArrayList<Questions> qArrList = new ArrayList<>();
for (int i = 0; i < 5; i++) {
ques = new Questions();
ques.setQuestion("");
qArrList.add(ques);
}
adapter = new AdapterListView(getBaseContext(), R.layout.item_listview, qArrList);
questListView.setAdapter(adapter);
}
}//End of Class
This is the AdapterListView.java file:
public class AdapterListView extends ArrayAdapter<Questions> {
Context mContext;
LayoutInflater inflater;
private ArrayList<Questions> questionsArrayList;
private Questions quesObject;
private ArrayList<String> quesList = new ArrayList<String>();
private int a, b, ab, c, d, cd, e, f, ef, g, h, gh, i, j, ij;
private ArrayList<Integer> answersList = new ArrayList<Integer>();
public AdapterListView(Context context, int resource, ArrayList<Questions> questionsArrayList) {
super(context, resource);
this.mContext = context;
this.setQuestionsArrayList(questionsArrayList);
this.inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
if (convertView == null) {
convertView = inflater.inflate(R.layout.item_listview, null);
holder = new ViewHolder();
holder.questionTextView = convertView.findViewById(R.id.question);
holder.editText = convertView.findViewById(R.id.ans_edit_text);
holder.imgTrue = convertView.findViewById(R.id.ans_true);
holder.imgFalse = convertView.findViewById(R.id.ans_false);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
quesObject = getQuestionsArrayList().get(position);
int count = 0;
if (position == 0) count = 1;
else if (position == 1) count = 2;
else if (position == 2) count = 3;
else if (position == 3) count = 4;
else if (position == 4) count = 5;
Random rand = new Random();
a = (rand.nextInt(15) + 1);
b = (rand.nextInt(10) + 1);
ab = a + b;
c = (rand.nextInt(15) + 1);
d = (rand.nextInt(10) + 1);
cd = c + d;
e = (rand.nextInt(15) + 1);
f = (rand.nextInt(10) + 1);
ef = e + f;
g = (rand.nextInt(15) + 1);
h = (rand.nextInt(10) + 1);
gh = g + h;
i = (rand.nextInt(15) + 1);
j = (rand.nextInt(10) + 10);
ij = i + j;
quesList.add(a + " + " + b);
quesList.add(c + " + " + d);
quesList.add(e + " + " + f);
quesList.add(g + " + " + h);
quesList.add(i + " + " + j);
getAnswersList().add(ab);
getAnswersList().add(cd);
getAnswersList().add(ef);
getAnswersList().add(gh);
getAnswersList().add(ij);
holder.questionTextView.setText("Q " + count + ": \t" + quesList.get(position));
holder.editText.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
if (holder.editText.getText().toString().trim().length() > 0) {
int inputNum = Integer.parseInt(String.valueOf(holder.editText.getText().toString().trim()));
if (getAnswersList().get(position) != inputNum) {
holder.imgFalse.setVisibility(View.VISIBLE);
holder.imgTrue.setVisibility(View.GONE);
} else {
holder.imgTrue.setVisibility(View.VISIBLE);
holder.imgFalse.setVisibility(View.GONE);
}
}
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
});
return convertView;
}
#Override
public int getCount() {
return getQuestionsArrayList().size();
}
static class ViewHolder {
TextView questionTextView;
EditText editText;
ImageView imgTrue, imgFalse;
}
}
I have manged to sort this out by setting an int variable against Position and calling this in MainActivity class inside the running Timer. Please see the code below.
public class MainActivity extends AppCompatActivity {
CountDownTimer questionTimer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnStart = (Button) findViewById(R.id.start);
btnStart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
setQuestions();
timer();
}
});
}//End of create()
public void timer() {
questionTimer = new CountDownTimer(30000, 1000) {
public void onTick(long millisUntilFinished) {
timer = (TextView) findViewById(R.id.timer);
timer.setText("Seconds Remaining: " + millisUntilFinished / 1000);
if (adapter.getEndQuiz() == 5) {
questionTimer.cancel();
}
}
public void onFinish() {
timer.setText("Done!");
}
}.start();
}
public void setQuestions() {
ArrayList<Questions> qArrList = new ArrayList<>();
for (int i = 0; i < 5; i++) {
ques = new Questions();
ques.setQuestion("");
qArrList.add(ques);
}
adapter = new AdapterListView(getBaseContext(), R.layout.item_listview, qArrList);
questListView.setAdapter(adapter);
}
}//End of Class
Adapter
public class AdapterListView extends ArrayAdapter<Questions> {
Context mContext;
LayoutInflater inflater;
private ArrayList<Questions> questionsArrayList;
private Questions quesObject;
private ArrayList<String> quesList = new ArrayList<String>();
private int a, b, ab, c, d, cd, e, f, ef, g, h, gh, i, j, ij;
private ArrayList<Integer> answersList = new ArrayList<Integer>();
private int endQuiz = 0;
public AdapterListView(Context context, int resource, ArrayList<Questions> questionsArrayList) {
super(context, resource);
this.mContext = context;
this.setQuestionsArrayList(questionsArrayList);
this.inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
if (convertView == null) {
convertView = inflater.inflate(R.layout.item_listview, null);
holder = new ViewHolder();
holder.questionTextView = convertView.findViewById(R.id.question);
holder.editText = convertView.findViewById(R.id.ans_edit_text);
holder.imgTrue = convertView.findViewById(R.id.ans_true);
holder.imgFalse = convertView.findViewById(R.id.ans_false);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
quesObject = getQuestionsArrayList().get(position);
int count = 0;
if (position == 0) count = 1;
else if (position == 1) count = 2;
else if (position == 2) count = 3;
else if (position == 3) count = 4;
else if (position == 4) count = 5;
Random rand = new Random();
a = (rand.nextInt(15) + 1);
b = (rand.nextInt(10) + 1);
ab = a + b;
c = (rand.nextInt(15) + 1);
d = (rand.nextInt(10) + 1);
cd = c + d;
e = (rand.nextInt(15) + 1);
f = (rand.nextInt(10) + 1);
ef = e + f;
g = (rand.nextInt(15) + 1);
h = (rand.nextInt(10) + 1);
gh = g + h;
i = (rand.nextInt(15) + 1);
j = (rand.nextInt(10) + 10);
ij = i + j;
quesList.add(a + " + " + b);
quesList.add(c + " + " + d);
quesList.add(e + " + " + f);
quesList.add(g + " + " + h);
quesList.add(i + " + " + j);
getAnswersList().add(ab);
getAnswersList().add(cd);
getAnswersList().add(ef);
getAnswersList().add(gh);
getAnswersList().add(ij);
holder.questionTextView.setText("Q " + count + ": \t" + quesList.get(position));
holder.editText.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
if (holder.editText.getText().toString().trim().length() > 0) {
int inputNum = Integer.parseInt(String.valueOf(holder.editText.getText().toString().trim()));
if (getAnswersList().get(position) != inputNum) {
holder.imgFalse.setVisibility(View.VISIBLE);
holder.imgTrue.setVisibility(View.GONE);
} else {
holder.imgTrue.setVisibility(View.VISIBLE);
holder.imgFalse.setVisibility(View.GONE);
}
if(position == 0) setEndQuiz(1);
else if(position == 1) setEndQuiz(2);
else if(position == 2) setEndQuiz(3);
else if(position == 3) setEndQuiz(4);
else if(position == 4) setEndQuiz(5);
}
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
});
return convertView;
}
#Override
public int getCount() {
return getQuestionsArrayList().size();
}
static class ViewHolder {
TextView questionTextView;
EditText editText;
ImageView imgTrue, imgFalse;
}
}
I am making a multi-video downloader. I have created a listview and for each item in the listview an asynctask is called which downloads the file in the background. Everything works perfect. But, if i want to delete an item from the listview for example from position 2, the item at position 3 (both are currently running) comes on position 2 and the asynctask attached previously to position 2 continues running and it shows the progress of asynctask that was previously attached to the position 2. How can I move the asynctask of position 3 to position 2.
Here is my Adapter Class from where I am calling the asynctask class:
public class DownloadInfoArrayAdapter extends ArrayAdapter<DownloadInfo> {
public static TextView progpercent;
// Simple class to make it so that we don't have to call findViewById frequently
// private static final String TAG = FileDownloadTask.class.getSimpleName();
public static Integer result;
LayoutInflater inflater5;
ImageView delete;
Activity activity1;
int mvalue;
ContextWrapper cw1;
int flag=0;
int status=0;
GlobalDownload downloadList;
ArrayList downloadState;
FileDownloadTask task;
private static class ViewHolder {
TextView textView;
ProgressBar progressBar;
ImageView delete;
DownloadInfo info;
TextView size;
TextView prog;
public TextView progpercent;
}
private static final String TAG = DownloadInfoArrayAdapter.class.getSimpleName();
public DownloadInfoArrayAdapter(Context context, int textViewResourceId,
List<DownloadInfo> objects, ContextWrapper cw, Activity DownloadScreen) {
super(context, textViewResourceId, objects);
cw1=cw;
activity1=DownloadScreen;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View row = convertView;
final DownloadInfo info = getItem(position);
ViewHolder holder = null;
if(null == row) {
LayoutInflater inflater = (LayoutInflater)getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = inflater.inflate(R.layout.file_download_row, parent, false);
holder = new ViewHolder();
holder.textView = (TextView) row.findViewById(R.id.downloadFileName);
holder.progressBar = (ProgressBar) row.findViewById(R.id.downloadProgressBar);
holder.size=(TextView) row.findViewById(R.id.downloadFileSize);
holder.progpercent=(TextView) row.findViewById(R.id.downloadFileProgress);
holder.delete=(ImageView) row.findViewById(R.id.deletebutton);
// holder.button = (Button)row.findViewById(R.id.downloadButton);
// holder.info = info;
row.setTag(holder);
} else {
holder = (ViewHolder) row.getTag();
}
holder.textView.setText(info.getFilename());
holder.progpercent.setText(info.getDownloadState().toString());
if(info.getStatus()== null)
{
Log.e("DATABASE1", "null ");
status=3;
info.setLastState(2);
}
else if(info.getStatus()== DownloadInfo.State.DONE)
{
if(info.getLastState()==1)
{
Log.e("DATABASE", "LS " + 1);
info.setDownloadState(DownloadInfo.DownloadState.COMPLETE);
status=1;
}
else if(info.getLastState()==0)
{
Log.e("DATABASE", "LS " + 2);
info.setDownloadState(DownloadInfo.DownloadState.FAILED);
status=1;
}
else
{
status=2;
}
}
Log.e("DATABASE", "DOWNLOAD STATE " + info.getDownloadState().toString());
if(info.getDownloadState()== DownloadInfo.DownloadState.NOT_STARTED)
{
if(status==3) {
holder.progressBar.setProgress(info.getProgress());
holder.progressBar.setMax(100);
holder.progpercent.setText("DOWNLOADING");
}
}
holder.size.setText(info.getFileSize());
info.setProgressBar(holder.progressBar);
if(info.getDownloadState()==DownloadInfo.DownloadState.NOT_STARTED){ info.setDownloadState(DownloadInfo.DownloadState.DOWNLOADING);
if (MainScreen.settingsvalue==0) {
Log.e("DATABASE", " " + 0);
mvalue = 0;
task = new FileDownloadTask(info, cw1, activity1, mvalue);
task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
if(info.getDownloadState()== DownloadInfo.DownloadState.COMPLETE) {
Log.e("DATABASE", "UPDATE COMPLETE " + info.getDownloadState());
info.setStatus(DownloadInfo.State.DONE);
info.setLastState(1);
holder.progressBar.setProgress(R.drawable.download_bar);
holder.progpercent.setText(info.getDownloadState().toString());
cancelstatus=0;
}
if(info.getDownloadState()== DownloadInfo.DownloadState.FAILED) {
info.setStatus(DownloadInfo.State.DONE);
MainScreen.newDB.execSQL("update " + DatabaseHelper.TABLE_NAME + " set " + DatabaseHelper.COL_6 + " = '" + info.getStatus() + "', " + DatabaseHelper.COL_7 + " =0 where " + DatabaseHelper.COL_1 + " = " + info.getFileid());
Log.e("DATABASE", "UPDATED ");
info.setLastState(0);
holder.progpercent.setText(info.getDownloadState().toString());
cancelstatus=0;
}
holder.delete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Integer index = (Integer) v.getTag();
Log.e("POSITION", "TAG " + index);
Log.e("POSITION", "POSITION " + position);
downloadList = ((GlobalDownload) activity1.getApplicationContext());
downloadState = (ArrayList) downloadList.getDownloadInfo();
CustomDialogClass.downloadfile=file.getAbsolutePath().toString();
CustomDialogClass2.customfilename2= info.getFilename() + "." + info.getFileType();
Log.e("VIDEOPATH", " " + CustomDialogClass.downloadfile);
CustomDialogClass2 cdd = new CustomDialogClass2(MainScreen.activity1);
cdd.show();
CustomDialogClass2.mPosition=position;
CustomDialogClass2.id=info.getFileid();
// downloadState.remove(position);
Log.e("STATUS", "Status before stopping " + info.getDownloadState());
if((info.getDownloadState()== DownloadInfo.DownloadState.DOWNLOADING)) {
info.setDownloadState(DownloadInfo.DownloadState.COMPLETE);
cancelstatus=1;
task.cancel(true);
}
}
});
return row;
}
}
Here is the Asynctask class
public class FileDownloadTask extends AsyncTask<String, Integer, Integer> {
private static final String TAG = FileDownloadTask.class.getSimpleName();
final DownloadInfo mInfo;
TextView display;
public int progress;
public String encodedurl;
PopupWindow popupWindow;
Activity activity;
// ListView listview1;
// Context context;
LayoutInflater layoutInflater;
static int i=0;
int Mvalue;
ContextWrapper cw;
File file;
String nameoffile;
PowerManager mgr;
PowerManager.WakeLock wakeLock;
public static int cancelstatus =0;
int a=0;
// DownloadInfoArrayAdapter mAdapter;
public FileDownloadTask(DownloadInfo info, ContextWrapper cw1, Activity activity1, int mvalue) {
mInfo = info;
cw=cw1;
activity=activity1;
this.Mvalue=mvalue;
// listView1 = (ListView) listview.findViewById(R.id.downloadListView);
// mAdapter = new DownloadInfoArrayAdapter(, R.id.downloadListView,mInfo);
}
// #Override
protected void onProgressUpdate(Integer... values) {
mInfo.setProgress(values[0]);
mInfo.setFilePercent(values[0]);
// Log.e("FILE PERCENT", String.valueOf(mInfo.getFilePercent()));
// mAdapter.notifyDataSetChanged();
// mAdapter.setNotifyOnChange(true);
// display = (TextView) row.findViewById(R.id.downloadFileProgress);
ProgressBar bar = mInfo.getProgressBar();
// Integer percent=mInfo.getFilePercent();
if (bar != null) {
bar.setProgress(mInfo.getProgress());
// percent(mInfo.getFilePercent());
// display.setText(mInfo.getProgress());
// bar.invalidate();
}
// DownloadScreen.adapter.notifyDataSetChanged();
// DownloadScreen.listView.setAdapter(DownloadScreen.adapter);
}
#Override
protected void onCancelled() {
super.onCancelled();
mInfo.setDownloadState(DownloadInfo.DownloadState.COMPLETE);
File rootdirectory = new File(Environment.getExternalStorageDirectory(), "YoutubeDownloaderVideos");
File file = new File(rootdirectory, CustomDialogClass2.customfilename2);
Log.e("FILE", " name" + file.toString());
file.delete();
DownloadScreen.adapter.notifyDataSetChanged();
}
#Override
protected Integer doInBackground(String... params) {
int count;
try {
String state = Environment.getExternalStorageState();
String root = Environment.getExternalStorageDirectory().toString();
URL url = new URL(mInfo.getFileUrl().toString());
Log.e("URL", "" + url);
HttpURLConnection conection = (HttpURLConnection) url.openConnection();
conection.connect();
Log.e("connection", " " + 0);
int lenghtOfFile = conection.getContentLength();
Log.e("length", "" + lenghtOfFile);
String nameoffile = mInfo.getFilename() + "." + mInfo.getFileType();
if (Environment.MEDIA_MOUNTED.equals(state)) {
File rootdirectory = new File(Environment.getExternalStorageDirectory(), "YoutubeDownloaderVideos");
if (!rootdirectory.exists()) {
rootdirectory.mkdirs();
}
File file = new File(rootdirectory, nameoffile);
file.createNewFile();
Log.e("name of file", "" + nameoffile);
InputStream input = new BufferedInputStream(url.openStream(), 8192);
OutputStream output = new FileOutputStream(file);
byte data[] = new byte[1024];
mInfo.setDownloadState(DownloadInfo.DownloadState.DOWNLOADING);
long total = 0;
while ((count = input.read(data)) != -1) {
if(!isCancelled()) {
total += count;
progress = (int) ((total * 100) / lenghtOfFile);
publishProgress(progress);
// Log.e("PROGRESS", "" + mInfo.getFileType() + progress);
mInfo.setFilePercent(progress);
output.write(data, 0, count);
i = 1;
}
}
mInfo.setDownloadState(DownloadInfo.DownloadState.COMPLETE);
mInfo.setStatus(DownloadInfo.State.COMPLETE);
output.flush();
output.close();
input.close();
Log.e("Download Complete", "" + 0);
Log.e("DEVICE SDCARD", " " + Mvalue);
}
return progress;
}
protected void onPostExecute(Integer progress) {
mInfo.setDownloadState(DownloadInfo.DownloadState.COMPLETE);
DownloadScreen.adapter.notifyDataSetChanged();
DownloadScreen.listView.setAdapter(DownloadScreen.adapter);
Uri contentUri = Uri.fromFile(file);
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,contentUri);
activity.sendBroadcast(mediaScanIntent);
CustomDialogClass.downloadfile=file.getAbsolutePath().toString();
CustomDialogClass.customfilename=mInfo.getFilename() + "." + mInfo.getFileType();
Log.e("VIDEOPATH", " " + CustomDialogClass.downloadfile);
CustomDialogClass cdd = new CustomDialogClass(MainScreen.activity1);
cdd.show();
}
#Override
protected void onPreExecute() {
}
}
you should override the remove method of your adapter in order to cancel properly the asyncTask associated to your item.
I am having a listview which I am populating from a database.
The listview is taking some time(<300ms) to populate the list.
If I am doing a smoothScrollToPosition on the onActivityCreated function it is doing nothing.
On the OnCreate function I had to wait for ~200ms before I could call smoothScrollToPosition before which even the ListView Object is not initialized.
I can use the getViewTreeObserver as below which runs fine but it requires the minimum sdk version 16. I was trying to get it working for version 14~15.
mListView.getViewTreeObserver().addOnGlobalLayoutListener(
new ViewTreeObserver.OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
mListView.smoothScrollToPosition(adapter.getCount());
// unregister listener (this is important)
mListView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
}
});
The code I am having -
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
list = new ArrayList<Chat>();
db = new DBAdapter(getContext());
adapter = new CustomChatAdapter(getContext(), list);
Log.d("ListView1", "Value of f: " + f);
thread= new Thread(){
#Override
public void run(){
try {
synchronized(this){
wait(200);
}
}
catch(InterruptedException ex){
Log.d("ListView1", "Interrupted Exception: " +ex.toString());
}
Log.d("ListView1", "Adapter Count: " +adapter.getCount());
mListView.smoothScrollToPosition(adapter.getCount());
}
};
getMsg("1", getActivity().getIntent().getStringExtra("key"));
thread.start();
Log.d("ListView1", "Adapter Count: " +adapter.getCount());
//mListView.smoothScrollToPosition(adapter.getCount());
}
public void getMsg(String myid, String friend_id) {
list.clear();
try {
Cursor cur = db.get_friend_shouts(myid,friend_id);
String img_id1 = "";
String img_id2 ="";
if (cur != null) {
if (cur.moveToFirst()) {
do {
img_id1 = cur.getString(cur.getColumnIndex("image_id"));
img_id1 = img_id1 == null ? "null" : img_id1;
img_id2 = cur.getString(cur.getColumnIndex("r_img_id"));
img_id2 = img_id2 == null ? "null" : img_id2;
list.add(new Chat( img_id1 , cur.getString(cur.getColumnIndex("firstname")) + " " + cur.getString(cur.getColumnIndex("lastname")), cur.getString(cur.getColumnIndex("user_id")),
cur.getString(cur.getColumnIndex("shout_msg")) ,
img_id2, cur.getString(cur.getColumnIndex("r_firstname")) + " " + cur.getString(cur.getColumnIndex("r_lastname")) , cur.getString(cur.getColumnIndex("r_user_id")) , cur.getString(cur.getColumnIndex("rec_time")) ));
//Log.d("ListView1", "User details: " + cur.getString(cur.getColumnIndex("user_id")) + " " + cur.getString(cur.getColumnIndex("firstname")) + cur.getString(cur.getColumnIndex("lastname")) + " " + cur.getString(cur.getColumnIndex("image_id")));
} while (cur.moveToNext());
}
}
adapter.notifyDataSetChanged();
if(mListView!=null)
mListView.smoothScrollToPosition(adapter.getCount());
} catch (Exception e) {
Log.d("ListView1", "getMsg Error: " + e.toString());
}
}
The ArrayAdapter class -
public class CustomChatAdapter extends ArrayAdapter<Chat> {
private final Context context;
private final List<Chat> list;
public CustomChatAdapter(Context context, ArrayList<Chat> presidents) {
super(context, R.layout.chatrowlayout, presidents);
this.context = context;
this.list = presidents;
}
static class ViewContainer { public ImageView imageView; public TextView txtMsg; public ImageView imageView1; public TextView txtTime; }
#Override
public View getView(int position, View view, ViewGroup parent) {
ViewContainer viewContainer;
View rowView = view;
//---print the index of the row to examine---
//Log.d("ListView1",String.valueOf(position));
//if(rowView == null) {
viewContainer = new ViewContainer();
LayoutInflater inflater = LayoutInflater.from(context);
rowView= inflater.inflate(R.layout.chatrowlayout, null, true);
viewContainer.txtMsg = (TextView) rowView.findViewById(R.id.msgText);
viewContainer.imageView = (ImageView) rowView.findViewById(R.id.icon1);
viewContainer.imageView1 = (ImageView) rowView.findViewById(R.id.icon2);
viewContainer.txtTime = (TextView) rowView.findViewById(R.id.timeText);
rowView.setTag(viewContainer);
/*} else {
viewContainer = (ViewContainer) rowView.getTag();
}*/
viewContainer.txtMsg.setText(list.get(position).getMsg());
viewContainer.txtTime.setText(list.get(position).getMsg_time());
if(list.get(position).getS_id().equals("1")) {
viewContainer.imageView.setImageBitmap(BitmapFactory.decodeFile(new Info().p + File.separator+ "image_" + list.get(position).getPic_id1() + ".jpeg" ));
viewContainer.imageView1.setAlpha(0);
viewContainer.txtMsg.setGravity(Gravity.LEFT);
} else {
viewContainer.imageView1.setImageBitmap(BitmapFactory.decodeFile(new Info().p + File.separator+ "image_" + list.get(position).getPic_id1() + ".jpeg" ));
viewContainer.imageView.setAlpha(0);
viewContainer.txtMsg.setGravity(Gravity.RIGHT);
}
return rowView;
}
}
removeGlobalOnLayoutListerner for pre SDK 16, addOnGlobalLayout works for pre 16.
OnCreate is too early.
You should wait for the layout to be inflated. Smooth scrolling in onResume should do the trick:
#Override
protected void onResume() {
mListView.smoothScrollToPosition(adapter.getCount());
}
How to call AsyncTask class in the fragment class, when i call is not go in the AsyncTask it will return null view what i do ? And my view is created in postExecute afetr i got all the data from doInbackground.
public class ShowResultsFragment extends android.support.v4.app.Fragment {
Context context;
ArrayList<Semester> semesterArrayList;
LayoutInflater inflaterView;
ViewGroup containerView;
View newView;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
this.inflaterView = inflater;
this.containerView = container;
context = container.getContext();
new StudentResultAsyncTask().execute();
return newView;
}
public class StudentResultAsyncTask extends AsyncTask {
JSONObject jsonObject = null;
ProgressDialog pDialog;
String jsondata = "{\"1\" :[{\"subName\":\"EG\",\"subCode\":\"1009\",\"subCredit\":\"5\",\"subGrade\":\"AA\"}," +
"{\"subName\":\"ES\",\"subCode\":\"2009\",\"subCredit\":\"6\",\"subGrade\":\"DD\"}," +
"{\"subName\":\"EME\",\"subCode\":\"3009\",\"subCredit\":\"6\",\"subGrade\":\"FF\"}," +
"{\"subName\":\"EEE\",\"subCode\":\"4009\",\"subCredit\":\"7\",\"subGrade\":\"BC\"}," +
"{\"subName\":\"MOS\",\"subCode\":\"5009\",\"subCredit\":\"6\",\"subGrade\":\"FF\"}," +
"{\"subName\":\"M-1\",\"subCode\":\"1009\",\"subCredit\":\"6\",\"subGrade\":\"CD\"}," +
"{\"subName\":\"EE\",\"subCode\":\"45090\",\"subCredit\":\"4\",\"subGrade\":\"AB\"}," +
"{\"subName\":\"ECE\",\"subCode\":\"10090\",\"subCredit\":\"5\",\"subGrade\":\"FF\"}," +
"{\"SPI\":\"1.4\",\"CPI\":\"4.67\"}]," +
"\"2\":[{\"subName\":\"M-2\",\"subCode\":\"111009\",\"subCredit\":\"6\",\"subGrade\":\"DD\"}," +
"{\"subName\":\"Workshop\",\"subCode\":\"1009\",\"subCredit\":\"6\",\"subGrade\":\"AB\"}," +
"{\"subName\":\"CPU\",\"subCode\":\"1009\",\"subCredit\":\"6\",\"subGrade\":\"FF\"}," +
"{\"subName\":\"EG\",\"subCode\":\"1009\",\"subCredit\":\"6\",\"subGrade\":\"CC\"}," +
"{\"subName\":\"M-4\",\"subCode\":\"1009\",\"subCredit\":\"6\",\"subGrade\":\"CD\"}," +
"{\"subName\":\"AE\",\"subCode\":\"103309\",\"subCredit\":\"6\",\"subGrade\":\"CD\"}," +
"{\"subName\":\"EG-1\",\"subCode\":\"11119\",\"subCredit\":\"6\",\"subGrade\":\"CD\"}," +
"{\"subName\":\"AE\",\"subCode\":\"8876\",\"subCredit\":\"6\",\"subGrade\":\"FF\"}," +
"{\"SPI\":\"2.5\",\"CPI\":\"6.67\"}]," +
"\"3\":[{\"subName\":\"M-3\",\"subCode\":\"111009\",\"subCredit\":\"6\",\"subGrade\":\"AA\"}," +
"{\"subName\":\"BE\",\"subCode\":\"1009\",\"subCredit\":\"6\",\"subGrade\":\"AB\"}," +
"{\"subName\":\"DLD\",\"subCode\":\"1009\",\"subCredit\":\"6\",\"subGrade\":\"BB\"}," +
"{\"subName\":\"NCS\",\"subCode\":\"1009\",\"subCredit\":\"6\",\"subGrade\":\"BC\"}," +
"{\"subName\":\"M-4\",\"subCode\":\"1009\",\"subCredit\":\"6\",\"subGrade\":\"CC\"}," +
"{\"subName\":\"AE\",\"subCode\":\"103309\",\"subCredit\":\"6\",\"subGrade\":\"CD\"}," +
"{\"SPI\":\"6.50\",\"CPI\":\"0.67\"}]," +
"\"4\":[{\"subName\":\"AAS\",\"subCode\":\"111009\",\"subCredit\":\"6\",\"subGrade\":\"AB\"}," +
"{\"subName\":\"C++\",\"subCode\":\"1009\",\"subCredit\":\"6\",\"subGrade\":\"AB\"}," +
"{\"subName\":\"Management-1\",\"subCode\":\"1009\",\"subCredit\":\"6\",\"subGrade\":\"AB\"}," +
"{\"subName\":\"EG\",\"subCode\":\"1009\",\"subCredit\":\"6\",\"subGrade\":\"AB\"}," +
"{\"subName\":\"M-4\",\"subCode\":\"1009\",\"subCredit\":\"6\",\"subGrade\":\"AB\"}," +
"{\"subName\":\"AE\",\"subCode\":\"103309\",\"subCredit\":\"6\",\"subGrade\":\"DD\"}," +
"{\"SPI\":\"9.50\",\"CPI\":\"5.67\"}]," +
"\"5\":[{\"subName\":\"WAD\",\"subCode\":\"111022209\",\"subCredit\":\"6\",\"subGrade\":\"FF\"}," +
"{\"subName\":\"AES\",\"subCode\":\"703309\",\"subCredit\":\"6\",\"subGrade\":\"DD\"}," +
"{\"SPI\":\"5.50\",\"CPI\":\"5.67\",\"CGPA\":\"5.67\"}]," +
"\"6\":[{\"subName\":\"SP\",\"subCode\":\"66622209\",\"subCredit\":\"6\",\"subGrade\":\"FF\"}," +
"{\"subName\":\"Parallel\",\"subCode\":\"66622209\",\"subCredit\":\"6\",\"subGrade\":\"AB\"}," +
"{\"subName\":\"Java\",\"subCode\":\"66622209\",\"subCredit\":\"6\",\"subGrade\":\"AB\"}," +
"{\"subName\":\"COA\",\"subCode\":\"66622209\",\"subCredit\":\"6\",\"subGrade\":\"AB\"}," +
"{\"subName\":\"Management\",\"subCode\":\"66622209\",\"subCredit\":\"6\",\"subGrade\":\"FF\"}," +
"{\"subName\":\"TOC\",\"subCode\":\"703309\",\"subCredit\":\"6\",\"subGrade\":\"DD\"}," +
"{\"SPI\":\"5.50\",\"CPI\":\"5.67\",\"CGPA\":\"6.07\"}]," +
"\"7\":[{\"subName\":\"CD\",\"subCode\":\"12522209\",\"subCredit\":\"6\",\"subGrade\":\"AB\"}," +
"{\"subName\":\"WCMP\",\"subCode\":\"12522209\",\"subCredit\":\"6\",\"subGrade\":\"AB\"}," +
"{\"subName\":\"SP\",\"subCode\":\"12522209\",\"subCredit\":\"6\",\"subGrade\":\"AB\"}," +
"{\"subName\":\"Advance Java\",\"subCode\":\"703309\",\"subCredit\":\"6\",\"subGrade\":\"FF\"}," +
"{\"SPI\":\"8.90\",\"CPI\":\"6.09\",\"CGPA\":\"7.77\"}]," +
"\"8\":[{\"subName\":\"Android\",\"subCode\":\77022209\",\"subCredit\":\"6\",\"subGrade\":\"AB\"}," +
"{\"subName\":\"PP\",\"subCode\":2209\",\"subCredit\":\"6\",\"subGrade\":\"BB\"}," +
"{\"subName\":\"DS\",\"subCode\":\"7309\",\"subCredit\":\"6\",\"subGrade\":\"DD\"}," +
"{\"SPI\":\"5.70\",\"CPI\":\"5.97\",\"CGPA\":\"6.85\"}]}";
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(context);
pDialog.setMessage("Loading...");
pDialog.show();
}
#Override
protected String doInBackground(String... params1) {
String key;
Iterator<String> iter;
int length;
/* List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair(c.getResources().getString(R.string.keyUsername), Utility.getUsername(c)));
JSONParser jp=new JSONParser();
//jp.makeHttpRequest(c.getResources().getString(R.string.server_name)+ c.getResources().getString(R.string.login_file), "POST", params);
*/ //Todo : delete comment when data is come from server.
try {
jsonObject = new JSONObject(jsondata);
} catch (JSONException e) {
e.printStackTrace();
}
iter = jsonObject.keys();
semesterArrayList = new ArrayList<>();
while (iter.hasNext()) {
key = iter.next();
try {
JSONArray jsonArray = jsonObject.getJSONArray(key);
length = jsonArray.length();
ArrayList<SubjectDetails> saveSubDetailsArrayList = new ArrayList<>();
Semester semDetail = new Semester();
semDetail.setSemester(key);
for (int i = 0; i < length; i++) {
JSONObject jsonObject1 = jsonArray.getJSONObject(i);
SubjectDetails subDetails = new SubjectDetails();
if (i == length - 1) {
Float spi = Float.valueOf(jsonObject1.getString(getResources().getString(R.string.server_key_result_SPI)));
Float cpi = Float.valueOf(jsonObject1.getString(getResources().getString(R.string.server_key_result_CPI)));
semDetail.setSpi(spi);
semDetail.setCpi(cpi);
if (key.equals("5") || key.equals("6") || key.equals("7") || key.equals("8")) {
Float cgpi = Float.valueOf(jsonObject1.getString(getResources().getString(R.string.server_key_result_CGPA)));
semDetail.setCgpi(cgpi);
}
} else {
String subname = jsonObject1.getString(getResources().getString(R.string.server_key_result_subName));
String subcode = jsonObject1.getString(getResources().getString(R.string.server_key_result_subCode));
String subcredit = jsonObject1.getString(getResources().getString(R.string.server_key_result_subCredit));
String subgrade = jsonObject1.getString(getResources().getString(R.string.server_key_result_subGrade));
subDetails.setSubname(subname);
subDetails.setSubcode(subcode);
subDetails.setSubcredit(subcredit);
subDetails.setSubgrade(subgrade);
saveSubDetailsArrayList.add(subDetails);
semDetail.setGetSubjectDetails(saveSubDetailsArrayList);
}
}
semesterArrayList.add(semDetail);
} catch (JSONException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
ListView lv = (ListView) newView.findViewById(R.id.listview);
lv.setAdapter(new ShowResultAdapter(semesterArrayList, context));
pDialog.dismiss();
}
}
and this is my Adapter class...
public class ShowResultAdapter extends BaseAdapter {
ArrayList<Semester> semesterArrayList;
Context c;
LinearLayout linearHeader;
ShowResultAdapter(ArrayList<Semester> saveDetails, Context context)
{
semesterArrayList = saveDetails;
c = context;
}
#Override
public int getCount() {
return semesterArrayList.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
LinearLayout linearSub;
LinearLayout linearSpiCpiCgpa;
LayoutInflater inflater = (LayoutInflater) c.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.layout_result_adapter, null);
LinearLayout linearLayout = (LinearLayout) view.findViewById(R.id.linear);
TextView sem = new TextView(c);
sem.setGravity(Gravity.CENTER_HORIZONTAL);
sem.setTextSize(20);
sem.setPadding(0, 0, 0, 10);
sem.setTextColor(Color.WHITE);
sem.setText(c.getResources().getString(R.string.result_Semester) + " " + ":" + " " + semesterArrayList.get(position).getSemester());
sem.setPaintFlags(Paint.UNDERLINE_TEXT_FLAG);
linearLayout.addView(sem);
linearHeader = new LinearLayout(c);
linearHeader.setOrientation(LinearLayout.HORIZONTAL);
linearHeader.setWeightSum(4);
TextView name = new TextView(c);
setHeader(name, c.getResources().getString(R.string.server_key_result_subName));
linearHeader.addView(name);
TextView code = new TextView(c);
setHeader(code, c.getResources().getString(R.string.server_key_result_subCode));
linearHeader.addView(code);
TextView credit = new TextView(c);
setHeader(credit, c.getResources().getString(R.string.server_key_result_subCredit));
linearHeader.addView(credit);
TextView grade = new TextView(c);
setHeader(grade, c.getResources().getString(R.string.server_key_result_subGrade));
linearHeader.addView(grade);
linearLayout.addView(linearHeader);
if (semesterArrayList.get(position).getSemester().equals("1") || semesterArrayList.get(position).getSemester().equals("2") || semesterArrayList.get(position).getSemester().equals("3") || semesterArrayList.get(position).getSemester().equals("4")) {
linearSpiCpiCgpa = new LinearLayout(c);
linearSpiCpiCgpa.setOrientation(LinearLayout.HORIZONTAL);
linearSpiCpiCgpa.setWeightSum(4);
for (int i = 0; i < semesterArrayList.get(position).getGetSubjectDetails().size(); i++)
{
linearSub = new LinearLayout(c);
linearSub.setLayoutParams(new TableLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, 4));
linearSub.setOrientation(LinearLayout.HORIZONTAL);
TextView subname = new TextView(c);
setSubject(subname);
TextView subcode = new TextView(c);
setSubject(subcode);
TextView subcredit = new TextView(c);
setSubject(subcredit);
TextView subgrade = new TextView(c);
setSubject(subgrade);
subgrade.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD));
subname.setText(semesterArrayList.get(position).getGetSubjectDetails().get(i).getSubname());
subcode.setText(semesterArrayList.get(position).getGetSubjectDetails().get(i).getSubcode());
subcredit.setText(semesterArrayList.get(position).getGetSubjectDetails().get(i).getSubcredit());
subgrade.setText(semesterArrayList.get(position).getGetSubjectDetails().get(i).getSubgrade());
if (semesterArrayList.get(position).getGetSubjectDetails().get(i).getSubgrade().equals("FF")) {
subgrade.setTextColor(Color.parseColor("#ff0000"));
}
linearSub.addView(subname);
linearSub.addView(subcode);
linearSub.addView(subcredit);
linearSub.addView(subgrade);
linearLayout.addView(linearSub);
}
TextView spi = new TextView(c);
setSpiCpiCgpa(spi);
TextView cpi = new TextView(c);
setSpiCpiCgpa(cpi);
spi.setText(c.getResources().getString(R.string.server_key_result_SPI) + " " + ":" + " " + semesterArrayList.get(position).getSpi());
cpi.setText(c.getResources().getString(R.string.server_key_result_CPI) + " " + ":" + " " + semesterArrayList.get(position).getCpi());
linearSpiCpiCgpa.addView(spi);
linearSpiCpiCgpa.addView(cpi);
linearLayout.addView(linearSpiCpiCgpa);
} else {
linearSpiCpiCgpa = new LinearLayout(c);
linearSpiCpiCgpa.setOrientation(LinearLayout.HORIZONTAL);
linearSpiCpiCgpa.setWeightSum(6);
for (int i = 0; i < semesterArrayList.get(position).getGetSubjectDetails().size(); i++)
{
linearSub = new LinearLayout(c);
linearSub.setOrientation(LinearLayout.HORIZONTAL);
linearSub.setLayoutParams(new TableLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, 4));
TextView subname = new TextView(c);
setSubject(subname);
TextView subcode = new TextView(c);
setSubject(subcode);
TextView subcredit = new TextView(c);
setSubject(subcredit);
TextView subgrade = new TextView(c);
setSubject(subgrade);
subname.setText(semesterArrayList.get(position).getGetSubjectDetails().get(i).getSubname());
subcode.setText(semesterArrayList.get(position).getGetSubjectDetails().get(i).getSubcode());
subcredit.setText(semesterArrayList.get(position).getGetSubjectDetails().get(i).getSubcredit());
subgrade.setText(semesterArrayList.get(position).getGetSubjectDetails().get(i).getSubgrade());
linearSub.addView(subname);
linearSub.addView(subcode);
linearSub.addView(subcredit);
linearSub.addView(subgrade);
linearLayout.addView(linearSub);
}
TextView spi = new TextView(c);
setSpiCpiCgpa(spi);
TextView cpi = new TextView(c);
setSpiCpiCgpa(cpi);
TextView cgpi = new TextView(c);
setSpiCpiCgpa(cgpi);
spi.setText(c.getResources().getString(R.string.server_key_result_SPI) + " " + ":" + " " + semesterArrayList.get(position).getSpi());
cpi.setText(c.getResources().getString(R.string.server_key_result_CPI) + " " + ":" + " " + semesterArrayList.get(position).getCpi());
cgpi.setText(c.getResources().getString(R.string.server_key_result_CGPA) + " " + ":" + " " + semesterArrayList.get(position).getCgpi());
linearSpiCpiCgpa.addView(spi);
linearSpiCpiCgpa.addView(cpi);
linearSpiCpiCgpa.addView(cgpi);
linearLayout.addView(linearSpiCpiCgpa);
}
return view;
}
public void setHeader(TextView txtObj, String setText) {
txtObj.setPadding(0, 0, 0, 10);
txtObj.setGravity(Gravity.CENTER_HORIZONTAL);
txtObj.setBackgroundResource(R.drawable.whiteborder);
txtObj.setTextColor(Color.WHITE);
txtObj.setBackgroundColor(Color.parseColor("#80000000"));
txtObj.setTextSize(16);
txtObj.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD));
txtObj.setLayoutParams(new TableLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, 1));
txtObj.setText(setText);
}
public void setSubject(TextView txtObj) {
txtObj.setLayoutParams(new TableLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT, 1));
txtObj.setPadding(5, 5, 5, 5);
txtObj.setBackgroundResource(R.drawable.resultborder);
txtObj.setTextColor(Color.WHITE);
txtObj.setGravity(Gravity.CENTER);
}
public void setSpiCpiCgpa(TextView txtObj) {
txtObj.setPadding(5, 5, 5, 5);
txtObj.setGravity(Gravity.CENTER_HORIZONTAL);
txtObj.setTextColor(Color.WHITE);
txtObj.setBackgroundResource(R.drawable.resultborder);
txtObj.setTypeface(Typeface.defaultFromStyle(Typeface.BOLD));
txtObj.setLayoutParams(new TableLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT, 2));
}
}
You didn't inflate your View. How do you expect it to not return null?
You should inflate the View in onCreateView() rather than in onPostExecute()
Change it like this.
ShowResultAdapter adapter = null;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
this.inflaterView = inflater;
this.containerView = container;
context = container.getContext();
newView = inflaterView.inflate(R.layout.your_layout, null);
lv = (ListView) newView.findViewById(R.id.listview); // Define lv at class level
adapter = new ShowResultAdapter(semesterArrayList, getActivity())
lv.setAdapter(adapter);
new StudentResultAsyncTask().execute();
return newView;
}
In your onPostExecute() method do this
protected void onPostExecute(String s)
{
super.onPostExecute(s);
adapter.notifyDataSetChanged();
pDialog.dismiss();
}
Following from the suggestions made by Rohit5k2, alter your getcount() method in your adapter to respond to null data:
#Override
public int getCount() {
if (semesterArrayList == null) {
return 0;
}
return semesterArrayList.size();
}
When you first call setAdapter() on the ListView in Rohit's answer, the data will be null as it is only populated in onPostExecute(). However, if you make the above adjustment, then all will happen is that the list will be empty until the data is populated.
I have a problem while displaying a list on Sony SmartWatch 2.
I copied layouts from sample project (AdvancedControlSample) and I have the following class:
public class OpenPositionsView extends ControlExtension implements BaseView {
private static final String LOG_TAG = "TAGG";
private Context context;
private ControlViewGroup mLayout;
public OpenPositionsView(Context context, String hostAppPackageName) {
super(context, hostAppPackageName);
this.context = context;
mLayout = setup();
}
public ControlViewGroup setup() {
Log.i(LOG_TAG, "setup");
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View layout = inflater.inflate(R.layout.watch_positions, null);
ControlViewGroup mLayout = (ControlViewGroup) parseLayout(layout);
return mLayout;
}
public void show(Controller parent) {
int listCount = DataProvider.getInstance().getPositions().size();
parent.sendListCountM(R.id.watch_positions_listview, listCount);
parent.sendListPositionM(R.id.watch_positions_listview, 0);
parent.refreshLayout(R.layout.watch_positions, null);
Log.i(LOG_TAG, "show [listCount: " + listCount + "]");
}
#Override
public void onRequestListItem(final int layoutReference, final int listItemPosition) {
Log.d(LOG_TAG, "onRequestListItem [layoutReference: " + layoutReference + ", position: " + listItemPosition + "]");
if (layoutReference != -1 && listItemPosition != -1 && layoutReference == R.id.watch_positions_listview) {
ControlListItem item = createControlListItem(listItemPosition);
if (item != null) {
Log.d(LOG_TAG, "Sending list item");
sendListItem(item);
}
}
}
#Override
public void onListItemSelected(ControlListItem listItem) {
super.onListItemSelected(listItem);
}
#Override
public void onListItemClick(final ControlListItem listItem, final int clickType, final int itemLayoutReference) {
Log.d(LOG_TAG, "onListItemClick [listItemPosition: " + listItem.listItemPosition + ", clickType: " + clickType + ", itemLayoutReference: "
+ itemLayoutReference + "]");
}
public void onClick(int id) {
mLayout.onClick(id);
}
protected ControlListItem createControlListItem(int position) {
Log.d(LOG_TAG, "createControlListItem [position: " + position + "]");
ControlListItem item = new ControlListItem();
item.layoutReference = R.id.watch_positions_listview;
item.dataXmlLayout = R.layout.watch_positions_item;
item.listItemPosition = position;
// We use position as listItemId. Here we could use some other unique id
// to reference the list data
item.listItemId = position;
Position target = DataProvider.getInstance().getPosition(position);
if (target != null) {
Bundle symbolBundle = new Bundle();
symbolBundle.putInt(Control.Intents.EXTRA_LAYOUT_REFERENCE, R.id.watch_position_symbol);
symbolBundle.putString(Control.Intents.EXTRA_TEXT, target.getSymbol());
Bundle typeBundle = new Bundle();
typeBundle.putInt(Control.Intents.EXTRA_LAYOUT_REFERENCE, R.id.watch_position_type);
typeBundle.putString(Control.Intents.EXTRA_TEXT, target.getTypeAsString());
item.layoutData = new Bundle[2];
item.layoutData[0] = symbolBundle;
item.layoutData[1] = typeBundle;
Log.d(LOG_TAG, "Item list created: [symbolBundle: " + symbolBundle + ", typeBundle: " + typeBundle + "]");
}
return item;
}
protected Bundle[] createBundle(int position) {
Bundle[] result = new Bundle[2];
Position target = DataProvider.getInstance().getPosition(position);
if (target != null) {
Bundle symbolBundle = new Bundle();
symbolBundle.putInt(Control.Intents.EXTRA_LAYOUT_REFERENCE, R.id.watch_position_symbol);
symbolBundle.putString(Control.Intents.EXTRA_TEXT, target.getSymbol());
Bundle typeBundle = new Bundle();
typeBundle.putInt(Control.Intents.EXTRA_LAYOUT_REFERENCE, R.id.watch_position_type);
typeBundle.putString(Control.Intents.EXTRA_TEXT, target.getTypeAsString());
result[0] = symbolBundle;
result[1] = typeBundle;
}
return result;
}
}
However, onRequestListItem gets called and createControlListItem returns a correct item list. Touching the display gives me the following result:
onListItemClick [listItem: com.sonyericsson.extras.liveware.extension.util.control.ControlListItem#423b6960, clickType: 0, itemLayoutReference: -1]
The problem is, I do not see any of "added" list items :(
Make sure you also copied the List-related intents from the Manifest.xml:
<action android:name="com.sonyericsson.extras.aef.control.LIST_REFERESH_REQUEST" />
<action android:name="com.sonyericsson.extras.aef.control.LIST_REQUEST_ITEM" />
<action android:name="com.sonyericsson.extras.aef.control.LIST_ITEM_CLICK" />
<action android:name="com.sonyericsson.extras.aef.control.LIST_ITEM_SELECTED" />
Couple questions for you:
What is being shown on the screen? Is it just blank?
Are you calling showLayout() and sendListCount()? I don't see them in the above code. In the sample code in onResume() you should see something like:
showLayout(R.layout.layout_test_list, null);
sendListCount(R.id.listView, mListContent.length);
These need to be called.
Did you make sure that sendListItem(item) is actually being called?
Aren't you adding black text items to layout with black background? :) Please check your layouts.