Duplicate Button in LinearLayout via Fragment - android

I have created a Fragment that uses a Receiver to take in data and present it dynamically (#runtime) on the View. However, everytime the receiver gets new data, the buttons get created and the view is not overriden, but added on with the previous button. The main problem lies within the Fragment class, as I have tested TextViews. Help me find the problem with this Fragment:
public class OneFragment extends Fragment{
SDReceiver sdr;
View v;
TextView tx;
LinearLayout main_layer;
public OneFragment() {}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
v = inflater.inflate(R.layout.fragment_one, container, false);
tx = (TextView) v.findViewById(R.id.result);
main_layer = (LinearLayout) v.findViewById(R.id.dynamic_layout);
setupServiceReceiver();
onStartService();
return v;
}
public void onStartService(){
Intent intent = new Intent(getActivity(),ServiceHandler.class);
intent.putExtra("receiver",sdr);
getActivity().startService(intent);
}
public void setupServiceReceiver() {
// Setup GUI by accessing objects from ArrayList
sdr = new SDReceiver(new Handler());
sdr.setReceiver(new SDReceiver.Receiver() {
#Override
public void onReceiveResult(int resultCode, Bundle resultData) {
if (resultCode == Activity.RESULT_OK) {
try{
HashMap<Integer,String[]> resultValue = (HashMap<Integer,String[]>) resultData.getSerializable("itemList");
for(int i=0;i<resultValue.size();i++){
String data[] = resultValue.get(i);
String resultString = data[1] + ", " + data[2] + ", " + data[3] + ", " + data[4] + "\n";
Button button1 = new Button(v.getContext());
button1.setId(i);
button1.setText(resultString);
//button1.setOnClickListener(getOnClickDoSomething(button1));
main_layer.addView(button1);
//tx.setText(bee);
}
}catch(NullPointerException e){
e.printStackTrace();
}
//tx.setText(values);
}
}
});
}
}

Remove the old Buttons from your LinearLayout before adding the new ones. You can use removeAllViews() method:
main_layer.removeAllViews(); // to remove the old Buttons
for(int i=0;i<resultValue.size();i++){// then you can loop to add the new ones
String data[] = resultValue.get(i);
String resultString = data[1] + ", " + data[2] + ", " + data[3] + ", " + data[4] + "\n";
Button button1 = new Button(v.getContext());
button1.setId(i);
button1.setText(resultString);
main_layer.addView(button1);
}

The answer is, assign a value to a variable does not mean your recreated a view, already drawn on a screen.
First, try to remove already added button by main_layer.removeView(button1) and then create and add a new one

Related

RecyclerView doesn't show data

