How to get tablerow id dynamically in android? - android

Hello, my old code is working, but the problem is that when i am clicking tablerow it call another activty, but it not set that table row data but it setting last array data to that activity.
Means it set the last array value to next screen activity.
for ( j = 0; j < dataListfeture.size(); j++)
{
HashMap<String, String> hm = new HashMap<String, String>();
hm = dataListfeture.get(j);
final TableRow tblrow = new TableRow(MainScreen.this);
final View rowView = inflater.inflate(R.layout.featuredrow, null);
tblrow.setId(j);
tblrow.getId();
featuredName = (TextView) rowView.findViewById(R.id.xxName);
featuredDistance = (TextView) rowView.findViewById(R.id.xxDistance);
featuredVeneType = (TextView) rowView.findViewById(R.id.xxVeneType);
featuredPhone = (TextView) rowView.findViewById(R.id.xxPhone);
featuredAddress = (TextView) rowView.findViewById(R.id.xxAddress);
Drawable image = ImageOperations(MainScreen.this, hm.get("url"), "image.jpg");
featuredImage = (ImageView) rowView.findViewById(R.id.xxdImage);
featuredImage.setImageDrawable(image);
featuredName.setText("" + hm.get("name"));
featuredDistance.setText("" + hm.get("distance") + " mi");
featuredVeneType.setText("" + hm.get("venuetype"));
featuredPhone.setText("" + hm.get("phonenumber"));
featuredAddress.setText("" + hm.get("address"));
mapnamelist = hm.get("name");
mapvenuelist = hm.get("venuetype");
mapothervenuelist = hm.get("othervenuetype");
mapaddresslist= hm.get("address");
mapcitylist= hm.get("city");
mapstatelist= hm.get("state");
tblrow.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
final ProgressDialog progDailog = ProgressDialog.show(MainScreen.this, null, "Loading ....", true);
final Handler handler = new Handler()
{
public void handleMessage(Message msg)
{
System.out.println("search");
Intent myIntent = new Intent(MainScreen.this, xxxxscreen.class);
startActivity(myIntent);
MainScreen.this.finish();
progDailog.dismiss();
}
};
new Thread()
{
public void run()
{
try
{
System.out.println();
handler.sendEmptyMessage(1);
}
catch (Exception e)
{
e.printStackTrace();
}
}
}.start();
}
});

Create an int array of id say array_id[] and after setting id to table row add that id to array_id[] also like
tblrow.setId(j);
array_id[j] = j;
And in onClick method do this:
for(int i = 0;i< array_id.length;i++)
{
TableRow tbl_row = (TableRow) findViewById(i);
if(v.getId() == array_id[i])
{
/** Perform your Operations */
}
}

Related

Adding TextView dynamically under the relativeLayout

