accessing specific itemview in listview in button onclick method - java

public class DisplayAllBets extends ActionBarActivity {
private String user1 = "user";
private static String url_all_games = "**";
private static String url_update_bet = "**";
// Progress Dialog
private ProgressDialog pDialog;
private ProgressDialog tDialog;
private BetDisplayer currentitem;
private HashMap<String, String> userhash = new HashMap<>();
private ArrayList<BetDisplayer> listwriter = new ArrayList<>();
private HashMap<String, String> useroutcomes = new HashMap<>();
private HashMap<String, String> finalhash = new HashMap<>();
private ArrayList<Map<String, String>> passtocheck = new ArrayList<>();
private HashMap<String, HashMap<String, String>> passtocheckver2 = new HashMap<>();
private String name;
private HashMap<String, String> allopens = new HashMap<>();
JSONParser jsonParser = new JSONParser();
// Creating JSON Parser object
JSONParsers jParser = new JSONParsers();
ArrayList<HashMap<String, String>> bet;
// url to get all products list
// JSON Node names
private static final String TAG_SUCCESS = "success";
private static final String TAG_BET = "bet";
private static final String TAG_ID = "id";
private static final String TAG_STAKE = "stake";
private static final String TAG_USER = "user";
private static final String TAG_RETURNS = "returns";
private static final String TAG_TEAMS = "teams";
private static final String TAG_STATUS = "status";
// products JSONArray
JSONArray allgames = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_all_bets);
name = (getIntent().getExtras().getString("user")).toLowerCase();
Log.d("name", name);
// Hashmap for ListView
bet = new ArrayList<HashMap<String, String>>();
// Loading products in Background Thread
new LoadAllGames().execute();
}
/**
* Background Async Task to Load all product by making HTTP Request
*/
class LoadAllGames extends AsyncTask<String, String, String> {
private String id;
private String stake;
private String user;
private String returns;
private String teams;
private String status;
// *//**
// * Before starting background thread Show Progress Dialog
// *//*
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(DisplayAllBets.this);
pDialog.setMessage("Loading Games. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
}
// *//**
// * getting All products from url
// *//*
protected String doInBackground(String... args) {
// Building Parameters
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(url_all_games);
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("email", name));
try {
post.setEntity(new UrlEncodedFormEntity(params));
} catch (IOException ioe) {
ioe.printStackTrace();
}
try {
HttpResponse response = client.execute(post);
Log.d("Http Post Response:", response.toString());
HttpEntity httpEntity = response.getEntity();
InputStream is = httpEntity.getContent();
JSONObject jObj = null;
String json = "";
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
if (!line.startsWith("<", 0)) {
if (!line.startsWith("(", 0)) {
sb.append(line + "\n");
}
}
}
is.close();
json = sb.toString();
json = json.substring(json.indexOf('{'));
Log.d("sb", json);
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
Log.d("json", jObj.toString());
try {
allgames = jObj.getJSONArray(TAG_BET);
Log.d("allgames", allgames.toString());
ArrayList<BetDatabaseSaver> listofbets = new ArrayList<>();
// looping through All Products
for (int i = 0; i < allgames.length(); i++) {
JSONObject c = allgames.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_ID);
String user = c.getString(TAG_USER);
String returns = c.getString(TAG_RETURNS);
String stake = c.getString(TAG_STAKE);
String status = c.getString(TAG_STATUS);
String Teams = c.getString(TAG_TEAMS);
Log.d("id", id);
Log.d("user", user);
Log.d("returns", returns);
Log.d("stake", stake);
Log.d("status", status);
Log.d("teams", Teams);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_ID, id);
map.put(TAG_TEAMS, Teams);
map.put(TAG_USER, user);
map.put(TAG_RETURNS, returns);
map.put(TAG_STAKE, stake);
map.put(TAG_STATUS, status);
if (status.equals("open")) {
useroutcomes.put(id.substring(0, 10), Teams);
}
listwriter.add(i, new BetDisplayer(user, id, Integer.parseInt(stake), Integer.parseInt(returns), status, Teams));
// adding HashList to ArrayList
bet.add(map);
}
} catch (JSONException e) {
e.printStackTrace();
}
} catch (IOException ioe) {
ioe.printStackTrace();
}
return "";
}
#Override
protected void onPostExecute(String param) {
// dismiss the dialog after getting all products
// updating UI from Background Thread
String ultparam = "";
int i = 0;
for (HashMap<String, String> a : bet) {
String teams = a.get(TAG_TEAMS);
Map<String, String> listofteams = new HashMap<>();
Pattern p = Pattern.compile("[(](\\d+)/([1X2])[)]");
Matcher m = p.matcher(teams);
Log.d("printa", teams);
while (m.find()) {
listofteams.put(m.group(1), m.group(2));
}
Log.d("dede", listofteams.toString());
String c = "";
for (String x : listofteams.keySet()) {
String b = x + ",";
c = c + b;
}
Log.d("C", c);
c = c.substring(0, c.lastIndexOf(","));
// Log.d("Cproc", c);
if (a.get(TAG_STATUS).equals("open")) {
ultparam = ultparam + a.get(TAG_ID).substring(0, 10) + c + "//";
passtocheck.add(listofteams);
allopens.put(Integer.toString(i), a.get(TAG_STATUS));
i++;
}
i++;
}
ultparam = ultparam.substring(0, ultparam.lastIndexOf("//"));
Log.d("ULTPARAM", ultparam);
CheckBet checker = new CheckBet(ultparam, passtocheck);
HashMap<String, String> finaloutcomes = checker.checkbetoutcome();
Log.d("Finaloutcomes", finaloutcomes.toString());
for (String x : finaloutcomes.keySet()) {
for (int p = 0; p < listwriter.size(); p++) {
if (listwriter.get(p).getId().substring(0, 10).equals(x)) {
String[] finaloutcomearray = finaloutcomes.get(x).split(" ");
String[] useroutcomearray = listwriter.get(p).getSelections().split(" ");
for (int r = 0; r < finaloutcomearray.length; r++) {
Log.d("finaloutcomearray", finaloutcomearray[r]);
Log.d("useroutcomearray", useroutcomearray[r]);
String[] indfinaloutcomesarray = finaloutcomearray[r].split("\\)");
String[] induseroutcomearray = useroutcomearray[r].split("\\)");
for (int d = 0; d < indfinaloutcomesarray.length; d++) {
Log.d("indfinaloutcome", indfinaloutcomesarray[d]);
Log.d("induseroutcome", induseroutcomearray[d]);
finalhash.put(indfinaloutcomesarray[d].substring(1, indfinaloutcomesarray[d].lastIndexOf("/")), indfinaloutcomesarray[d].substring(indfinaloutcomesarray[d].lastIndexOf("/") + 1));
userhash.put(induseroutcomearray[d].substring(1, induseroutcomearray[d].lastIndexOf("/")), induseroutcomearray[d].substring(induseroutcomearray[d].lastIndexOf("/") + 1));
}
}
Log.d("FINALHASHfinal", finalhash.toString());
Log.d("USERHASHfinal", userhash.toString());
listwriter.get(p).setStatus("won");
for (String id : userhash.keySet()) {
if (finalhash.get(id).equals("null")){
listwriter.get(p).setStatus("open");
}
else if (!(finalhash.get(id).equals(userhash.get(id)))) {
listwriter.get(p).setStatus("lost");
break;
}
}
finalhash.clear();
userhash.clear();
currentitem = listwriter.get(p);
new UpdateBetStatus().execute();
}
}
}
Log.d("USEROUTCOMES", useroutcomes.toString());
PopulateList();
}
}
#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_display_all_bets, 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);
}
class UpdateBetStatus extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* *
*/
#Override
protected void onPreExecute() {
super.onPreExecute();
tDialog = new ProgressDialog(DisplayAllBets.this);
tDialog.setMessage("Loading your bets! Good luck!");
tDialog.setIndeterminate(false);
tDialog.setCancelable(true);
}
/**
* Creating product
* *
*/
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("id", currentitem.getId()));
params.add(new BasicNameValuePair("stake", Integer.toString(currentitem.getStake())));
params.add(new BasicNameValuePair("user", name));
params.add(new BasicNameValuePair("returns", Integer.toString(currentitem.getReturns())));
params.add(new BasicNameValuePair("teams", currentitem.getSelections()));
params.add(new BasicNameValuePair("status", currentitem.getStatus()));
// getting JSON Object
// Note that create product url accepts POST method
JSONObject json = jsonParser.makeHttpRequest(url_update_bet,
"POST", params);
// check log cat fro response
Log.d("Printing", json.toString());
// check for success tag
try {
int success = json.getInt(TAG_SUCCESS);
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* * * *
*/
protected void onPostExecute(String file_url) {
// dismiss the dialog once done
}
}
private class MyListAdapter extends ArrayAdapter<BetDisplayer> {
public MyListAdapter() {
super(DisplayAllBets.this, R.layout.activity_singletotalbet, listwriter);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View itemView = convertView;
if (itemView == null) {
itemView = getLayoutInflater().inflate(R.layout.activity_singletotalbet, parent, false);
}
BetDisplayer currentwriter = listwriter.get(position);
Log.d("TESTING", currentwriter.getSelections());
Button v = (Button) itemView.findViewById(R.id.detailsbutton);
v.setTag(Integer.toString(position));
Log.d("TESTING2", currentwriter.getSelections());
String selections = currentwriter.getSelections();
int numberofselections = 0;
for (int i = 0; i < selections.length(); i++) {
if (selections.charAt(i) == '/') {
numberofselections++;
}
}
if (numberofselections == 1) {
TextView descriptor = (TextView) itemView.findViewById(R.id.no);
descriptor.setText("Single");
} else if (numberofselections == 2) {
TextView descriptor = (TextView) itemView.findViewById(R.id.no);
descriptor.setText("Double");
} else if (numberofselections == 3) {
TextView descriptor = (TextView) itemView.findViewById(R.id.no);
descriptor.setText("Treble");
} else {
TextView descriptor = (TextView) itemView.findViewById(R.id.no);
descriptor.setText("Accumulator" + "(" + numberofselections + ")");
}
TextView status = (TextView) itemView.findViewById(R.id.status);
status.setText(currentwriter.getStatus());
return itemView;
}
}
private void PopulateList() {
ArrayAdapter<BetDisplayer> adapter = new MyListAdapter();
final ListView list = (ListView) findViewById(R.id.betslistviews);
list.setAdapter(adapter);
}
public void Viewdetails(View v) {
Button b = (Button) v;
int position = Integer.parseInt((String) v.getTag());
final ListView list = (ListView) findViewById(R.id.betslistviews);
String stake;
String winnings;
String token;
String teams;
String typeofbet;
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> adapter, View v, int position, long id) {
TextView status = (TextView) v.findViewById(R.id.status);
Log.d("STATUSTESTING",status.getText().toString());
}
});
}
I have a populated listview. Each item in the list contains a button and a few TextViews, in the following format.
I created a method which is run when any of the buttons is clicked. What I need it to do is to retrieve that particular itemView at that position in the listview so I can access the TextViews in that itemview. This is my code but it isn't working atm.
public void Viewdetails(View v) {
Button b = (Button) v;
int position = Integer.parseInt((String) v.getTag());
final ListView list = (ListView) findViewById(R.id.betslistviews);
String stake;
String winnings;
String token;
String teams;
String typeofbet;
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> adapter, View v, int position, long id) {
View selItem = (View) list.getItemAtPosition(position);
TextView status = (TextView) selItem.findViewById(R.id.status);
Log.d("STATUSTESTING",status.getText().toString());
}
});
}