Its my first time when I'm trying to use RecyclerView. My app do request to get array of documents data. I wrote my own adapter for RecyclerView, TaskAsync class which extend from AsyncTask. And when do request all data which I need, but I don't know why those data doesn't show in my recycler view. pls help. I read many post about recyclerView, but I think in my adapter something goes wrong.
Acts class and into this class I have TaskAsync
public class Acts extends Fragment{
private String direction, limit, existingToken;
private SharedPreferences sharedPreferences;
private ArrayList<Document> documentsList;
private TextView docCategory;
private EditText search;
private RecyclerView recyclerView;
private RecyclerView.LayoutManager layoutManager;
private DocumentAdapter documentAdapter;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, Bundle savedInstanceState) {
View act = inflater.inflate(R.layout.two_sided_docs, container, false);
View header = getActivity().getLayoutInflater().inflate(R.layout.document_list_header, null);
docCategory = (TextView)header.findViewById(R.id.docs_category_one);
search = (EditText)header.findViewById(R.id.search_text_one);
recyclerView = (RecyclerView) act.findViewById(R.id.documentListView2);
documentsList = new ArrayList<Document>();
documentAdapter = new DocumentAdapter(act.getContext(), documentsList, Document.DOCUMENT_TYPE.ACT);
layoutManager = new LinearLayoutManager(act.getContext());
recyclerView.setAdapter(documentAdapter);
recyclerView.setLayoutManager(layoutManager);
sharedPreferences = getContext().getSharedPreferences(Constants.PROJECT, Context.MODE_PRIVATE);
existingToken = sharedPreferences.getString(Constants.TOKEN, "");
direction = "in";
limit = "50";
new TestAsync(getActivity()).execute(Urls.ACTS_FEED);
return act;
}
public class TestAsync extends AsyncTask<String, Void, String> {
private Activity activity;
private ProgressDialog progressDialog;
private OkHttpClient okHttpClient;
private Request request;
private RequestBody formBody;
public TestAsync(Activity activity) {
this.activity = activity;
progressDialog = new ProgressDialog(this.activity);
}
#Override
protected String doInBackground(String... params) {
Log.i("sadasd", "asdasd");
URL url;
try {
url = new URL(params[0]);
okHttpClient = new OkHttpClient();
formBody = new FormBody.Builder()
.add(Constants.DIRECTION, Constants.IN)
.add(Constants.LIMIT, Constants.docs_limit)
.build();
request = new Request.Builder()
.url(url.toString())
.addHeader(Constants.AUTH_TOKEN, existingToken)
.post(formBody)
.build();
Response response = null;
response = okHttpClient.newCall(request).execute();
return response.body().string();
} catch (MalformedURLException e) {
Log.i("test", "test1");
e.printStackTrace();
} catch (IOException e) {
Log.i("test", "test2");
e.printStackTrace();
}
return null;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog.setTitle(R.string.wait);
progressDialog.setMessage("load");
progressDialog.setCancelable(false);
progressDialog.show();
Log.i("test", "test3");
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
Log.i("test", "test4" + s);
AlertView.showAlertView(activity, Messages.CONNECTION_ERROR, s, Messages.OK);
if (progressDialog.isShowing()) {
progressDialog.dismiss();
} else if (s == null) {
Log.i("test", "test5");
AlertView.showAlertView(activity, Messages.CONNECTION_ERROR, Messages.NO_INTERNET, Messages.OK);
} else {
Log.i("test", "test6");
try {
Log.i("test", "test7");
JSONObject jsonObject = new JSONObject(s);
int code = Integer.valueOf(jsonObject.getString(Constants.CODE));
if (code == Codes.OK) {
Log.i("test", "test8");
String header = jsonObject.getString("act_header");
JSONArray arr = new JSONArray(header);
for (int i = 0; i < arr.length(); i++) {
JSONObject jsonPart = arr.getJSONObject(i);
Document document = null;
String docId;
String docNum;
String docTotalPrice;
String senderCompany;
String receiverCompany;
BigInteger timestamp;
String docStatus;
String documentInternalType;
docId = jsonPart.getString("id");
docNum = jsonPart.getString("act_num");
docTotalPrice = jsonPart.getString("total_price");
senderCompany = jsonPart.getString("sender_company_name");
receiverCompany = jsonPart.getString("receiver_company_name");
timestamp = BigInteger.valueOf(Long.valueOf(jsonPart.getString("timestamp")));
docStatus = jsonPart.getString("status");
documentInternalType = jsonPart.getString("documentInternaltyep");
document = new Document(docId, docNum, docTotalPrice, senderCompany, receiverCompany, timestamp, docStatus, documentInternalType);
Log.i("document", document.toString());
documentsList.add(document);
documentAdapter.notifyDataSetChanged();
}
} else {
Log.i("error", "error");
AlertView.showAlertView(activity, Messages.ERROR, jsonObject.getString(Constants.MESSAGE), Messages.OK);
}
} catch (JSONException e) {
AlertView.showAlertView(activity, Messages.CONNECTION_ERROR, Messages.NO_INTERNET, Messages.OK);
e.printStackTrace();
}
}
}
}
}
And this is my DocumentAdapter class:
public class DocumentAdapter extends RecyclerView.Adapter<DocumentAdapter.ViewHolder> {
private Context context;
private ArrayList<Document> docData;
private Document.DOCUMENT_TYPE documentType;
private static LayoutInflater inflater = null;
public static class ViewHolder extends RecyclerView.ViewHolder {
TextView datetime;
TextView senderOrReceiverCompany;
TextView docInfo;
TextView docCost;
ImageView arrow;
TextView docStatus;
ViewHolder(View v) {
super(v);
datetime = (TextView) v.findViewById(R.id.datetime);
senderOrReceiverCompany = (TextView) v.findViewById(R.id.senderc);
docInfo = (TextView) v.findViewById(R.id.docInfo);
docCost = (TextView) v.findViewById(R.id.cost);
arrow = (ImageView) v.findViewById(R.id.arrow_icon);
docStatus = (TextView) v.findViewById(R.id.doc_st_sign);
}
}
public DocumentAdapter(Context context, ArrayList<Document> docData, Document.DOCUMENT_TYPE documentType) {
this.context = context;
this.docData = docData;
this.documentType = documentType;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
Context cn = parent.getContext();
LayoutInflater inf = LayoutInflater.from(context);
View documentView = inf.inflate(R.layout.list_adapter_row, parent, false);
ViewHolder viewHolder = new ViewHolder(documentView);
return viewHolder;
}
#Override
public int getItemCount() {
return docData.size();
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
Document document = docData.get(position);
TextView datetime;
TextView senderOrReceiverCompany;
TextView docInfo;
TextView docCost;
ImageView arrow;
TextView docStatus;
datetime = holder.datetime;
datetime.setText(document.getTimestamp());
senderOrReceiverCompany = holder.senderOrReceiverCompany;
senderOrReceiverCompany.setText(document.getSenderCompany());
docInfo = holder.docInfo;
docInfo.setText(String.format(Constants.ACT_TITLE, document.getDocNum(), document.getTimestamp()));
docCost = holder.docCost;
docStatus = holder.docStatus;
switch (documentType) {
case ACT:
docCost.setText(String.valueOf(Math.round(Double.valueOf(document.getDocTotalPrice()))) + Constants.KZT);
break;
case SHIPPING_LIST:
docCost.setText(String.valueOf(Math.round(Double.valueOf(document.getDocTotalPrice()))) + Constants.KZT);
break;
case COMMON_DOCUMENT:
docCost.setText(" ");
break;
case INVOICE:
docCost.setText(String.valueOf(Math.round(Double.valueOf(document.getDocTotalPrice()))) + Constants.KZT);
String colorful = "";
switch (document.getDocStatus()) {
case "0":
colorful = Constants.DOCUMENT_INVOICE_STATUS.get(document.getDocStatus());
break;
case "1":
colorful = "<font color='#008000'>" + Constants.DOCUMENT_INVOICE_STATUS.get(document.getDocStatus()) + "</font>";
break;
case "2":
colorful = "<font color='#FFA500'>" + Constants.DOCUMENT_INVOICE_STATUS.get(document.getDocStatus()) + "</font>";
break;
case "3":
colorful = "<font color='#EE0000'>" + Constants.DOCUMENT_INVOICE_STATUS.get(document.getDocStatus()) + "</font>";
break;
default:
colorful = "<font color='#EE0000'>" + Constants.DOCUMENT_INVOICE_STATUS.get(document.getDocStatus()) + "</font>";
break;
}
docStatus.setText(Html.fromHtml(Constants.DOCUMENT_INVOICE_TYPE.get(document.getDocumentInternalType()) + " | " + colorful));
break;
case PAYMENT_INVOICE:
docCost.setText(String.valueOf(Math.round(Double.valueOf(document.getDocTotalPrice()))) + Constants.KZT);
break;
case RECON:
docCost.setText(" ");
break;
default:
docCost.setText(document.getDocTotalPrice());
break;
}
if (!documentType.equals(Document.DOCUMENT_TYPE.INVOICE)) {
switch (document.getDocStatus()) {
case "1":
docStatus.setText(Html.fromHtml(Constants.DOCUMENT_INTERNAL_TYPE.get(document.getDocumentInternalType()) + " | " + "<font color='#800080'>" + Constants.DOCUMENT_STATUS.get(document.getDocStatus()) + "</font>"));
break;
case "2":
docStatus.setText(Html.fromHtml(Constants.DOCUMENT_INTERNAL_TYPE.get(document.getDocumentInternalType()) + " | " + "<font color='#800080'>" + Constants.DOCUMENT_STATUS.get(document.getDocStatus()) + "</font>"));
break;
case "3":
docStatus.setText(Html.fromHtml(Constants.DOCUMENT_INTERNAL_TYPE.get(document.getDocumentInternalType()) + " | " + "<font color='#FFA500'>" + Constants.DOCUMENT_STATUS.get(document.getDocStatus()) + "</font>"));
break;
case "4":
docStatus.setText(Html.fromHtml(Constants.DOCUMENT_INTERNAL_TYPE.get(document.getDocumentInternalType()) + " | " + "<font color='#008000'>" + Constants.DOCUMENT_STATUS.get(document.getDocStatus()) + "</font>"));
break;
case "6":
docStatus.setText(Html.fromHtml(Constants.DOCUMENT_INTERNAL_TYPE.get(document.getDocumentInternalType()) + " | " + "<font color='#EE0000'>" + Constants.DOCUMENT_STATUS.get(document.getDocStatus()) + "</font>"));
break;
case "7":
docStatus.setText(Html.fromHtml(Constants.DOCUMENT_INTERNAL_TYPE.get(document.getDocumentInternalType()) + " | " + "<font color='#EE0000'>" + Constants.DOCUMENT_STATUS.get(document.getDocStatus()) + "</font>"));
break;
default:
docStatus.setText(Html.fromHtml(Constants.DOCUMENT_INTERNAL_TYPE.get(document.getDocumentInternalType()) + " | " + "<font color='#800080'>" + Constants.DOCUMENT_STATUS.get(document.getDocStatus()) + "</font>"));
break;
}
}
arrow = holder.arrow;
}
private Context getContext() {
return context;
}
}
And this is my layout:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<android.support.v7.widget.RecyclerView
android:id="#+id/documentListView2"
android:scrollbars="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</FrameLayout>
UPDATE
this what I got after request:
test: test4{"code": 0, "act_header": [{"status": 1, "sender_company_name": "\u0422\u041e\u041e\"\u0410\u0441\u0435\u043c-2\"", "receiver_company_name": "\u0422\u041e\u041e\"\u0410\u0441\u0435\u043c-2\"", "total_price": "1.000000", "create_date": "10.05.2017", "descri...
and after Log.i("test", "test4" + s) nothing shows into android monitoring
I don't know why my data doesn't record
Pass getActivity() as your Context in all the Fragment class. Try changing it like the following code.
This line:
documentAdapter = new DocumentAdapter(getActivity(), documentsList, Document.DOCUMENT_TYPE.ACT);
This line:
layoutManager = new LinearLayoutManager(getActivity());
And this line:
sharedPreferences = getActivity().getSharedPreferences(Constants.PROJECT, Context.MODE_PRIVATE);
I think the problem is with this line
documentAdapter = new DocumentAdapter(act.getContext(), documentsList, Document.DOCUMENT_TYPE.ACT);
Here, you are passing empty list which does not have any data. And in Adapter in getItemCount() method, you will get size as 0. so there is no data to display.
Try this.
In onPostExecute() method, after for loop where you parse your data call this line.
documentAdapter = new DocumentAdapter(act.getContext(), documentsList, Document.DOCUMENT_TYPE.ACT);
documentAdapter.notifyDataSetChanged();
May be this will solve your issue.
In my case a problem was in assigning RecyclerView's adapter to itself.
private lateinit var adapter: MyAdapter
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
val view = inflater.inflate(R.layout.recycler_view_layout, container, false)
val layoutManager = LinearLayoutManager(context)
adapter = MyAdapter(listOf(MyAdapter.Item(1, "dfg")))
view.recycler_view.apply {
this.layoutManager = layoutManager
this.adapter = adapter
this.setHasFixedSize(true)
}
return view
}
After many hours I removed apply operator and understood that compiler recognized layoutManager as local variable, while adapter was recognized as recycler_view.adapter.

ANDROID - Save multiple images in database

I have an app in which I have to combine parts of clothes. To understand me better I have given a screenshot below. The thing is, that i am having problems on how to get these images and save them in my database. Of course i faced errors.
public class ViewOutfit extends Activity {
private DatabaseHandler handler;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.view_outfit);
Intent i = getIntent();
final ImageView im1 = (ImageView) findViewById(R.id.im1);
im1.setImageBitmap(BitmapFactory.decodeFile(i.getStringExtra("image1")));
im1.toString();
final ImageView im2 = (ImageView) findViewById(R.id.im2);
im2.setImageBitmap(BitmapFactory.decodeFile(i.getStringExtra("image2")));
im2.toString();
final ImageView im3 = (ImageView)findViewById(R.id.im3);
im3.setImageBitmap(BitmapFactory.decodeFile(i.getStringExtra("image3")));
im3.toString();
final ImageView im4 = (ImageView)findViewById(R.id.im4);
im4.setImageBitmap(BitmapFactory.decodeFile(i.getStringExtra("image4")));
im4.toString();
final ImageView im5 = (ImageView)findViewById(R.id.im5);
im5.setImageBitmap(BitmapFactory.decodeFile(i.getStringExtra("image5")));
im5.toString();
final ImageView im6 = (ImageView)findViewById(R.id.im6);
im6.setImageBitmap(BitmapFactory.decodeFile(i.getStringExtra("image6")));
im6.toString();
ImageButton btn_save_outfit = (ImageButton)findViewById(R.id.btn_combine);
btn_save_outfit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
im1.getDrawable().toString();
im2.getDrawable().toString();
im3.getDrawable().toString();
im4.getDrawable().toString();
im5.getDrawable().toString();
im6.getDrawable().toString();
Outfits outfits = new Outfits();
outfits.setImage1(String.valueOf(im1));
outfits.setImage2(String.valueOf(im2));
outfits.setImage3(String.valueOf(im3));
outfits.setImage4(String.valueOf(im4));
outfits.setImage5(String.valueOf(im5));
outfits.setImage6(String.valueOf(im6));
Boolean added = handler.addOutfit(outfits);
if(added){
Toast.makeText(getApplicationContext() , "Outfit added." , Toast.LENGTH_LONG).show();
String log = "Id: "+ outfits.getID()+" ,Image1: " + outfits.getImage1() + " ,Image2: " + outfits.getImage2()
+ ",Image3:" + outfits.getImage3() + ",Image4:" + outfits.getImage5() + ",Image6:" +outfits.getImage6();
Log.d("Image1: ", log);
}else{
Toast.makeText(getApplicationContext(), "Outfit not added. Please try again", Toast.LENGTH_LONG).show();
}
}});
}