enter image description herehow can i add multiple TextView and their inside relative layout dynamically which is already created? Also I have to call the values of those text boxes from database sqlite.
public class DownloadPackagesActivity extends Activity implements AdapterView.OnItemSelectedListener{
private SQLiteDatabase db;
DBHelper dbHelper;
String newFolder = "";
int SId = 1;
TextView subjects;
List<String> categories = new ArrayList<String>();
String FilePart = "";
DownloadManager dManager;
long did;
// private static String file_url = "http://mobileteacher.in/audio/demo/2725.mp3";
String urlString ="";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_download_packages);
// Get DownloadManager instance
dManager = (DownloadManager) this.getSystemService(Context.DOWNLOAD_SERVICE);
subjects = (TextView)findViewById(R.id.subjects);
// Spinner element
Spinner spinner = (Spinner) findViewById(R.id.spinnerPackage);
// Spinner click listener
spinner.setOnItemSelectedListener(this);
// Add textview
dbHelper = new DBHelper(this);
try{
dbHelper.createDataBase();
}
catch(Exception ex)
{
ex.printStackTrace();
}
String myPath = dbHelper.DB_PATH + DBHelper.DB_NAME;
db = SQLiteDatabase.openDatabase(myPath, null,
SQLiteDatabase.OPEN_READWRITE);
Cursor c = db.rawQuery("select * from DownloadSubject", null);
while (c.moveToNext()) {
categories.add(c.getString(1));
}
ArrayAdapter<String> dataAdapter1 = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_single_choice, categories);
dataAdapter1.setDropDownViewResource(android.R.layout.simple_list_item_single_choice);
spinner.setAdapter(dataAdapter1);
showPart();
}
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id)
{
SId = position + 1;
showPart();
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
public void showPart()
{
int j=1;
int ii=0;
dbHelper = new DBHelper(this);
try{
dbHelper.createDataBase();
}
catch(Exception ex)
{
ex.printStackTrace();
}
TableLayout stk = (TableLayout) findViewById(R.id.tbl);
stk.removeAllViews();
String myPath = dbHelper.DB_PATH + DBHelper.DB_NAME;
db = SQLiteDatabase.openDatabase(myPath, null,
SQLiteDatabase.OPEN_READWRITE);
Cursor c;
if (SId==8 || SId==9)
{
c = db.rawQuery("select * from DownloadSubject", null);
}
else
{
c = db.rawQuery("select * from DownloadSubject where Id = '"+ SId +"'", null);
}
while (c.moveToNext())
{
subjects.clearComposingText();
String[] part = c.getString(2).split(",");
for(int i = 0;i<part.length;i++)
{
TableRow tr1 = new TableRow(this);
Button button = new Button(this);
button.setBackgroundColor(Color.TRANSPARENT);
button.setText(part[i] +"\u00A0 \u00A0 \u00A0 \u00A0 Download");
button.setTextColor(Color.BLUE);
button.setPadding(20, 0, 0, 0);
button.setOnClickListener(downloads());
button.setId(i);
// button.setHint(part[i]);
tr1.addView(button);
stk.addView(tr1);
}
stk = (TableLayout) findViewById(R.id.tbl);
int N = 1;
TextView[] TextViews = new TextView[N]; // create an empty array;
// for (int i = 0; i < N; i++) {
//if(ii!=0) {
// subjects.setText(c.getString(j));
// Toast.makeText(this, c.getString(j), Toast.LENGTH_LONG).show();
// save a reference to the textview for later
// TextViews[j] = TextView;
//}
if(ii==0)
{
subjects.setText(c.getString(j));
ii=ii+1;
}
else
{
final TextView TextView = new TextView(this);
TextView.setText(c.getString(j));
TextView.setLayoutParams(new TableLayout.LayoutParams(TableLayout.LayoutParams.WRAP_CONTENT,
TableLayout.LayoutParams.WRAP_CONTENT));
TextView.setPadding(0, 20, 0, 20);
TextView.setTextSize(getResources().getDimension(R.dimen.textsize));
TextView.setTextColor(Color.parseColor("#800080"));
// add the textview to the layout
stk.addView(TextView);
}
}
}
public String part;
View.OnClickListener downloads()
{
return new View.OnClickListener()
{
public void onClick(View v) {
//Button b1 = (Button)v;
//int i = b1.getId();
// Toast.makeText(getApplicationContext(),"Ide = " + i,Toast.LENGTH_LONG).show();
part ="";
TextView subjects = (TextView)findViewById(R.id.subjects);
if(subjects.getText().toString().equals("Modern History (500 MB)"))
{
part = "modern_history";
}
else if(subjects.getText().toString().equals("Polity (250 MB)"))
{
part = "polity";
}
else if(subjects.getText().toString().equals("Economy (100 MB)"))
{
part = "economy";
}
else if(subjects.getText().toString().equals("Ancient History (500 MB)"))
{
part = "ancient_history";
}
else if(subjects.getText().toString().equals("English Grammar (500 MB)"))
{
part = "english_grammar";
}
else if(subjects.getText().toString().equals("Vocabulary (560 MB)"))
{
part = "vocabulary";
}
else if(subjects.getText().toString().equals("Maths (100 MB)"))
{
part = "maths";
}
else if(subjects.getText().toString().equals("One Day Complete(Vol.1(2GB))"))
{
part = "oneday_complete";
}
else if(subjects.getText().toString().equals("Civil Complete (Vol.1 (2GB))"))
{
part = "civil_complete" ;
}
newFolder = "/voice";
subjects = (TextView)findViewById(R.id.subjects);
String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
File myNewFolder = new File(extStorageDirectory + newFolder);
//File f = new File(myNewFolder);
myNewFolder.mkdir();
Button b = (Button)v;
FilePart = b.getText().toString();
String RemoveSpace = FilePart.split("\u00A0")[0].replace(" ","");
try {
urlString = "http://mobileteacher.in/DealerPackage/" + part + "/" + RemoveSpace + ".zip";
downloadFile();
Toast.makeText(getApplicationContext(), "Download Started", Toast.LENGTH_LONG).show();
}
catch(Exception e)
{
Toast.makeText(getApplicationContext(), "Please Connect Internet", Toast.LENGTH_LONG).show();
}
}
};
}
public void downloadFile() {
// String urlString = "http://mobileteacher.in/audio/demo/2725.mp3";
if (!urlString.equals("")) {
try {
// Get file name from the url
String fileName = urlString.substring(urlString.lastIndexOf("/") + 1);
// Create Download Request object
DownloadManager.Request request = new DownloadManager.Request(Uri.parse((urlString)));
// Display download progress and status message in notification bar
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
// Set description to display in notification
// request.setDescription("Download " + fileName + " from " + urlString);
request.setDescription("Download " + fileName + " from mobileteacher.in");
// Set title
request.setTitle("Mobile Teacher");
// Set destination location for the downloaded file
request.setDestinationUri(Uri.parse("file://" + Environment.getExternalStorageDirectory() + "/voice/"+fileName.split("\u00A0")[0].replace(" ","")));
// Download the file if the Download manager is ready
did = dManager.enqueue(request);
} catch (Exception e) {
}
}
}
// BroadcastReceiver to receive intent broadcast by DownloadManager
private BroadcastReceiver downloadReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context arg0, Intent arg1) {
// TODO Auto-generated method stub
DownloadManager.Query q = new DownloadManager.Query();
q.setFilterById(did);
Cursor cursor = dManager.query(q);
if (cursor.moveToFirst()) {
String message = "";
int status = cursor.getInt(cursor.getColumnIndex(DownloadManager.COLUMN_STATUS));
if (status == DownloadManager.STATUS_SUCCESSFUL) {
message = "Download successful";
} else if (status == DownloadManager.STATUS_FAILED) {
message = "Download failed";
}
//query.setText(message);
}
}
};
protected void onResume() {
super.onResume();
// Register the receiver to receive an intent when download complete
IntentFilter intentFilter = new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE);
registerReceiver(downloadReceiver, intentFilter);
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
// Unregister the receiver
unregisterReceiver(downloadReceiver);
}
#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_download_packages, 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);
}
public void back(View view)
{
finish();
}
public void Create(View view)
{
String newFolder = "/voice";
String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
File myNewFolder = new File(ext[enter image description here][1]StorageDirectory + newFolder);
myNewFolder.mkdir();
}
}
this is the image
create relative layout object from it layout id, then you can add it as below
relativeLayout = findViewById(R.id.yourRelativeLayoutId);
relativeLayout.addView(yourView);
Listview or recyclerview is best for practice but as you want to use textview, you can use like this in your code:
RelativeLayout relativeLayout =
(RelativeLayout) findViewById(R.id.rootlayout);
TextView textView = new TextView(this);
textView.setText("Hey, I am TextView");
relativeLayout.addView(textView);
appending a textview to relativelayout is pretty simple.
just use
TextView textview = new TextView(this);
textview.setText("Text");
relativelayoutobject.addView(textview);
to setup the position use
textview.setLayoutParams(thelayoutparams)
But if you use big database, please, use 'TableLayout' instead of your method due to performance reasons.
Define relative layout in your xml layout. Add multiple textview programmatic ally like this-
RelativeLayout relativeLayout = (RelativeLayout) findViewById(R.id.relativeLayout);
//use a for loop to define multiple textView in RelativeLayout
//length is no. of textView you required
for (int i = 0; i < length; i++) {
TextView tv = new TextView(relativeLayout.getContext());
tv.setText("Text from sqlite database");
tv.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
relativeLayout.addView(tv);
}