Assuming your ListView listener starts here.
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> adapter, View v, int position, long id) {
View selItem = (View) list.getItemAtPosition(position);
TextView status = (TextView) selItem.findViewById(R.id.status);
Log.d("STATUSTESTING",status.getText().toString());
}
});
You don't have to write
View selItem = (View) list.getItemAtPosition(position);
since you already got reference to the particular View in ListView from the overridden onItemClick method.
So you can skip that line and directly access TextView
TextView status = (TextView) v.findViewById(R.id.status);
Finally the code will be like
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> adapter, View v, int position, long id) {
//Already got reference to View v
TextView status = (TextView) v.findViewById(R.id.status);
Log.d("STATUSTESTING",status.getText().toString());
}
});

To catch onListItemClick add listener in PopulateList() method:
private void PopulateList() {
ArrayAdapter<BetDisplayer> adapter = new MyListAdapter();
final ListView list = (ListView) findViewById(R.id.betslistviews);
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> adapter, View v, int position, long id) {
// Change children of list item here
TextView status = (TextView) v.findViewById(R.id.status);
Log.d("STATUSTESTING",status.getText().toString());
}
});
}
To catch click on button in your list item you need in your adapter's getView() method add click listener to button:
#Override
public View getView(int position, View convertView, ViewGroup parent) {
Button v = (Button) itemView.findViewById(R.id.detailsbutton);
v.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Handle button click
}
});
}
EDIT:
To store data create fields in Activity and setters for it:
private String text1;
private String text2;
public void setText1(String text){
text1 = text;
}
public void setText2(String text){
text2 = text;
}
Then set it in button click listener:
#Override
public View getView(int position, View convertView, ViewGroup parent) {
TextView tv1 = (TextView) itemView.findViewById(R.id.textview1_id);
TextView tv2 = (TextView) itemView.findViewById(R.id.textview2_id);
Button v = (Button) itemView.findViewById(R.id.detailsbutton);
v.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
setText1(tv1.getText());
setText2(tv2.getText());
}
});
}