Android show image from camera horizontal scroll view listview

I want to show image from camera in HorizontalScrollView Images.
Currently, In each item of List View HorizontalScrollView is added and each
HorizontalScrollView displayes the images dynamically on the basis of data fetched from the sqlite. Sqlite is preloaded with the data that is downloaded from our application server.
Also, In each list item 'Camera' button is added. On click event of this button .I am adding images captured from Camera to the existing HorizontalScrollView.
I am adding some code snippet from my application -
1) First I'm trying to show images dynamically in HorizontalScrollView from sqlite in ArrayAdapter -
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
View row = convertView;
final Holder holder;
if (row == null)
{
LayoutInflater vi;
vi = LayoutInflater.from(getContext());
row = vi.inflate(R.layout.all_post_row, null);
holder = new Holder();
holder.horizontalScrollView = (HorizontalScrollView)row.findViewById(R.id.hlist);
holder.lLinearLayout=(LinearLayout)row.findViewById(R.id.innerlay);
row.setTag(holder);
}
else
{
holder = (Holder) row.getTag();
}
final All_Post all_Post = data.get(position);
String strListItem_ActivityId = all_Post.getStrActivityId();
Log.e("strListItem_ActivityId ", " = " + strListItem_ActivityId);
dbhelper = new MyDbHelper(AllPosts_Page.this);
SQLiteDatabase db = dbhelper.getReadableDatabase();
Cursor cursor = db.rawQuery("select * from ActivityObjectList where activityId " + "= ? ", new String[]{strListItem_ActivityId});
imageArray.clear();
if (cursor.moveToFirst())
{
do
{
String imagePath = cursor.getString(cursor.getColumnIndex("imageaudioPath"));
Log.e("imagePath ", " = " + imagePath);
imageArray.add(imagePath);
}
while (cursor.moveToNext());
}
cursor.close();
db.close();
holder.lLinearLayout.removeAllViews();
final Iterator<String> it = imageArray.iterator();
while (it.hasNext())
{
final String imgElement = it.next();
int imgArraySize = imageArray.size();
Log.e("imgArraySize "," = " + imgArraySize);
final ImageView imageView = new ImageView (getContext());
final ProgressBar pBar = new ProgressBar(getContext(),null ,android.R.attr.progressBarStyleSmall);
imageView.setTag(it);
pBar.setTag(it);
imageView.setImageResource(R.drawable.img_placeholder);
pBar.setVisibility(View.VISIBLE);
Uri uri = Uri.fromFile(new File(path));
Picasso.with(getContext()).load(uri).placeholder(R.drawable.img_placeholder).resize(newWidth,fixHeight).into(imageView, new com.squareup.picasso.Callback() {
#Override
public void onSuccess() {
if (pBar != null) {
pBar.setVisibility(View.GONE);
}
}
#Override
public void onError() {
}
});
holder.lLinearLayout.addView(imageView);
holder.lLinearLayout.addView(pBar);
}
2) 2) Here is my Camera button click event in ArrayAdapter class -
holder.imgBtn_Camera.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
Toast.makeText(context, "Camera" + " = ", Toast.LENGTH_SHORT).show();
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_PIC_REQUEST);
}
});
3) Here is onActivityResult method implementation which is in Activity class -
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == CAMERA_PIC_REQUEST)
{
activityObj_Id++;
intoString = Integer.toString(activityObj_Id);
SimpleDateFormat s = new SimpleDateFormat("ddMMyyyyhhmmss");
String dateformat = s.format(new Date());
Log.e("format", " and activityObj_Id = " + dateformat + " & " + activityObj_Id);
imageCamera_Path = activityObj_Id +"_"+ dateformat+".png";
downloadstatus = "1";
Log.e("imageCamera_Path", "= " + imageCamera_Path);
Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
//imageView.setImageBitmap(thumbnail);
}
Log.e("Data Save","in onActivityResult Succesfully !!!!");
}
The above code should show the images captured from camera into HorizontalScrollView. However, images are not getting added to scroll view. I am not able to understand where does it went wrong ? I have tried to modify code in many ways. However it did not help.
Please take look at my code snippets and let me know if anything is missing.
Thanks.