Trying to set the marker on the current position gives me nullpointer exception

I have done the following things in my program:
I am generating some Buttons programmatically in my MenuItemsActivity class. I have a Listview in the xml of the MenuItemsActivity class.
When I click on the button the appropriate contents get loaded in the Listview. I just refresh the activity i.e I am using the same Listview to load different contents based on the button which is clicked.
I want to do the following:
When the Button is clicked I want to change the background of the button to 'blue_tab` and maintain that same color when the same activity reloads. Can anyone guide me step by step what to do, as I am a newbie to Android.
i = getIntent();
String Salad=i.getStringExtra("Salad");
String cat_name_from_fragment=i.getStringExtra("category name");
final ListView salad_list = (ListView) findViewById(R.id.salads);
category = new ArrayList<HashMap<String, String>>();
items = new ArrayList<HashMap<String, String>>();
db = new DbHelper(MenuItemsActivity.this);
category.clear();
if (i.getStringExtra("category name") != null) {
String getcategory = i.getStringExtra("category name").toString();
items = db.retrieve_item_details(getcategory);
Log.i("sub items", "" + items);
}
else if(cat_name_from_fragment!=null)
{
items = db.retrieve_item_details(cat_name_from_fragment);
}
else
{
items = db.retrieve_item_details("Salads");
}
category = db.retrieve_category_name();
count = category.size();
Log.i("Sqlite database values", "" + count + " " + category);
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
}
LinearLayout l1 = (LinearLayout) findViewById(R.id.tableRow1);
int i = 0;
for (HashMap<String, String> map : category)
for (Entry<String, String> mapEntry : map.entrySet()) {
String key = mapEntry.getKey();
String value = mapEntry.getValue();
TextView tv2 = new TextView(this);
tv2.setLayoutParams(new LinearLayout.LayoutParams(40, 90));
Log.i("map", "" + value);
final Button tv1 = new Button(this);
tv1.setId(i);
tv1.setText(value);
tv1.setTextSize(35);
tv1.setTextColor(Color.parseColor("#1569C7"));
tv1.setGravity(Gravity.CENTER);
tv1.setBackgroundDrawable(getResources().getDrawable(R.drawable.popup));
tv1.setLayoutParams(new LinearLayout.LayoutParams(300,90));
tv1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String text = tv1.getText().toString();
Log.e("text message", "" + text);
tv1.setBackgroundDrawable(getResources().getDrawable(R.drawable.blue_tab));
Toast.makeText(MenuItemsActivity.this, "clicked", 1000)
.show();
Intent i = new Intent(MenuItemsActivity.this,
MenuItemsActivity.class);
i.putExtra("category name", "" + text);
finish();
startActivity(i);
}
});
/*TextView tv2 = new TextView(this);
tv2.setText(" ");
tv2.setTextSize(10);
tv2.setGravity(Gravity.CENTER);*/
l1.addView(tv1);
l1.addView(tv2);
i++;
Log.e("i count ", "" + i);
}
final int imageArra[] = { R.drawable.leftbar_logo ,R.drawable.leftbar_logo};
ListAdapter k = new SimpleAdapter(MenuItemsActivity.this, items,
R.layout.menulist, new String[] { "Item_Name", "Desc",
"Currency", "Price","url","veggie","cat" }, new int[] { R.id.cat_name,
R.id.textView1, R.id.textView2, R.id.textView3,R.id.url,R.id.veggie,R.id.Category}) {
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
final View v = super.getView(position, convertView, parent);
final ImageView im=(ImageView)v.findViewById(R.id.imageView1);
TextView url=(TextView)v.findViewById(R.id.url);
TextView veg=(TextView)v.findViewById(R.id.veggie);
String vegg=veg.getText().toString();
ImageView imagevegs=(ImageView)v.findViewById(R.id.veggies);
Log.i("veggie",""+vegg);
if(vegg.compareToIgnoreCase("Veg")==0)
{
imagevegs.setImageResource(R.drawable.veg);
imagevegs.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
}
else
{imagevegs.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
imagevegs.setImageResource(R.drawable.non);
}
final String urls="http://166.62.17.208/"+url.getText().toString();
Log.i("urls",""+urls);
imageLoader.DisplayImage(urls,im);
//return super.getView(position, convertView, parent);
return v;
}
};
salad_list.setAdapter(k);
You can use PreferenceManager to save data and use it when the app is reloaded/restarted
sample:
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
String text = tv1.getText().toString();
Log.e("text message", "" + text);
if(PreferenceManager.getDefaultSharedPreferences(MenuItemsActivity.this).getString("button", "").length != 0)
tv1.setBackgroundDrawable(getResources().getDrawable(R.drawable.blue_tab));
else
{
Editor editor = PreferenceManager.getDefaultSharedPreferences(MenuItemsActivity.this).edit();
editor.putString("button", "1");
editor.commit();
tv1.setBackgroundDrawable(getResources().getDrawable(R.drawable.blue_tab));
}
Toast.makeText(MenuItemsActivity.this, "clicked", 1000)
.show();
Intent i = new Intent(MenuItemsActivity.this,
MenuItemsActivity.class);
i.putExtra("category name", "" + text);
finish();
startActivity(i);
}