Related

How to solve the error like java.lang.Throwable: setStateLocked?

I am developing an app. In it I'm using a listview. When I click on list item, it should go to next activity, i.e ProfileActivity2.java. It works fine, but in this ProfileActivty2 there is a button at the bottom and when I click on this button my app gets crashed and stopped in listview page. And shows the error java.lang.Throwable: setStateLocked in listview layout file i.e At setContentView. How do I solve this error?
//ProfileActivity2.java
public class ProfileActivity2 extends AppCompatActivity {
//Textview to show currently logged in user
private TextView textView;
private boolean loggedIn = false;
Button btn;
EditText edname,edaddress;
TextView tvsname, tvsprice;
NumberPicker numberPicker;
TextView textview1,textview2;
Integer temp;
String pname, paddress, email, sname, sprice;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_profile1);
//Initializing textview
textView = (TextView) findViewById(R.id.textView);
edname=(EditText)findViewById(R.id.ed_pname);
edaddress=(EditText)findViewById(R.id.ed_add);
tvsname=(TextView)findViewById(R.id.textView_name);
tvsprice=(TextView)findViewById(R.id.textView2_price);
btn=(Button)findViewById(R.id.button);
Intent i = getIntent();
// getting attached intent data
String name = i.getStringExtra("sname");
// displaying selected product name
tvsname.setText(name);
String price = i.getStringExtra("sprice");
// displaying selected product name
tvsprice.setText(price);
numberPicker = (NumberPicker)findViewById(R.id.numberpicker);
numberPicker.setMinValue(0);
numberPicker.setMaxValue(4);
final int foo = Integer.parseInt(price);
textview1 = (TextView)findViewById(R.id.textView1_amount);
textview2 = (TextView)findViewById(R.id.textView_seats);
// numberPicker.setValue(foo);
numberPicker.setOnValueChangedListener(new NumberPicker.OnValueChangeListener() {
#Override
public void onValueChange(NumberPicker picker, int oldVal, int newVal) {
temp = newVal * foo;
// textview1.setText("Selected Amount : " + temp);
// textview2.setText("Selected Seats : " + newVal);
textview1.setText(String.valueOf(temp));
textview2.setText(String.valueOf(newVal));
// textview1.setText(temp);
// textview2.setText(newVal);
}
});
//Fetching email from shared preferences
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// submitForm();
// Intent intent = new Intent(ProfileActivity2.this, SpinnerActivity.class);
// startActivity(intent);
SharedPreferences sharedPreferences = getSharedPreferences(Config.SHARED_PREF_NAME, Context.MODE_PRIVATE);
loggedIn = sharedPreferences.getBoolean(Config.LOGGEDIN_SHARED_PREF, false);
String email = sharedPreferences.getString(Config.EMAIL_SHARED_PREF, "Not Available");
textView.setText(email);
if(loggedIn){
submitForm();
Intent intent = new Intent(ProfileActivity2.this, SpinnerActivity.class);
startActivity(intent);
}
}
});
}
private void submitForm() {
// Submit your form here. your form is valid
//Toast.makeText(this, "Submitting form...", Toast.LENGTH_LONG).show();
String pname = edname.getText().toString();
String paddress = edaddress.getText().toString();
String sname = textview1.getText().toString();
// String sname= String.valueOf(textview1.getText().toString());
String sprice= textview2.getText().toString();
// String sprice= String.valueOf(textview2.getText().toString());
String email= textView.getText().toString();
Toast.makeText(this, "Signing up...", Toast.LENGTH_SHORT).show();
new SignupActivity(this).execute(pname,paddress,sname,sprice,email);
}
}
//SignupActivity
public class SignupActivity extends AsyncTask<String, Void, String> {
private Context context;
Boolean error, success;
public SignupActivity(Context context) {
this.context = context;
}
protected void onPreExecute() {
}
#Override
protected String doInBackground(String... arg0) {
String pname = arg0[0];
String paddress = arg0[1];
String sname = arg0[2];
String sprice = arg0[3];
String email = arg0[4];
String link;
String data;
BufferedReader bufferedReader;
String result;
try {
data = "?pname=" + URLEncoder.encode(pname, "UTF-8");
data += "&paddress=" + URLEncoder.encode(paddress, "UTF-8");
data += "&sname=" + URLEncoder.encode(sname, "UTF-8");
data += "&sprice=" + URLEncoder.encode(sprice, "UTF-8");
data += "&email=" + URLEncoder.encode(email, "UTF-8");
link = "http://example.in/Spinner/update.php" + data;
URL url = new URL(link);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
bufferedReader = new BufferedReader(new InputStreamReader(con.getInputStream()));
result = bufferedReader.readLine();
return result;
} catch (Exception e) {
// return new String("Exception: " + e.getMessage());
// return null;
}
return null;
}
#Override
protected void onPostExecute(String result) {
String jsonStr = result;
Log.e("TAG", jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
String query_result = jsonObj.getString("query_result");
if (query_result.equals("SUCCESS")) {
Toast.makeText(context, "Success! Your are Now MangoAir User.", Toast.LENGTH_LONG).show();
} else if (query_result.equals("FAILURE")) {
Toast.makeText(context, "Looks Like you already have Account with US.", Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
e.printStackTrace();
// Toast.makeText(context, "Error parsing JSON Please data Fill all the records.", Toast.LENGTH_SHORT).show();
// Toast.makeText(context, "Please LogIn", Toast.LENGTH_SHORT).show();
Toast.makeText(context, "Please Login", Toast.LENGTH_LONG).show();
}
} else {
Toast.makeText(context, "Grrr! Check your Internet Connection.", Toast.LENGTH_SHORT).show();
}
}
}
//List_Search
public class List_Search extends AppCompatActivity {
JSONObject jsonobject;
JSONArray jsonarray;
ListView listview;
ListViewAdapter adapter;
ProgressDialog mProgressDialog;
ArrayList<HashMap<String, String>> arraylist;
static String SNAME = "sname";
static String SPRICE = "sprice";
Context ctx = this;
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.list_search);
new DownloadJSON().execute();
}
// DownloadJSON AsyncTask
private class DownloadJSON extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Create a progressdialog
mProgressDialog = new ProgressDialog(List_Search.this);
// Set progressdialog title
mProgressDialog.setTitle("Android JSON Parse Tutorial");
// Set progressdialog message
mProgressDialog.setMessage("Loading...");
mProgressDialog.setIndeterminate(false);
// Show progressdialog
mProgressDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
// Create an array
arraylist = new ArrayList<HashMap<String, String>>();
// Retrieve JSON Objects from the given URL address
jsonobject = JSONfunctions
.getJSONfromURL("http://example.in/MangoAir_User/mangoair_reg/ListView1.php");
try {
// Locate the array name in JSON
jsonarray = jsonobject.getJSONArray("result");
for (int i = 0; i < jsonarray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
jsonobject = jsonarray.getJSONObject(i);
// Retrive JSON Objects
map.put("sname", jsonobject.getString("sname"));
map.put("sprice", jsonobject.getString("sprice"));
// Set the JSON Objects into the array
arraylist.add(map);
}
} catch (JSONException e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void args) {
// Locate the listview in listview_main.xml
listview = (ListView) findViewById(R.id.listView_search);
// Pass the results into ListViewAdapter.java
// adapter = new ListViewAdapter(List_Search.this, arraylist);
adapter = new ListViewAdapter(ctx, arraylist);
// Set the adapter to the ListView
listview.setAdapter(adapter);
// Close the progressdialog
mProgressDialog.dismiss();
}
}
}
//ListViewAdapter
public class ListViewAdapter extends BaseAdapter {
// Declare Variables
Context context;
LayoutInflater inflater;
private boolean loggedIn = false;
ArrayList<HashMap<String, String>> data;
HashMap<String, String> resultp = new HashMap<String, String>();
public ListViewAdapter(Context context,
ArrayList<HashMap<String, String>> arraylist) {
this.context = context;
data = arraylist;
}
#Override
public int getCount() {
return data.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
public View getView(final int position, View convertView, ViewGroup parent) {
// Declare Variables
TextView name,price;
Button btn;
inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View itemView = inflater.inflate(R.layout.search_item, parent, false);
// Get the position
resultp = data.get(position);
// Locate the TextViews in listview_item.xml
name = (TextView) itemView.findViewById(R.id.textView8_sellernm);
// Capture position and set results to the TextViews
name.setText(resultp.get(List_Search.SNAME));
price = (TextView) itemView.findViewById(R.id.textView19_bprice);
// Capture position and set results to the TextViews
price.setText(resultp.get(List_Search.SPRICE));
btn=(Button)itemView.findViewById(R.id.button3_book);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
resultp = data.get(position);
Intent intent = new Intent(context, ProfileActivity2.class);
// Pass all data rank
intent.putExtra("sname", resultp.get(List_Search.SNAME));
intent.putExtra("sprice", resultp.get(List_Search.SPRICE));
context.startActivity(intent);
}
});
return itemView;
}
}
context.startActivity(intent);
I think the error is at this line inside btn.setOnClickListener of getview block just use startActivity(intent);