No items on ListControl

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.

Android: Randomly picking strings from an array

I'm trying to randomly pick a string from an array and spit it out to the user, but whenever I try to run it via AVD the app crashes. I'm very much a novice at this, and can't figure out what to do.
Here is my code:
public class MainActivity extends Activity {
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final LinearLayout rr = new LinearLayout (this);
// setting up the LinearLayout. I'll get to proper formatting one I get the code running.
Button b1 = new Button (this);
b1.setId(R.id.Button01);
b1.setText("Generate");
rr.addView(b1);
final TextView tv;
tv = new TextView(this);
tv.setId(R.id.Text1);
rr.addView(tv);
setContentView(rr);
final String [] columnA = { "artless", "bawdy", "beslubbering", "bootless", "churlish", "cockered", "clouted", "craven", "currish", "dankish", "dissembling", "droning", "errant", "fawning", "fobbing", "froward", "frothy", "gleeking", "goatish", "gorbellied", "impertinent", "infectious", "jarring", "loggerheaded", "lumpish", "mammering", "mangled", "mewling", "paunchy", "pribbling", "puking", "puny", "qualling", "rank", "reeky", "roguish", "ruttish", "saucy", "spleeny", "spongy", "surly", "tottering", "unmuzzled", "vain", "venomed", "villainous", "warped", "wayward", "weedy", "yeasty" };
final String [] columnB = { "base-court", "bat-fowling", "beef-witted", "beetle-headed", "boil-brained", "clapper-clawed", "clay-brained", "common-kissing", "crook-patted", "dismal-dreaming", "dizzy-eyed", "doghearted", "dread-boiled", "earth-vexing", "elf-skinned", "fat-kidneyed", "fen-sucked", "flap-mouthed", "fly-bitten", "folly-fallen", "fool-born", "full-gorged", "guts-gripping", "hasty-witted", "half-faced", "hell-hated", "idle-headed", "ill-breeding", "ill-nurtured", "knotty-pated", "milk-livered", "motley-minded", "onion-eyed", "plume-plucked", "pottle-deep", "pox-marked", "reeling-riped", "rough-hewn", "rude-growing", "rump-fed", "shard-borne", "sheep-biting", "spur-galled", "swag-bellied", "tardy-gaited", "tickle-brained", "toad-spotted", "unchin-snouted", "weather-bitten"};
final String [] columnC = { "apple-john", "baggage", "barnacle", "bladder", "boar-pig", "bugbear", "bum-bailey", "canker-blossom", "clack-dish", "clotpole", "coxcomb", "codpiece", "death-token", "dewberry", "flap-dragon", "flax-wench", "flirt-gill", "foot-licker", "fustilarian", "giglet", "gudgeon", "haggard", "harpy", "hedge-pig", "horn-beast", "hugger-mugger", "joithead", "lewdster", "lout", "maggot-pie", "malt-worm", "mammet", "measle", "minnow", "miscreant", "moldwarp", "mumble-news", "nut-hook", "pigeon-egg", "pignut", "puttock", "pumpion", "ratsbane", "scut", "skainsmate", "strumpet", "varlot", "vassal", "whey-face", "wagtail"};
//Attempts to pick one string from each array, add "thou art a" and spaces, and display it to the device.
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String outputA;
Random r;
r = new Random(columnA.length);
Random s;
s = new Random(columnB.length);
Random t;
t = new Random(columnC.length);
outputA = "Thou art a" + " " + columnA[r.nextInt() % columnA.length] + " " + columnB[s.nextInt() % columnB.length] + " " + columnC[t.nextInt() % columnC.length];
tv.setText(outputA);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
I imagine you were getting an ArrayIndexOutOfBoundsException
To solve, remove all the Randoms and change your onClickListener to:
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String outputA = "Thou art a" + " " + columnA[(int) (Math.random() * columnA.length)] + " " + columnB[(int) (Math.random() * columnB.length)] + " " + columnC[(int) (Math.random() * columnC.length)];
tv.setText(outputA);
}
});

Categories

Resources