java.lang.NumberFormatException: unable to parse '' as integer

i want to set the calculation result in TextView named total[] from the value of EditText named point[] .but i am able to parse the value and put it in the TextView . it give me an error in logcat
06-27 02:27:01.467: E/AndroidRuntime(275): Caused by: java.lang.NumberFormatException: unable to parse '' as integer
this is an error in logcat. i want to add integer values to the textview continuously from the edittext on the same layout
public class player_name extends Activity {
LinearLayout player_name;
TableLayout ply_name;
Bundle b,b1;
List<TextView> allEds = new ArrayList<TextView>();
List<Button> allplus = new ArrayList<Button>();
List<Button> allminus = new ArrayList<Button>();
List<EditText> alledit = new ArrayList<EditText>();
List<TextView> alltotal = new ArrayList<TextView>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.player_name);
b1 = getIntent().getExtras();
String[] result = b1.getStringArray("playerName");
player_name = (LinearLayout) findViewById(R.id.player_name);
ply_name = new TableLayout(this);
player_name.addView(ply_name);
TableLayout.LayoutParams tableRowParams=new TableLayout.LayoutParams
(TableLayout.LayoutParams.MATCH_PARENT,TableLayout.LayoutParams.MATCH_PARENT,1.0f);
TextView[] ed1 = new TextView[result.length+1];
Button[] plus = new Button[result.length+1];
Button[] minus = new Button[result.length+1];
EditText[] point = new EditText[result.length+1];
TextView[] total = new TextView[result.length+1];
TableRow[] TR= new TableRow[result.length+1];
int[] totalscore = null;
String[] temp = null;
Button btnResult = new Button(player_name.this);
btnResult.setText(" click here to get RESULT");
for(int i=0;i<=(result.length-1);i++) {
ed1[i] = new TextView(player_name.this);
plus[i] = new Button(player_name.this);
minus[i] = new Button(player_name.this);
point[i] = new EditText(player_name.this);
total[i] = new TextView(player_name.this);
TR[i] = new TableRow(player_name.this);
allEds.add(ed1[i]);
alltotal.add(total[i]);
alledit.add(point[i]);
allplus.add(plus[i]);
allminus.add(minus[i]);
TR[i].addView(ed1[i]);
TR[i].addView(point[i]);
TR[i].addView(plus[i]);
TR[i].addView(minus[i]);
TR[i].addView(total[i]);
ply_name.addView(TR[i]);
TR[i].setLayoutParams(tableRowParams);
totalscore[i] =Integer.parseInt(point[i].getText().toString());
temp[i] = "" + totalscore[i];
ed1[i].setId(i);
ed1[i].setHeight(50);
ed1[i].setWidth(70);
ed1[i].setText(result[i]);
ed1[i].setTextColor(Color.CYAN);
total[i].setId(i);
total[i].setHeight(50);
total[i].setWidth(70);
total[i].setText(""+0);
total[i].setTextColor(Color.CYAN);
point[i].setId(i);
point[i].setHeight(50);
point[i].setWidth(120);
point[i].setHint(result[i]+"\'s");
point[i].setInputType(InputType.TYPE_CLASS_NUMBER);
point[i].setTextColor(Color.BLACK);
plus[i].setId(i);
plus[i].setHeight(50);
plus[i].setWidth(50);
plus[i].setText("+");
plus[i].setTextColor(Color.BLACK);
minus[i].setId(i);
minus[i].setHeight(50);
minus[i].setWidth(50);
minus[i].setText("-");
minus[i].setTextColor(Color.BLACK);
plus[i].setOnClickListener(new OnClickListener() {
public void onClick(View v) {
}
});
minus[i].setOnClickListener(new OnClickListener() {
public void onClick(View v) {
}
});
}
LayoutParams lp = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
player_name.addView(btnResult, lp);
btnResult.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent intent1 = new Intent(player_name.this,result.class);
startActivity(intent1);
}
});
}
}
You need to check whether the string you are parsing is an integer. Try this code:
if (IsInteger(point[i].getText().toString()))
totalscore[i] =Integer.parseInt(point[i].getText().toString());
and add this function:
public static boolean IsInteger(String s)
{
if (s == null || s.length() == 0) return false;
for(int i = 0; i < s.length(); i++)
{
if (Character.digit(s.charAt(i), 10) < 0)
return false;
}
return true;
}
I hope this helps