sent parameter to adapter in same class android

I have public class StudioDetail (main class) and in StudioDetail I generate private class SendfeedbackKelas like this :
private class SendfeedbackKelas extends AsyncTask<String, Void, String> {
private static final String LOG_TAG = "CariKelas";
Bundle extras = getIntent().getExtras();
final String token= extras.getString("TOKEN");
final String idstudio= extras.getString("STUDIO_ID");
#Override
protected String doInBackground(String... params) {
String date = params[0];
Utils.log("params 1:" + date);
// do above Server call here
kelasstudioList = new ArrayList<KelasStudioModel>();
String responseString = null;
final String url_kelas_studio = Constant.URI_BASE_STUDIO + idstudio + "/class" + "?date=" + date + "&token=" + token;
Utils.log("url kelas studio:"+ url_kelas_studio);
try
{
runOnUiThread(new Runnable() {
public void run() {
new JSONAsyncTask().execute(url_kelas_studio);
ListView listview = (ListView) findViewById(R.id.listView1);
adapter = new ClassSAdapter(context, R.layout.jadwalstudio_info, kelasstudioList);
listview.setAdapter(adapter);
}
});
}
catch (Exception e)
{
/*Toast.makeText(context,
"user not registered", Toast.LENGTH_SHORT).show();*/
Log.e(LOG_TAG, String.format("Error during login: %s", e.getMessage()));
}
return "processing";
}
protected void onPostExecute(Boolean result) {
//dialog.cancel();
}
}
that called ClassSAdapter like this :
private class ClassSAdapter extends ArrayAdapter<KelasStudioModel> {
final Context context = getContext();
ArrayList<KelasStudioModel> kelasstudioList;
LayoutInflater vi;
int Resource;
ViewHolder holder;
public ClassSAdapter(Context context, int resource, ArrayList<KelasStudioModel> objects) {
super(context, resource, objects);
vi = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
Resource = resource;
kelasstudioList = objects;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View.OnClickListener listener1 = new View.OnClickListener() {
#Override
public void onClick(View v) {
int position = (int)v.getTag();
// do stuff based on position or kelasList.get(position)
// you can call mActivity.startActivity() if you need
final Dialog dialog = new Dialog(context);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
dialog.setContentView(R.layout.dialog_popup_pesan_kelas);
closedialog = (ImageView) dialog.findViewById(R.id.closeDialog);
// if button is clicked, close the custom dialog
closedialog.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
/*studio_name.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(context, StudioDetail.class);
startActivity(intent);
}
});*/
dialog.show();
}
};
View.OnClickListener listener2 = new View.OnClickListener() {
#Override
public void onClick(View v) {
int position = (int)v.getTag();
// do stuff based on position or kelasList.get(position)
// you can call mActivity.startActivity() if you need
final Dialog dialog = new Dialog(context);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
dialog.setContentView(R.layout.dialog_popup_pelatih);
/*final String url_studio_image = Constant.URI_FRONTEND + "vendor_trainer/20150821052441-tanda-tanya.jpg";
Utils.log("url_studio_image: " + url_studio_image);
new DownloadImageTask((ImageView) dialog.findViewById(R.id.class_image_pelatih)).execute(url_studio_image);*/
closedialog = (ImageView) dialog.findViewById(R.id.closeDialog);
// if button is clicked, close the custom dialog
closedialog.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
dialog.dismiss();
}
});
dialog.show();
}
};
// convert view = design
View v = convertView;
if (v == null) {
holder = new ViewHolder();
v = vi.inflate(Resource, null);
holder.kelas = (TextView) v.findViewById(R.id.kelas);
holder.waktu = (TextView) v.findViewById(R.id.waktu);
holder.pelatih = (TextView) v.findViewById(R.id.pelatih);
// set OnClickListeners
holder.kelas.setOnClickListener(listener1);
holder.pelatih.setOnClickListener(listener2);
v.setTag(holder);
} else {
holder = (ViewHolder) v.getTag();
}
//holder.imageview.setImageResource(R.drawable.promo_1);
holder.kelas.setText(kelasstudioList.get(position).getKelas());
holder.waktu.setText(kelasstudioList.get(position).getWaktu());
holder.pelatih.setText(kelasstudioList.get(position).getPelatih());
// set tags
holder.kelas.setTag(position);
holder.waktu.setTag(position);
holder.pelatih.setTag(position);
return v;
}
private class ViewHolder {
public TextView kelas;
public TextView waktu;
public TextView pelatih;
}
}
I want to sent some parameter like this from class JSONAsyncTask to private class ClassSAdapter on View.OnClickListener listener1 and View.OnClickListener listener2 :
final String startdate=object.getString("startdate");
final String masterclass_name=Html.fromHtml((String) object.getString("masterclass_name")).toString();
final String enddate=object.getString("enddate");
final String trainer_name=Html.fromHtml((String) object.getString("trainer_name")).toString();
How to sent that parameter?
As information here is JSONAsynTask class:
class JSONAsyncTask extends AsyncTask<String, Void, Boolean> {
ProgressDialog dialog;
private static final String TAG_CLASSES = "classes";
#Override
protected void onPreExecute() {
super.onPreExecute();
dialog = new ProgressDialog(context);
dialog.setMessage("Loading, please wait");
dialog.setTitle("Connecting server");
dialog.show();
dialog.setCancelable(false);
}
#Override
protected Boolean doInBackground(String... urls) {
try {
HttpGet httppost = new HttpGet(urls[0]);
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response = httpclient.execute(httppost);
// StatusLine stat = response.getStatusLine();
int status = response.getStatusLine().getStatusCode();
if (status == 200) {
HttpEntity entity = response.getEntity();
String responseAsText = EntityUtils.toString(entity);
Utils.log("daftar isi classes: " + responseAsText);
JSONObject jsonObj = new JSONObject(responseAsText);
// Getting JSON Array node
JSONArray classes = jsonObj.getJSONArray(TAG_CLASSES);
for(int i=0;i<classes.length();i++){
//HashMap<String, String> promo = new HashMap<String, String>();
JSONObject object = classes.getJSONObject(i);
final String startdate=object.getString("startdate");
final String masterclass_name=Html.fromHtml((String) object.getString("masterclass_name")).toString();
final String enddate=object.getString("enddate");
final String trainer_name=Html.fromHtml((String) object.getString("trainer_name")).toString();
KelasStudioModel actor = new KelasStudioModel();
String starttime = parseDateToHis((String) object.getString("startdate")).toString();
String endtime = parseDateToHis((String) object.getString("enddate")).toString();
actor.setKelas(Html.fromHtml((String) object.getString("masterclass_name")).toString());
actor.setWaktu(starttime + "-" + endtime);
actor.setPelatih(object.getString("trainer_name"));
kelasstudioList.add(actor);
}
return true;
}
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return false;
}
protected void onPostExecute(Boolean result) {
dialog.cancel();
adapter.notifyDataSetChanged();
if(result == false){
Toast.makeText(context, "Unable to fetch data from server", Toast.LENGTH_LONG).show();
}else{
}
}
}
listener 1 and listener 2 called different dialog.

how to display details of single item of list in another activity from url (json data)?

I have written a program to display the list of json data from a url which has an image and 5 textviews which is displaying perfectly.
Url : https://itunes.apple.com/search?term=jack+johnson&limit=50.
When i click on an item from the list i want to display the details of that item in another activity based on the track-id
Url : https://itunes.apple.com/lookup?id=659234741
So when i click on the item the details are getting displayed in the textview , but by default it is displaying the details of id = 659234741 for some items or in short the details does not match.
Need some help to figure out the problem
My Code :
MainActivity.java
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
resultsList = new ArrayList<HashMap<String, String>>();
lv = getListView();
// Calling async task to get json
new GetTunesDetails().execute();
}
/**
* Async task class to get json by making HTTP call
* */
private class GetTunesDetails extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected Void doInBackground(Void... params) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
tunes = jsonObj.getJSONArray(TAG_RESULT);
// looping through All Products
for (int i = 0; i < tunes.length(); i++) {
JSONObject c = tunes.getJSONObject(i);
artworkImage = c.getString("artworkUrl100");
wrapperType = c.getString("wrapperType");
artistName = c.getString("artistName");
collectionName = c.getString("collectionName");
trackName = c.getString("trackName");
collectionPrice = c.getString("collectionPrice");
trackId = c.getString("trackId");
// tmp hashmap for single contact
HashMap<String, String> tunesMap = new HashMap<String,
String>();
// adding each child node to HashMap key => value
// contact.put(TAG_ID, firstname);
tunesMap.put(TAG_ARTWORK_IMAGE, artworkImage);
tunesMap.put(TAG_WRAPPER_TYPE, wrapperType);
tunesMap.put(TAG_ARTIST_NAME, artistName);
tunesMap.put(TAG_COLLECTION_NAME, collectionName);
tunesMap.put(TAG_TRACK_NAME, trackName);
tunesMap.put(TAG_COLLECTION_PRICE, collectionPrice);
tunesMap.put(TAG_TRACK_ID, trackId);
// adding contact to contact list
resultsList.add(tunesMap);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if (pDialog.isShowing())
pDialog.dismiss();
// Pass the results into ListViewAdapter.java
adapter = new ListViewAdapter(MainActivity.this, resultsList);
// Set the adapter to the ListView
lv.setAdapter(adapter);
}
}
ListViewAdapter.java
public class ListViewAdapter extends BaseAdapter {
// Declare Variables
Context context;
LayoutInflater inflater;
ArrayList<HashMap<String, String>> data;
ImageLoader imageLoader;
HashMap<String, String> resultp = new HashMap<String, String>();
int position;
TextView wrapperType, artistName, collectionName, trackName,
collectionPrice;
ImageView artworkImage;
public ListViewAdapter(Context context, ArrayList<HashMap<String, String>>
arraylist) {
this.context = context;
data = arraylist;
imageLoader = new ImageLoader(context);
}
#Override
public int getCount() {
return data.size();
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
return 0;
}
public View getView(final int position, View convertView, ViewGroup parent) {
// Declare Variables
// this.position = position;
inflater = (LayoutInflater)
context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View itemView = inflater.inflate(R.layout.custom_row, parent, false);
// Get the position
resultp = data.get(position);
// Locate the TextViews in listview_item.xml
wrapperType = (TextView) itemView.findViewById(R.id.wrapperType);
artistName = (TextView) itemView.findViewById(R.id.artistName);
collectionName = (TextView) itemView.findViewById(R.id.collectionName);
trackName = (TextView) itemView.findViewById(R.id.trackName);
collectionPrice = (TextView)
itemView.findViewById(R.id.collectionPrice);
// Locate the ImageView in listview_item.xml
artworkImage = (ImageView) itemView.findViewById(R.id.artworkImage);
// Capture position and set results to the TextViews
wrapperType.setText(resultp.get(MainActivity.TAG_WRAPPER_TYPE));
artistName.setText(resultp.get(MainActivity.TAG_ARTIST_NAME));
collectionName.setText(resultp.get(MainActivity.TAG_COLLECTION_NAME));
trackName.setText(resultp.get(MainActivity.TAG_TRACK_NAME));
collectionPrice.setText(resultp.get(MainActivity.TAG_COLLECTION_PRICE));
// Capture position and set results to the ImageView
// Passes flag images URL into ImageLoader.class
imageLoader.DisplayImage(resultp.get(MainActivity.TAG_ARTWORK_IMAGE),
artworkImage);
// Capture ListView item click
itemView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) { // TODO Auto-generated method
Toast.makeText(context, "Clicked at position " + position,
Toast.LENGTH_LONG).show();
Intent intent = new Intent(context, SingleTrack.class);
intent.putExtra("track_image",
resultp.get(MainActivity.TAG_ARTWORK_IMAGE));
intent.putExtra("wrapper_type",
resultp.get(MainActivity.TAG_WRAPPER_TYPE));
intent.putExtra("artistName",
resultp.get(MainActivity.TAG_ARTIST_NAME));
intent.putExtra("collectionName",
resultp.get(MainActivity.TAG_COLLECTION_NAME));
intent.putExtra("trackName",
resultp.get(MainActivity.TAG_TRACK_NAME));
intent.putExtra("collectionPrice",
resultp.get(MainActivity.TAG_COLLECTION_PRICE));
intent.putExtra("trackId",
resultp.get(MainActivity.TAG_TRACK_ID));
context.startActivity(intent);
}
});
return itemView;
}
SingleTrack.java : This is the class where i displaying the details on single item click
public class SingleTrack extends Activity {
// URL to get contacts JSON
private static String url = "";
// JSON Node names
static final String TAG_RESULT = "results";
static final String TAG_ARTWORK_IMAGE = "artworkUrl100";
static final String TAG_WRAPPER_TYPE = "wrapperType";
static final String TAG_ARTIST_NAME = "artistName";
static final String TAG_COLLECTION_NAME = "collectionName";
static final String TAG_TRACK_NAME = "trackName";
static final String TAG_COLLECTION_PRICE = "collectionPrice";
static final String TAG_TRACK_ID = "trackId";
// contacts JSONArray
JSONArray tracks = null;
// Hashmap for ListView
ArrayList<HashMap<String, String>> singleTrackDetails;
ProgressDialog pDialog;
String passedData1, passedData2, passedData3, passedData4, passedData5,
passedData6, passedData7;
TextView wrapperTypeText, artistNameText, collectionNameText, trackNameText,
collectionPriceText;
ImageView trackImage;
String artworkImage, wrapperType, artistName, collectionName, trackName,
collectionPrice, trackId;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.single_track);
wrapperTypeText = (TextView) findViewById(R.id.wrapperType1);
artistNameText = (TextView) findViewById(R.id.artistName1);
collectionNameText = (TextView) findViewById(R.id.collectionName1);
trackNameText = (TextView) findViewById(R.id.trackName1);
collectionPriceText = (TextView) findViewById(R.id.collectionPrice);
trackImage = (ImageView) findViewById(R.id.artworkImage1);
passedData1 = getIntent().getStringExtra("track_image");
passedData2 = getIntent().getStringExtra("wrapper_type");
passedData3 = getIntent().getStringExtra("artistName");
passedData4 = getIntent().getStringExtra("collectionName");
passedData5 = getIntent().getStringExtra("trackName");
passedData6 = getIntent().getStringExtra("collectionPrice");
passedData7 = getIntent().getStringExtra("trackId");
singleTrackDetails = new ArrayList<HashMap<String, String>>();
// url
url = "https://itunes.apple.com/lookup?id=" + passedData7;
// Calling async task to get json
new GetSingleTrackDetails().execute();
}
class GetSingleTrackDetails extends AsyncTask<String, Void, String> {
private JSONObject jsonObj;
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(SingleTrack.this);
pDialog.setMessage("Loading Track Details...");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected String doInBackground(String... params) {
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(url, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
// Getting JSON Array node
tracks = jsonObj.getJSONArray(TAG_RESULT);
// looping through All Products
for (int i = 0; i < tracks.length(); i++) {
JSONObject c = tracks.getJSONObject(i);
artworkImage = c.getString("artworkUrl100");
wrapperType = c.getString("wrapperType");
artistName = c.getString("artistName");
collectionName = c.getString("collectionName");
trackName = c.getString("trackName");
collectionPrice = c.getString("collectionPrice");
trackId = c.getString("trackId");
// tmp hashmap for single contact
HashMap<String, String> tunesMap = new HashMap<String,
String>();
// adding each child node to HashMap key => value
// contact.put(TAG_ID, firstname);
tunesMap.put(TAG_ARTWORK_IMAGE, artworkImage);
tunesMap.put(TAG_WRAPPER_TYPE, wrapperType);
tunesMap.put(TAG_ARTIST_NAME, artistName);
tunesMap.put(TAG_COLLECTION_NAME, collectionName);
tunesMap.put(TAG_TRACK_NAME, trackName);
tunesMap.put(TAG_COLLECTION_PRICE, collectionPrice);
tunesMap.put(TAG_TRACK_ID, trackId);
// adding contact to contact list
singleTrackDetails.add(tunesMap);
}
} catch (JSONException e) {
e.printStackTrace();
}
} else {
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
if (pDialog != null) {
pDialog.dismiss();
pDialog = null;
}
wrapperTypeText.setText(wrapperType);
artistNameText.setText(artistName);
collectionNameText.setText(collectionName);
trackNameText.setText(trackName);
collectionPriceText.setText(collectionPrice);
}
}
Thank you
The problem is that you are initializing the resultp each element in your getView method, so therefore the last id/element of the listview adapter's data will be considered as the resultp.
Im sure that the id 659234741 is the last element, which will always be the id for each onclick that would happen.
A solution for this is to create a final resultp within your getView method instead of having just one global resultp.
final HashMap<String, String> resultp = data.get(position);

