Semi-new to programming Android apps, or apps in general. I'm trying to create a bunch of buttons based on JSON response. The response is coming back good (checked in Log.i) and no errors showing an issue, but the buttons aren't displaying. Here's my main activity, asynctask class and main xml. Any feedback super appreciated.
Main Activity:
public class MainActivity extends ActionBarActivity {
Spinner spinner;
public SpinAdapter adapter;
JSONObject jsonobject;
JSONArray jsonarray;
ProgressDialog mProgressDialog;
ArrayList<String> barlist;
Brewery[] breweries;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
spinner = (Spinner) findViewById(R.id.planets_spinner);
Log.i("msg", "sent to json");
new DownloadJSON().execute();
Log.i("msg", "past to json");
}
private class DownloadJSON extends AsyncTask<Void, Void, Void>
{
#Override
protected Void doInBackground(Void... params) {
barlist = new ArrayList<String>();
try
{
Log.i("msg", "inside try");
HttpClient httpclient = new DefaultHttpClient();
httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
HttpGet request = new HttpGet("http://fltapmap.com/populate.php");
HttpResponse response = httpclient.execute(request);
HttpEntity resEntity = response.getEntity();
String _response=EntityUtils.toString(resEntity);
jsonobject = new JSONObject(_response);
jsonarray = jsonobject.getJSONArray("breweries");
Log.i("msg", "breweries lengths: "+jsonarray.length());
breweries = new Brewery[jsonarray.length()];
for (int i = 0; i < jsonarray.length(); i++) {
jsonobject = jsonarray.getJSONObject(i);
breweries[i] = new Brewery();
breweries[i].setId(jsonobject.optInt("ID"));
breweries[i].setName(jsonobject.optString("brewery"));
}
}catch(Exception e)
{
Log.i("msg",""+e.getMessage());
}
return null;
}
protected void onPostExecute(Void args) {
// Spinner adapter
adapter = new SpinAdapter(MainActivity.this,android.R.layout.simple_spinner_item,breweries);
spinner.setAdapter(adapter);
// You can create an anonymous listener to handle the event when is selected an spinner item
spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> adapterView, View view,
int position, long id) {
// Here you get the current item (a User object) that is selected by its position
Brewery brewery = adapter.getItem(position);
// Here you can do the action you want to...
Log.i("msg", "inside selected method"+String.valueOf(brewery.getId()));
new RetrieveBeersTask(MainActivity.this, findViewById(R.id.beer_list)).execute(String.valueOf(brewery.getId()));
/*
jsonarray = jsonobject.getJSONArray("ontap");
Log.i("msg", "breweries lengths: "+jsonarray.length());
Button beer_btns[] = new Button[jsonarray.length()];
Log.i("msg","buttons made");
for (int i = 0; i < jsonarray.length(); i++) {
Log.i("msg","in loop"+String.valueOf(i));
LinearLayout layout = (LinearLayout)findViewById(R.id.beer_list);
beer_btns[i] = new Button(MainActivity.this);
beer_btns[i].setText(jsonarray.getJSONObject(i).getString("beer"));
beer_btns[i].setGravity(Gravity.CENTER_HORIZONTAL);
beer_btns[i].setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//add your code here
}
});
layout.addView(beer_btns[i]);
}
*/
}
#Override
public void onNothingSelected(AdapterView<?> adapter) { }
});
}
}
#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;
}
#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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
AsyncTask Class
public class RetrieveBeersTask extends AsyncTask<String, Void, ArrayList<String>> {
private Exception exception;
JSONObject jsonobject;
public JSONArray jsonarray;
public ArrayList<String> return_beers;
private Activity myMain;
private View myLayout;
public RetrieveBeersTask(Activity passedin, View mainLayout) {
this.myMain = passedin;
this.myLayout = mainLayout;
}
#Override
protected ArrayList<String> doInBackground(String... brewery) {
try {
Log.i("msg", "inside launcher: Brewery - "+brewery[0]);
HttpClient httpclient = new DefaultHttpClient();
httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
HttpGet request = new HttpGet("http://fltapmap.com/ontap.php?id="+brewery[0]);
HttpResponse response = httpclient.execute(request);
Log.i("msg","request back");
HttpEntity resEntity = response.getEntity();
String _response=EntityUtils.toString(resEntity);
/*
Log.i("msg","ssending request");
HttpResponse response = httpclient.execute(request);
Log.i("msg","request back");
HttpEntity resEntity = response.getEntity();
Log.i("msg","should have response");
String _response=EntityUtils.toString(resEntity);
Log.i("msg","got repsonse"+_response);
*/
jsonobject = new JSONObject(_response);
jsonarray = jsonobject.getJSONArray("ontap");
return_beers = new ArrayList<String>();
for (int i = 0; i < jsonarray.length(); i++) {
Log.i("msg", "beer name: "+jsonarray.getJSONObject(i).getString("beer"));
return_beers.add(jsonarray.getJSONObject(i).getString("beer"));
}
return return_beers;
} catch(Exception e) {
e.printStackTrace();
return null;
}
}
protected void onPostExecute(ArrayList<String> beers) {
// TODO: check this.exception
// TODO: do something with the feed
Log.i("msg", "length of array: "+String.valueOf(beers.size()));
Button beer_btns[] = new Button[jsonarray.length()];
for (int i = 0; i < beers.size(); i++) {
beer_btns[i] = new Button(myMain);
beer_btns[i].setText(beers.get(i));
beer_btns[i].setGravity(Gravity.CENTER_HORIZONTAL);
beer_btns[i].setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//add your code here
}
});
LinearLayout layout = (LinearLayout)myLayout;
Log.i("msg",String.valueOf(layout));
layout.addView(beer_btns[i]);
}
}
}
Related
I know this question keeps popping up but my code is slightly different from the other ones, so I don't know where I need to make my changes.
I want to put data ("fest_name") into an ArrayList ("festivals") and make it appear in a ListView.
This is my code for JSON:
public void getFestivals() {
Thread thread_getdata = new Thread(new Runnable() {
#Override
public void run() {
try {
HttpClient httpclient = new DefaultHttpClient();
String link = "http://pou-pou.de/stagedriver/android/uebersicht.php";
HttpPost httppost = new HttpPost(link);
ResponseHandler<String> responseHandler = new BasicResponseHandler();
final String response = httpclient.execute(httppost,
responseHandler);
final ArrayList<String> festivals = new ArrayList<String>();
Log.i("Response", "Response : " + response);
JSONArray jsonarray = new JSONArray(response);
for (int i = 0; i < jsonarray.length(); i++) {
JSONObject jsonobj = jsonarray.getJSONObject(i);
final String fest_name = jsonobj.getString("fest_name");
festivals.add(fest_name);
runOnUiThread(new Runnable() {
#Override
public void run() {
}
});
}
} catch (Exception e) {
e.printStackTrace();
}
}
});
thread_getdata.start();
}
And this is for the ListView:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fahrt_anbieten1);
ListView lvFestivals = (ListView) findViewById(R.id.lvFestivals);
getFestivals();
ListAdapter festivalsAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, festivals);
lvFestivals.setAdapter(festivalsAdapter);
}
I just don't know how to combine the two ones: if I run the app, I just get an empty page, but no real errors.
I would be so happy if anyone could help!
First, using Thread to make network requests isn't recommended.
Second, Apache HTTP has some extra code around simple network requests. When you could instead use Volley (you'll need compile 'com.android.volley:volley:1.0.0')
If you implement the below code, you should get something like this listview.
public class FestListActivity extends AppCompatActivity
implements Response.Listener<JSONArray>, Response.ErrorListener {
private ListView mListView;
private ArrayAdapter<String> mAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(android.R.layout.list_content);
mListView = (ListView) findViewById(android.R.id.list);
mAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1);
mListView.setAdapter(mAdapter);
getFestivals();
}
private void getFestivals() {
String festURL = "http://pou-pou.de/stagedriver/android/uebersicht.php";
RequestQueue queue = Volley.newRequestQueue(this);
JsonArrayRequest req = new JsonArrayRequest(festURL, this, this);
queue.add(req);
}
#Override
public void onErrorResponse(VolleyError error) {
Log.e("Error", error.getMessage());
}
#Override
public void onResponse(JSONArray response) {
mAdapter.clear();
try {
for (int i = 0; i < response.length(); i++) {
final JSONObject festObj = response.getJSONObject(i);
int festId = Integer.valueOf(festObj.getString("id_fest"));
String festName = festObj.getString("fest_name");
mAdapter.add(festId + " - " + festName);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
After the adapter is not a problem if you put the loop
public void getFestivals() {
Thread thread_getdata = new Thread(new Runnable() {
#Override
public void run() {
try {
HttpClient httpclient = new DefaultHttpClient();
String link = "http://pou-pou.de/stagedriver/android/uebersicht.php";
HttpPost httppost = new HttpPost(link);
ResponseHandler<String> responseHandler = new BasicResponseHandler();
final String response = httpclient.execute(httppost,
responseHandler);
final ArrayList<String> festivals = new ArrayList<String>();
Log.i("Response", "Response : " + response);
JSONArray jsonarray = new JSONArray(response);
for (int i = 0; i < jsonarray.length(); i++) {
JSONObject jsonobj = jsonarray.getJSONObject(i);
final String fest_name = jsonobj.getString("fest_name");
festivals.add(fest_name);
runOnUiThread(new Runnable() {
#Override
public void run() {
}
});
}
ListAdapter festivalsAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, festivals);
lvFestivals.setAdapter(festivalsAdapter);
} catch (Exception e) {
e.printStackTrace();
}
}
});
thread_getdata.start();
}
Put it on the ListView variable OnCreate
ListView lvFestivals;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fahrt_anbieten1);
lvFestivals = (ListView) findViewById(R.id.lvFestivals);
getFestivals();
}
I am getting this exception
android.view.ViewRootImpl$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
Below is the code:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_page2);
lv = (ListView) findViewById(R.id.list_view);
btnNew = (Button)findViewById(R.id.btnAddNew);
btnNew.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent moveToNewUser = new Intent(getApplication(),ExecutiveInfo2.class);
moveToNewUser.putExtra("ClickType","1");
startActivity(moveToNewUser);
}
});
new Connection2().execute();
// Listview Data
}
private class Connection2 extends AsyncTask {
#Override
protected Object doInBackground(Object... arg0) {
test2();
return null;
}
#Override
protected void onPostExecute(Object s) {
super.onPostExecute(s);
}
}
public void test2() {
HttpURLConnection connection = null;
try {
sharedpreferences = getSharedPreferences("MyPrefs", this.MODE_PRIVATE);
String storedUUID = sharedpreferences.getString("UUID", "");
String url2= "http://crm.xqicai.com/sales/getExecutiveInfo?UUID="+storedUUID;
//String url = "http://crm.xqicai.com/sales/login";
URL postUrl = new URL(url2);
connection = (HttpURLConnection) postUrl.openConnection();
connection.setDoOutput(true);
connection.setDoInput(true);
connection.setRequestMethod("GET");
connection.setUseCaches(false);
connection.setInstanceFollowRedirects(true);
connection.setRequestProperty("Content-Type", "application/json");
connection.connect();
BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(), "utf-8"));// 设置编ç �,å�¦åˆ™ä¸æ–‡ä¹±ç �
while (true) {
String str = reader.readLine();
if (str == null) {
break;
}
System.out.println(str);
JSONObject mainObject = new JSONObject(str);
Status = mainObject.getString("status");
int j=0;
if(Status.equals("0"))
{
JSONObject uniObject = mainObject.getJSONObject("data");
JSONArray a = uniObject.getJSONArray("data");
for (int i = 0; i < a.length(); i++) {
JSONObject json_obj = a.getJSONObject(i);
String demo = json_obj.getString("realName");
fetchedNames[j]= demo;
j++;
}
// Adding items to listview
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, fetchedNames);
lv.setAdapter(adapter);
}
else
{
JSONObject mainObject2 = new JSONObject(str);
errorMsg = mainObject2.getString("msg");
runOnUiThread(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), errorMsg, Toast.LENGTH_SHORT).show();
}
});
}
}
} catch (Exception e) {
e.printStackTrace();
} finally {
}
}
I'm only a beginner, so please forgive me for asking possibly a stupid question.
What line is giving the error? The problem is that you update a view created in the main thread, in your AsyncTask (a different thread). You should update this view in the onPostExecute of your AsyncTask (this is done in your main thread). I don't see immediately where you update the view.
EDIT:
Your problem should be solved if you put these two lines
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, fetchedNames);
lv.setAdapter(adapter);
below this line:
lv = (ListView) findViewById(R.id.list_view);
or in the:
protected void onPostExecute(Object s)
Test that:
ListView lv...
lv.post(new Runnable() {
#Override
public void run() {
//Update UI;
lv.setAdapter(...);
}
})
you can try use Handler with sendEmptyMessage() inside asynctask to pass by exception.
ex.
Handler mHandler = new Handler(Looper.getMainLooper()) {
#Override
public void handleMessage(Message inputMessage) {
// Adding items to listview
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, fetchedNames);
lv.setAdapter(adapter);
}
});
note for code bellow:
//call mHandler.sendEmpyMessage() in asynctask:
if(Status.equals("0"))
{
JSONObject uniObject = mainObject.getJSONObject("data");
JSONArray a = uniObject.getJSONArray("data");
for (int i = 0; i < a.length(); i++) {
JSONObject json_obj = a.getJSONObject(i);
String demo = json_obj.getString("realName");
fetchedNames[j]= demo;
j++;
}
// Adding items to listview
mHandler.sendEmpyMessage(0); //0 or any number is identify code from you want use to check with every action
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());
}
});
}
I am using viewpager with gridview and downloading json data into it and implemented gridview scroll listener but whenever i start activity again the current viewpager fragment in which sroll listener implemented shows blank.
Here is my code, please see and tell me my mistake.
//My Activity Fragment
private static String url = "http://--------/------";
private int mVisibleThreshold = 5;
private int mCurrentPage = 0;
private int mPreviousTotal = 0;
private boolean mLoading = true;
private boolean mLastPage = false;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.gridview_fragment, container,
false);
setRetainInstance(true);
arrayList = new ArrayList<Items>();
gridView = (GridView) rootView.findViewById(R.id.gridView1);
//My Json Execution
new LoadData().execute(url);
//Scroll listener when gridview reaches at end
gridView.setOnScrollListener(new OnScrollListener() {
#Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
if (mLoading) {
if (totalItemCount > mPreviousTotal) {
mLoading = false;
mPreviousTotal = totalItemCount;
mCurrentPage++;
if (mCurrentPage + 1 > 10) {
mLastPage = true;
}
}
}
if (!mLastPage
&& !mLoading
&& (totalItemCount - visibleItemCount) <= (firstVisibleItem + mVisibleThreshold)) {
//Loading new datas in gridview
new LoadData()
.execute("http://-----/-----");
mLoading = true;
}
}
});
return rootView;
}
private class LoadData extends AsyncTask<String, Void, Void> {
#Override
protected void onPostExecute(Void result) {
//checking whether adapter is null or not
if (adap == null) {
adap = new Grid_View_Adatper(getActivity()
.getApplicationContext(), arrayList);
gridView.setAdapter(adap);
}
adap.notifyDataSetChanged();
super.onPostExecute(result);
}
#Override
protected Void doInBackground(String... urls) {
try {
HttpClient client = new DefaultHttpClient();
HttpGet httpget = new HttpGet(urls[0]);
HttpResponse response = client.execute(httpget);
HttpEntity entity = response.getEntity();
String data = EntityUtils.toString(entity);
JSONArray json = new JSONArray(data);
for (int i = 0; i < json.length(); i++) {
JSONObject e = json.getJSONObject(i);
String name = e.getString("name");
String price = e.getString("price");
String image = e.getString("image");
String code = e.getString("sku");
tems = new Items(name, price, image, code);
arrayList.add(tems);
}
} catch (JSONException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
} catch (IOException e) {
} catch (RuntimeException e) {
}
return null;
}
}
}
Thanks in advance...
So I have this code, which is a page with a ListView search field and a button to confirm the search, when the button is pressed the ListView is filled with movie names from the Rotten Tomatoes API, The problem is that someone helped me with this code, and I would love some help breaking it down and understanding it sentence after sentence, My main goal is to get is to get the "title", "synopsis" and "url image" of a movie that was clicked in the list, and pass it with an intent to my other activity but the whole JSON and get specific data stuff, got me very confused.
Link to Rotten Tomatoes API documentation, this is my code:
public class MovieAddFromWeb extends Activity implements View.OnClickListener,
OnItemClickListener {
private TextView searchBox;
private Button bGo, bCancelAddFromWeb;
private ListView moviesList;
public List<String> movieTitles;
static final int ACTIVITY_WEB_ADD = 3;
// the Rotten Tomatoes API key
private static final String API_KEY = "8q6wh77s65aw435cab9rbzsq";
// the number of movies to show in the list
private static final int MOVIE_PAGE_LIMIT = 8;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.movie_add_from_web);
InitializeVariables();
}
/*
* Initializing the variables and creating the bridge between the views from
* the xml file and this class
*/
private void InitializeVariables() {
searchBox = (EditText) findViewById(R.id.etSearchBox);
bGo = (Button) findViewById(R.id.bGo);
bCancelAddFromWeb = (Button) findViewById(R.id.bCancelAddFromWeb);
moviesList = (ListView) findViewById(R.id.list_movies);
bGo.setOnClickListener(this);
bCancelAddFromWeb.setOnClickListener(this);
moviesList.setOnItemClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.bGo:
new RequestTask()
.execute("http://api.rottentomatoes.com/api/public/v1.0/movies.json?apikey="
+ API_KEY
+ "&q="
+ searchBox.getText()
+ "&page_limit=" + MOVIE_PAGE_LIMIT);
break;
case R.id.bCancelAddFromWeb:
finish();
break;
}
}
private void refreshMoviesList(List<String> movieTitles) {
moviesList.setAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, movieTitles
.toArray(new String[movieTitles.size()])));
}
private class RequestTask extends AsyncTask<String, String, String> {
// make a request to the specified url
#Override
protected String doInBackground(String... uri) {
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response;
String responseString = null;
try {
// make a HTTP request
response = httpclient.execute(new HttpGet(uri[0]));
StatusLine statusLine = response.getStatusLine();
if (statusLine.getStatusCode() == HttpStatus.SC_OK) {
ByteArrayOutputStream out = new ByteArrayOutputStream();
response.getEntity().writeTo(out);
out.close();
responseString = out.toString();
} else {
// close connection
response.getEntity().getContent().close();
throw new IOException(statusLine.getReasonPhrase());
}
} catch (Exception e) {
Log.d("Test", "Couldn't make a successful request!");
}
return responseString;
}
#Override
protected void onPostExecute(String response) {
super.onPostExecute(response);
try {
// convert the String response to a JSON object
JSONObject jsonResponse = new JSONObject(response);
// fetch the array of movies in the response
JSONArray jArray = jsonResponse.getJSONArray("movies");
// add each movie's title to a list
movieTitles = new ArrayList<String>();
for (int i = 0; i < jArray.length(); i++) {
JSONObject movie = jArray.getJSONObject(i);
movieTitles.add(movie.getString("title"));
}
// refresh the ListView
refreshMoviesList(movieTitles);
} catch (JSONException e) {
Log.d("Test", "Couldn't successfully parse the JSON response!");
}
}
}
#Override
public void onItemClick(AdapterView<?> av, View view, int position, long id) {
Intent openMovieEditor = new Intent(this, MovieEditor.class);
openMovieEditor.putExtra("movieTitle", movieTitles.get(position));
openMovieEditor.putExtra("callingActivity", ACTIVITY_WEB_ADD);
startActivityForResult(openMovieEditor, ACTIVITY_WEB_ADD);
}
}
see the modified code below..
public class MovieAddFromWeb extends Activity implements View.OnClickListener, OnItemClickListener {
private TextView searchBox;
private Button bGo, bCancelAddFromWeb;
private ListView moviesList;
public List<String> movieTitles;
//added new variables
public List<String> movieSynopsis;
public List<String> movieImgUrl;
static final int ACTIVITY_WEB_ADD = 3;
// the Rotten Tomatoes API key
private static final String API_KEY = "8q6wh77s65aw435cab9rbzsq";
// the number of movies to show in the list
private static final int MOVIE_PAGE_LIMIT = 8;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.movie_add_from_web);
InitializeVariables();
}
/*
* Initializing the variables and creating the bridge between the views from
* the xml file and this class
*/
private void InitializeVariables() {
searchBox = (EditText) findViewById(R.id.etSearchBox);
bGo = (Button) findViewById(R.id.bGo);
bCancelAddFromWeb = (Button) findViewById(R.id.bCancelAddFromWeb);
moviesList = (ListView) findViewById(R.id.list_movies);
bGo.setOnClickListener(this);
bCancelAddFromWeb.setOnClickListener(this);
moviesList.setOnItemClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.bGo:
new RequestTask()
.execute("http://api.rottentomatoes.com/api/public/v1.0/movies.json?apikey="
+ API_KEY
+ "&q="
+ searchBox.getText()
+ "&page_limit=" + MOVIE_PAGE_LIMIT);
break;
case R.id.bCancelAddFromWeb:
finish();
break;
}
}
private void refreshMoviesList(List<String> movieTitles) {
moviesList.setAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, movieTitles
.toArray(new String[movieTitles.size()])));
}
private class RequestTask extends AsyncTask<String, String, String> {
// make a request to the specified url
#Override
protected String doInBackground(String... uri) {
HttpClient httpclient = new DefaultHttpClient();
HttpResponse response;
String responseString = null;
try {
// make a HTTP request
response = httpclient.execute(new HttpGet(uri[0]));
StatusLine statusLine = response.getStatusLine();
if (statusLine.getStatusCode() == HttpStatus.SC_OK) {
ByteArrayOutputStream out = new ByteArrayOutputStream();
response.getEntity().writeTo(out);
out.close();
responseString = out.toString();
} else {
// close connection
response.getEntity().getContent().close();
throw new IOException(statusLine.getReasonPhrase());
}
} catch (Exception e) {
Log.d("Test", "Couldn't make a successful request!");
}
return responseString;
}
#Override
protected void onPostExecute(String response) {
super.onPostExecute(response);
try {
// convert the String response to a JSON object
JSONObject jsonResponse = new JSONObject(response);
// fetch the array of movies in the response
JSONArray jArray = jsonResponse.getJSONArray("movies");
// add each movie's title to a list
movieTitles = new ArrayList<String>();
//newly added
movieSynopsis = new ArrayList<String>();
movieImgUrl= new ArrayList<String>();
for (int i = 0; i < jArray.length(); i++) {
JSONObject movie = jArray.getJSONObject(i);
movieTitles.add(movie.getString("title"));
movieSynopsis.add(movie.getString(#add the synopsis var name returned by the JSON));
movieImgUrl.add(movie.getString(#add the urlvar name returned by the JSON));
}
// refresh the ListView
refreshMoviesList(movieTitles);
} catch (JSONException e) {
Log.d("Test", "Couldn't successfully parse the JSON response!");
}
}
}
#Override
public void onItemClick(AdapterView<?> av, View view, int position, long id) {
Intent openMovieEditor = new Intent(this, MovieEditor.class);
openMovieEditor.putExtra("movieTitle", movieTitles.get(position));
//newly added
openMovieEditor.putExtra("movieSynopsis", movieSynopsis.get(position));
openMovieEditor.putExtra("movieImgUrl", movieImgUrl.get(position));
openMovieEditor.putExtra("callingActivity", ACTIVITY_WEB_ADD);
startActivityForResult(openMovieEditor, ACTIVITY_WEB_ADD);
}