Updating a listview from a HTTP request

I am trying to display a list of items I am getting from a mysql database on a webserver. Here is my create for the page.
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.getlist);
showBusyDialog();
new GetData()
.execute(picdetails);
}
Here is my GetData class. The problem here is with the lines that are adding items to the listview. I am passing a JSON array as a text result.
public class GetData extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... pic) {
// You might be tempted to display the busy dialog here, but you
// CAN'T update the UI from this method!
return loadImageFromNetwork(pic[0]);
}
#Override
protected void onPostExecute(String result) {
// Our long-running process is done, and we can safely access the UI thread
int ct_id;
String item_make;
String item_model;
String item_price;
String item_desc;
String item_location;
String item_image;
dismissBusyDialog();
TableLayout tl = (TableLayout)findViewById(R.id.myTableLayout1);
try{
JSONArray jArray = new JSONArray(result);
JSONObject json_data=null;
for(int i=0;i<jArray.length();i++){
json_data = jArray.getJSONObject(i);
ct_id=json_data.getInt("id");
item_make=json_data.getString("make");
item_model=json_data.getString("model");
item_price = json_data.getString("price");
item_desc = json_data.getString("cardesc");
item_location = json_data.getString("location");
item_image = json_data.getString("image");
String image_URL = "http://www.myurl.com/images/" + car_image;
TableRow tr = new TableRow(null);
tr.setId(ct_id);
tr.setClickable(true);
tr.setOnClickListener(new OnClickListener() {
#Override
public void onClick(final View v) {
String sdet_id;
int det_id;
// v.setBackgroundColor(Color.GRAY);
det_id = v.getId();
sdet_id = String.valueOf(det_id);
final Intent i = new Intent();
i.setClassName("demo.example.com", "demo.example.com.viewdetails");
i.putExtra("Det_id", sdet_id);
startActivity(i);
// v.setBackgroundColor(Color.TRANSPARENT);
// TODO Auto-generated method stub
}
});
TableLayout.LayoutParams tableRowParams=
new TableLayout.LayoutParams
(TableLayout.LayoutParams.FILL_PARENT,TableLayout.LayoutParams.WRAP_CONTENT);
int leftMargin=20;
int topMargin=10;
int rightMargin=15;
int bottomMargin=20;
tableRowParams.setMargins(leftMargin, topMargin, rightMargin, bottomMargin);
tr.setLayoutParams(tableRowParams);
/* Create a Button to be the row-content. */
ImageView myimage = new ImageView(R.layout.getlist);
BitmapFactory.Options bmOptions;
bmOptions = new BitmapFactory.Options();
bmOptions.inSampleSize = 1;
Bitmap bm = LoadImage(image_URL, bmOptions);
myimage.setImageBitmap(bm);
tr.addView(myimage);
TextView tmake=new TextView(R.layout.getlist);
// tmake.setText(item_make);
tmake.setText(Html.fromHtml("<H1>" + " " + item_location + "</H1>" + "<br /> ;" + item_desc
));
tr.addView(tmake);
TextView tmodel=new TextView(R.layout.getlist);
tmodel.setText(Html.fromHtml("<b><H1>" + " " + "€" + item_price + "</b></H1></br></br>" ));
tr.addView(tmodel);
/* Add row to TableLayout. */
// tr.setPadding(50, 0, 0, 0);
tl.addView(tr);
View v = new View(R.layout.getlist);
v.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.FILL_PARENT, 1));
v.setBackgroundColor(Color.rgb(51, 51, 51));
tl.addView(v);
}
}
catch(JSONException e1){
Toast.makeText(getBaseContext(), "No Category Found" ,Toast.LENGTH_LONG).show();
} catch (ParseException e1) {
e1.printStackTrace();
}
}
}
The problem appears to be with creating new items to add to the view, lines like this
View v = new View(R.layout.getlist);
Is my overall structure ok or do I need to do this another way?
1.Usually we show the busy dialog in the onPreExecute of the
asyncTask.
2.You need to inflater your views thanks to an inflater.
LayoutInflater li = (LayoutInflater)mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View v = li.inflate(R.layout.view, null);
Hope this will help you.