ListView Doesn't display anymore than 8 ImageViews

I am decoding jpeg images from a server request I get using json. I display them with a custom ListView Adapter along with a little text.
The images display correctly for the first 8 ImageViews in the ListView, however, after that it will no longer display the image (it will display the text). For example, if I have a total of 10 images, the last two images will not show in the ListView, but if I delete the first 2 images, the last two will show, so there is no concern about retrieving the actual images.
On my main activity (NotesActivity) I have a button that goes to another activity which does an asyntask, and in that async task in the onPostExecute, it returns back to the main activity where it should show the updated list (and it does, unless there are more than 8 images).
I don't know where to begin, any suggestions?
My Activity that contains the ListView
public class NotesActivity extends Activity implements OnClickListener {
String key = "NOTES";
String key2 = "UPDATE_NOTES";
Gson gson = new Gson();
// Notes myNotes = new Notes();
NotesList myNotes = new NotesList();
String bId;
String res = null;
EditText notes;
Button save;
private Button createNote;
private int position;
private String type;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.notes_layout);
createNote = (Button) findViewById(R.id.notes_layout_btn_createNote);
Bundle bundle = this.getIntent().getExtras();
position = bundle.getInt("position");
type = bundle.getString("type");
//
if (type.equals("LISTINGS")) {
Listings it = ListingsFragment.myListings.getListings().get(
position);
bId = it.getBID();
notes = (EditText) findViewById(R.id.notes);
}
//
if (type.equals("SHARED")) {
Listings it = SharedFragment.myShared.getListings().get(position);
bId = it.getBID();
notes = (EditText) findViewById(R.id.notes);
}
GetNotes getNotes = new GetNotes();
try {
NotesList copy = new NotesList();
getNotes.execute(key, bId).get();
for (int j = 0; j < myNotes.getNotes().size(); j++) {
Notes note = myNotes.getNotes().get(j);
System.out.println("Removed value: " + note.getIsRemoved());
if (note.getIsRemoved() == null) {
copy.getNotes().add(note);
}
}
NotesAdapter adapter = new NotesAdapter(this, R.layout.note_row,
copy.getNotes());
ListView lv = (ListView) findViewById(R.id.notes_layout_lv_notesList);
lv.setAdapter(adapter);
} catch (Exception e) {
}
createNote.setOnClickListener(this);
}
private class GetNotes extends AsyncTask<String, String, NotesList> {
#Override
protected NotesList doInBackground(String... things) {
ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("key", things[0]));
postParameters.add(new BasicNameValuePair("bId", things[1]));
// String valid = "1";
String response = null;
try {
response = CustomHttpClient.executeHttpPost(
"http://propclip.dev/mobile.php", postParameters);
res = response.toString();
// System.out.println("This is the response " + res);
// res = res.trim();
// res= res.replaceAll("\\s+","");
// error.setText(res);
// System.out.println(res);
myNotes = gson.fromJson(res, NotesList.class);
// System.out.println(res);
} catch (Exception e) {
res = e.toString();
}
return myNotes;
}
#Override
protected void onPostExecute(NotesList res) {
}
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.notes_layout_btn_createNote:
ProfileDataSource datasource = new ProfileDataSource(this);
datasource.open();
PropClipGlobal pcg = datasource.getUserIdenity();
Intent intent = new Intent(this, NewNoteActivity.class);
intent.putExtra("bId", bId);
intent.putExtra("uId", pcg.getUID());
intent.putExtra("username", pcg.getEm());
intent.putExtra("position", position);
intent.putExtra("type", type);
startActivity(intent);
}
}
}
My custom adapter
public class NotesAdapter extends ArrayAdapter<Notes> {
List<Notes> notes;
Context context;
public NotesAdapter(Context context, int resource, List<Notes> notes) {
super(context, resource, notes);
this.notes = notes;
this.context = context;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = convertView;
if (v == null) {
LayoutInflater vi;
vi = LayoutInflater.from(getContext());
v = vi.inflate(R.layout.note_row, null);
}
Notes note = notes.get(position);
ImageView icon = (ImageView) v.findViewById(R.id.note_row_icon);
TextView name = (TextView) v.findViewById(R.id.note_row_name);
TextView message = (TextView) v.findViewById(R.id.note_row_message);
TextView date = (TextView) v.findViewById(R.id.note_row_date);
String input = note.getNoteDate();
SimpleDateFormat inputDf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
SimpleDateFormat outputDf = new SimpleDateFormat("dd, yyyy");
SimpleDateFormat monthFormat = new SimpleDateFormat("MM");
Date myDate = null;
try {
myDate = inputDf.parse(input);
} catch (ParseException e) {
e.printStackTrace();
}
String month = monthFormat.format(myDate);
date.setText(getMonth(Integer.parseInt(month)) + " "
+ outputDf.format(myDate));
message.setText(note.getNote());
name.setText(note.getFirstName() + " " + note.getLastName());
// System.out.println(p.getFileData());
byte[] imageAsBytes = Base64.decode(note.getFileData().getBytes(),
position);
icon.setImageBitmap(BitmapFactory.decodeByteArray(imageAsBytes, 0,
imageAsBytes.length));
System.out.println(note.getFileData());
return v;
}
public String getMonth(int month) {
return new DateFormatSymbols().getMonths()[month - 1];
}
}
Activity which eventually goes to the main activity (NotesActivity)
public class NewNoteActivity extends Activity implements OnClickListener {
private String uId;
private String bId;
private String username;
private String response;
private String key = "UPDATE_NOTES";
private Button submit;
private EditText note;
private int position;
private String type;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new_note);
submit = (Button) findViewById(R.id.activity_new_note_btn_submit);
note = (EditText) findViewById(R.id.activity_new_note_et_note);
Intent intent = getIntent();
bId = intent.getStringExtra("bId");
uId = intent.getStringExtra("uId");
username = intent.getStringExtra("username");
position = intent.getIntExtra("position", 0);
type = intent.getStringExtra("type");
submit.setOnClickListener(this);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.new_note, menu);
return true;
}
private class UpdateNotes extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... values) {
ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("key", values[0]));
postParameters.add(new BasicNameValuePair("bId", values[1]));
postParameters.add(new BasicNameValuePair("uId", values[2]));
postParameters.add(new BasicNameValuePair("username", values[3]));
postParameters.add(new BasicNameValuePair("note", values[4]));
String response = null;
try {
response = CustomHttpClient.executeHttpPost(
"http://propclip.dev/mobile.php", postParameters);
response = response.toString();
} catch (Exception e) {
response = e.toString();
}
return null;
}
#Override
protected void onPostExecute(String response) {
Intent intent = new Intent(getApplicationContext(),
NotesActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra("position", position);
intent.putExtra("type", type);
startActivity(intent);
Toast toast = Toast.makeText(getApplicationContext(),"Added note!", Toast.LENGTH_LONG);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
}
}
#Override
public void onClick(View v) {
String noteMessage = note.getText().toString();
UpdateNotes updateNotes = new UpdateNotes();
updateNotes.execute(key, bId, uId, username, noteMessage);
}
}