Getting id of imageview

I am making a number of imageViews programmatically in a loop and assigning them ids. But when in onClick method I need to get the id of images, it is returning the id of the last image only. How do I get the id of the image that is clicked?
The code I am using:
for (int j = 0; j < 5; j++) {
TableRow tr = new TableRow(this);
imageUrl = "http://ondamove.it/English/images/users/";
imageUrl = imageUrl + listObject.get(j).getImage();
image = new ImageView(this);
image.setPadding(20, 10, 0, 0);
image.setId(j+1);
tr.addView(image);
try {
new DownloadFileAsync(image, new URL(imageUrl))
.execute(imageUrl);
images.add(image);
//images = new ImageView[5];
}
catch (Exception e) {
e.printStackTrace();
}
tr.addView(image);
table.addView(tr, new TableLayout.LayoutParams(
LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT));
image.setOnClickListener(clickImageListener);
Following is the onclicklistener.
private OnClickListener clickImageListener = new OnClickListener() {
public void onClick(View v) {
imageId = image.getId();
Intent fullScreenIntent = new Intent(v.getContext(),FullImageActivity.class);
fullScreenIntent.putExtra(ProfilePageNormalUser.class.getName(),imageId);
ProfilePageNormalUser.this.startActivity(fullScreenIntent);
}
};
Inside the onClick(View v) method you can call v.getId() - this will return you the ID of the View being clicked. Hope this helps.
Try this out:
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
int index = 0;
for (int i = 0; i < image.length; i++)
{
if (image[i].getId() == v.getId())
{
index = i;
break;
}
}
Toast.makeText(this, "Image clicked index => "+index, Toast.LENGTH_SHORT).show();
}

Categories

Resources