"returnRes cannot be resolved to a variable" error in android

I had tested the function of endless Scrolling function in a dummy projects, it works fine but if i paste the same code in my original project m getting "loadMoreListItems cannot be resolved to a variable" on the variable "loadMoreListItems" and "returnRes cannot be resolved to a variable" on the variable, even i checked for android.R imports and layout name everything is correct dont know where is the mistake.
public class Home extends ListActivity {
ArrayList<HashMap<String, String>> songsList;
ListView list;
LazyAdapter adapter;
JSONArray posts;
LinearLayout line1,line2;
ImageView menu;
boolean loadingMore = false;
ArrayList<String> songsList1;
LayoutInflater inflater;
static int jsonpage = 0;
JSONParser jParser;
JSONObject json;
TextView loadtext;
// All static variables
static final String URL = "http://www.exm.com/?json=get_recent_posts";
static final String KEY_POSTS = "posts";
static final String KEY_ID = "id";
static final String KEY_TITLE = "title";
static final String KEY_DATE = "date";
static final String KEY_CONTENT = "content";
static final String KEY_AUTHOR = "author";
static final String KEY_NAME = "name";
static final String KEY_ATTACHMENTS = "attachments";
static final String KEY_SLUG = "slug";
static final String KEY_THUMB_URL = "thumbnail";
static final String KEY_IMAGES = "images";
static final String KEY_URL = "url";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
list = (ListView) findViewById(android.R.id.list);
// get the LayoutInflater for inflating the customomView
// this will be used in the custom adapter
inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
songsList = new ArrayList<HashMap<String, String>>();
_loaddata();
LayoutInflater li = LayoutInflater.from(getBaseContext());
View footerView = li.inflate(com.exm.com.R.layout.listfooter, null);
loadtext = (TextView) footerView.findViewById(R.id.empty);
loadtext.setEnabled(false);
loadtext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "poda",
Toast.LENGTH_LONG).show();
}
});
this.getListView().addFooterView(footerView);
// Getting adapter by passing json data ArrayList
adapter = new LazyAdapter(this, songsList);
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(
getApplicationContext(),
"Click ListItem Number "
+ songsList.get(position).get("title"),
Toast.LENGTH_LONG).show();
}
});
this.getListView().setOnScrollListener(new OnScrollListener() {
#Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
// int first = view.getFirstVisiblePosition();
// int count = view.getChildCount();
//
// if (scrollState == SCROLL_STATE_IDLE
// || (first + count > adapter.getCount())) {
// list.invalidateViews();
// }
if (scrollState == SCROLL_STATE_IDLE) {
_loaddata();
adapter.notifyDataSetChanged();
}
}
#Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
}
});
Thread thread = new Thread(null, loadMoreListItems);
thread.start();
}
#SuppressWarnings("unused")
private void _loaddata() {
try {
// getting JSON string from URL
jParser = new JSONParser();
jsonpage = jsonpage + 1;
json = jParser
.getJSONFromUrl("http://india.exm.net/ads/page/"
+ jsonpage + "/?json=get_recent_posts");
posts = json.getJSONArray(KEY_POSTS);
if (posts.length() > 0) {
for (int i = 0; i < posts.length(); i++) {
JSONObject c = posts.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(KEY_ID);
String title = c.getString(KEY_TITLE);
String date = c.getString(KEY_DATE);
String content = c.getString(KEY_CONTENT);
// to remove all <P> </p> and <br /> and replace with ""
content = content.replace("<br />", "");
content = content.replace("<p>", "");
content = content.replace("</p>", "");
// authornumber is agin JSON Object
JSONObject author = c.getJSONObject(KEY_AUTHOR);
String name = author.getString(KEY_NAME);
String url = null;
String slug = null;
try {
JSONArray atta = c.getJSONArray("attachments");
for (int j = 0; j < atta.length(); j++) {
JSONObject d = atta.getJSONObject(j);
slug = d.getString(KEY_SLUG);
JSONObject images = d.getJSONObject(KEY_IMAGES);
JSONObject thumbnail = images
.getJSONObject(KEY_THUMB_URL);
url = thumbnail.getString(KEY_URL);
}
} catch (Exception e) {
e.printStackTrace();
}
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(KEY_ID, id);
map.put(KEY_TITLE, title);
map.put(KEY_DATE, date);
map.put(KEY_NAME, name);
map.put(KEY_CONTENT, content);
map.put(KEY_SLUG, slug);
map.put(KEY_URL,
url);
// adding HashList to ArrayList
songsList.add(map);
}
} else
loadtext.setText("Data ivlo thaan irukku k va summa look-u vidatha");
} catch (JSONException e) {
e.printStackTrace();
}
// Runnable to load the items
Runnable loadMoreListItems = new Runnable() {
#Override
public void run() {
// Set flag so we cant load new items 2 at the same time
loadingMore = true;
// Reset the array that holds the new items
songsList1 = new ArrayList<String>();
// Simulate a delay, delete this on a production environment!
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
}
runOnUiThread(returnRes);
}
};
// Since we cant update our UI from a thread this Runnable takes care of
// that!
private Runnable returnRes = new Runnable() {
#Override
public void run() {
// Loop thru the new items and add them to the adapter
if (songsList1 != null && songsList1.size() > 0) {
for (int i = 0; i < songsList1.size(); i++)
adapter.add(songsList1.get(i));
}
// Update the Application title
setTitle("Neverending List with "
+ String.valueOf(adapter.getCount()) + " items");
// Tell to the adapter that changes have been made, this will cause
// the list to refresh
adapter.notifyDataSetChanged();
// Done loading more.
loadingMore = false;
}
};
This has nothing to do with Android resources.
The variable loadMoreListItems is used in onCreate(), but it is defined in _loaddata(). You cannot define a variable in one method and use it in another method.
You could return loadMoreListItems from _loaddata()
private Runnable _loaddata() {
...
return loadMoreListItems;
}
and use it in onCreate() like
Runnable loadMoreListItems = _loaddata();
...
Thread thread = new Thread(null, loadMoreListItems);
And you use returnRes in Runnable loadMoreListItems before it is defined later in the same method. You must first define and initialize returnRes and then you can use it in loadMoreListItems. So moving returnRes before loadMoreListItems should solve this one.

Categories

Resources