I have an android rate bar that is inflated into an layout. When I run the code, I get the rating I want to update the rateBar with from json and I check with my log to see that I actually get a rating, which I do. But when I try:
RatingBar ratingBar = (RatingBar) ((Activity) c).findViewById(R.id.beerRatingBar);
ratingBar.setNumStars(beerRate);
It does not update the rateBar on the activity.
My activity is beer page:
public class BeerPage extends Activity {
BeerData e;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.beer_page);
//get data from listview
Intent intent = getIntent();
Bundle b = intent.getExtras();
e = b.getParcelable("myBeerObject");
//prepare buttons
Button buttonBrewery = (Button) findViewById(R.id.buttonBrewery);
Button buttonStyle = (Button) findViewById(R.id.buttonStyle);
//prepare text things
TextView tv1 = (TextView) findViewById(R.id.beerTitle);
TextView tv2 = (TextView) findViewById(R.id.beerDescription);
TextView tv_ibu = (TextView) findViewById(R.id.IBU);
TextView tv_abv = (TextView) findViewById(R.id.abv);
TextView tv_glass = (TextView) findViewById(R.id.glass);
//set text thinsg
tv1.setText(e.beerName);
tv2.setText(e.beerDescription);
buttonBrewery.setText(e.beerBreweryName);
buttonStyle.setText(e.beerStyle);
tv_ibu.setText(e.beerIBU);
tv_abv.setText(e.beerABV);
tv_glass.setText(e.beerGlass);
//Toast.makeText(this, e.mediumLabel, Toast.LENGTH_SHORT).show();
//set image
ImageView im1 = (ImageView) findViewById(R.id.image);
ImageDownloadTask imageD = new ImageDownloadTask(im1);
imageD.execute(e.largeLabel);
//test shared prefs
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
String userName = prefs.getString("userName", null);
String userID = prefs.getString("userID", null);
//check if user has beer
String url = myURL;
String userURLComp = user;
String beerID = beerID;
url = url + userURLComp + beerID;
Log.d("lat", e.beerBreweryLat);
Log.d("long", e.beerBreweryLong);
new CheckBeerJSON(this,e).execute(url);
}
//view brewery function
public void viewBrewery(View view) {
// launch new brewery page class
Intent i = new Intent(this, BreweryPage.class);
i.putExtra("myBeerObject", e);
i.setClass(this, BreweryPage.class);
startActivity(i);
}
public void viewStyle(View view) {
// launch new brewery page class
Intent i = new Intent(this, BreweryPage.class);
i.putExtra("myBeerObject", e);
i.setClass(this, StylePage.class);
startActivity(i);
}
public String encodeThisWord(String word){
try {
word = URLEncoder.encode(word, "UTF-8");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return word;
}
public void addBeer(View view){
//get user info
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
String userName = prefs.getString("userName", null);
String userID = prefs.getString("userID", null);
//get beer details
String url = url2;
String urlUserID = userID;
String urlBeerID = beer + e.beerId;
String urlBeerName = beerName + encodeThisWord(e.beerName);
//construct url for adding beer
url = url + urlUserID + urlBeerID + urlBeerName;
Log.d("url", url);
//execute async on url to add to brewery
new AddBeer(this).execute(url);
//to do: change to start rater
}
}
GetUserRating is where I get the rating to put into the rateBar:
public class GetUserRating extends AsyncTask
<String, Void, String> {
Context c;
public GetUserRating(Context context)
{
c = context;
}
#Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
return readJSONFeed(arg0[0]);
}
protected void onPostExecute(String result){
int beerRate = 0;
//parse json for value
try{
JSONObject json = new JSONObject(result);
beerRate = json.getInt("rate");
}
catch(Exception e){
}
Log.d("logIN", "the rating: " + beerRate);
//change rating
RatingBar ratingBar = (RatingBar) ((Activity) c).findViewById(R.id.beerRatingBar);
ratingBar.setNumStars(beerRate);
}
public String readJSONFeed(String URL) {
StringBuilder stringBuilder = new StringBuilder();
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(URL);
try {
HttpResponse response = httpClient.execute(httpGet);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) {
HttpEntity entity = response.getEntity();
InputStream inputStream = entity.getContent();
BufferedReader reader = new BufferedReader(
new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
stringBuilder.append(line);
}
inputStream.close();
} else {
Log.d("JSON", "Failed to download file");
}
} catch (Exception e) {
Log.d("readJSONFeed", e.getLocalizedMessage());
}
return stringBuilder.toString();
}
}
I found out my problem, I was changing the number of stars shown with this:
ratingBar.setNumStars(beerRate);
Which was in fact changing the number of stars shown. I wanted to highlight a certain number of the 5 stars shown, not change the number of stars shown.
What I really wanted to do was set the stars with:
r.setRating(beerRate);
I think that update a view item in an asyncTasck directly is a bad idea.
I suggest to create a public static member in BeerPage to update the beer rating.
Regards
Related
I have a recycleview in a card layout, the cards have 3 values set with a company array, I'm trying to send those values as an intent. But for some reason everything I try the intent ends up sending null
#Override
public void onBindViewHolder(#NonNull final ViewHolder viewHolder, final int i) {
//companyList= new ArrayList<Company>();
//heres where the textviews get there values set
final Company company = companies.get(i);
viewHolder.textViewHead.setText(company.getCompanyTitle());
viewHolder.textviewDesc.setText(company.getCompanyType());
viewHolder.textViewNumber.setText(company.getCompanyNumber());
viewHolder.linearLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
///send these to nodes them attach the officers, get both in nodes and send to myview
companylist = new ArrayList<Company>();
//here are my ateempts try and send the values as intents
Company company1 = companies.get(i);
// view.getContext().startActivity(new Intent(view.getContext(), Nodes.class));
Intent skipintent = new Intent(view.getContext(), Nodes.class);
skipintent.putExtra(KEY_NAME, company.getCompanyTitle());
skipintent.putExtra(KEY_NAME,viewHolder.textViewHead.getText().toString());
skipintent.putExtra(KEY_TYPE, company1.getCompanyType());
skipintent.putExtra(KEY_NUMBER, company1.getCompanyNumber());
// view.getContext().startActivity(skipintent);
Bundle bundle = new Bundle();
bundle.putString("Companyname", company.getCompanyTitle());
bundle.putString(KEY_TYPE, company1.getCompanyType());
bundle.putString(KEY_NUMBER, company1.getCompanyNumber());
// bundle.putParcelableArrayList("Companyselected", companylist);
skipintent.putExtras(bundle);
new RetrieveFeedTask().execute(company1.getCompanyNumber());
}
});
}
And here is my activity where I am trying to receive it
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.content_nodes);
//Toolbar toolbar = findViewById(R.id.toolbar);
// setSupportActionBar(toolbar);
//textViewNodes = (TextView) findViewById(R.id.textViewNodes);
// ArrayList<Company> recList = this.getIntent().getParcelableArrayListExtra("Company");
// companyList= new ArrayList <>();
ArrayList<Officer> officerArrayList = this.getIntent().getParcelableArrayListExtra("Officer");
// ArrayList<Company> companyArrayList = this.getIntent().getParcelableArrayListExtra("Companyselected");
Intent skipintent = getIntent();
Bundle bundle = getIntent().getExtras();
if (null != skipintent) { //Null Checking
Company company = new Company();
String companyTITLE = bundle.getString("Companyname");
String companyNUMBER = skipintent.getStringExtra(company.getCompanyNumber());
String companyTYPE = skipintent.getStringExtra(company.getCompanyType());
company.setCompanyNumber(companyNUMBER);
company.setCompanyTitle(companyTITLE);
company.setCompanyType(companyTYPE);
companyList.add(company);
Log.d("help", "onPostExecute: " + company.getCompanyTitle());
}
Log.d("meme", Arrays.toString(new ArrayList[]{companyList}));
here is the end of retrivefeed, I think I should send the values of the textviews here im not sure how
try {
JSONObject object = new JSONObject(response);
JSONArray itemsAraay = object.getJSONArray("items");
officerList = new ArrayList<Officer>();
Log.d("borkofficer", "onPostExecute: " + itemsAraay.length());
for (int i = 0; i < itemsAraay.length(); i++) {
Officer officer = new Officer();
JSONObject jsonObjectNew = itemsAraay.getJSONObject(i);
String name = jsonObjectNew.optString("name");
String role = jsonObjectNew.optString("officer_role");
String appointed_on = jsonObjectNew.optString("appointed_on");
//JSONArray.put(jsonObjectNew);
officer.setOfficerName(name);
officer.setOfficerRole(role);
officer.setOfficerAppointed(appointed_on);
officerList.add(officer);
Log.d("borkofficer", "onPostExecute: " + officer.getOfficerName());
Log.d("borkofficertitle", "onPostExecute: " + officer.getOfficerRole());
}
Bundle bundle = new Bundle();
bundle.putParcelableArrayList("Officer", officerList);
//Intent skipintent = new Intent(view.getContext(), Nodes.class);
Intent intentofficer = new Intent(context.getApplicationContext(), Nodes.class);
intentofficer.putParcelableArrayListExtra("Officer", officerList);
Intent intentofficer1 = new Intent(context.getApplicationContext(), Nodes.class);
intentofficer1.putExtras(bundle);
// context.startActivity(intentofficer1);
intentofficer.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intentofficer1.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.getApplicationContext().startActivity(intentofficer);
} catch (JSONException e) {
e.printStackTrace();
}
update im trying to bundle up the value and send in a intent but its still coming up null in the other activity is it because of the other intent im trying to send?
class RetrieveFeedTask extends AsyncTask {
private Exception exception;
protected String doInBackground(String... numbers) {
companylist = new ArrayList<Company>();
Company company = new Company();
String companynumber = numbers[0];
String companytitle = numbers[1];
String companytype = numbers[2];
company.setCompanyTitle(companytitle);
company.setCompanyType(companytype);
company.setCompanyNumber(companynumber);
companylist.add(company);
Bundle bundle1 = new Bundle();
Intent skipintent = new Intent(context.getApplicationContext(), Nodes.class);
skipintent.putExtra(KEY_NAME, companytitle);
skipintent.putExtra(KEY_NUMBER, companynumber);
skipintent.putExtra(KEY_TYPE, companytype);
skipintent.putParcelableArrayListExtra("Companylist", companylist);
skipintent.putExtras(bundle1);
Log.d("connect", "onPostExecute: " + companytitle.toString());
Log.d("connect", "onPostExecute: " + companytype.toString());
try {
URL url = new URL(API_URL + companynumber +"/officers");
Log.d("connect", "onPostExecute: " + companynumber.toString());
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
try {
urlConnection.setRequestMethod("GET");
urlConnection.setRequestProperty("Authorization", "uG5RCz7yWRZNKaMlkQRzUPXY1NpN0SRrb8mKSZ-0");
urlConnection.setReadTimeout(15000);
urlConnection.setConnectTimeout(15000);
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream()));
StringBuilder stringBuilder = new StringBuilder();
String line;
while ((line = bufferedReader.readLine()) != null) {
stringBuilder.append(line).append("\n");
}
bufferedReader.close();
return stringBuilder.toString();
} finally {
urlConnection.disconnect();
}
} catch (Exception e) {
Log.e("ERROR", e.getMessage(), e);
return null;
}
}
protected void onPostExecute(String response) {
if (response == null) {
response = "THERE WAS AN ERROR";
}
Log.i("INFO", response);
//does this store?
try {
JSONObject object = new JSONObject(response);
JSONArray itemsAraay = object.getJSONArray("items");
officerList = new ArrayList<Officer>();
Log.d("borkofficer", "onPostExecute: " + itemsAraay.length());
for (int i = 0; i < itemsAraay.length(); i++) {
Officer officer = new Officer();
JSONObject jsonObjectNew = itemsAraay.getJSONObject(i);
String name = jsonObjectNew.optString("name");
String role = jsonObjectNew.optString("officer_role");
String appointed_on = jsonObjectNew.optString("appointed_on");
//JSONArray.put(jsonObjectNew);
officer.setOfficerName(name);
officer.setOfficerRole(role);
officer.setOfficerAppointed(appointed_on);
officerList.add(officer);
Log.d("borkofficer", "onPostExecute: " + officer.getOfficerName());
Log.d("borkofficertitle", "onPostExecute: " + officer.getOfficerRole());
}
Bundle bundle = new Bundle();
bundle.putParcelableArrayList("Officer", officerList);
//skipintent.putExtra(KEY_NUMBER, company1.getCompanyNumber());
// view.getContext().startActivity(skipintent);
//Bundle bundle = new Bundle();
// bundle.putString(KEY_NAME,);
//bundle.putString(KEY_TYPE, companylist.get(1).getCompanyType());
//bundle.putString(KEY_NUMBER, companylist.get(1).getCompanyNumber());
//company1.setCompanyTitle(;
//company1.setCompanyNumber(KEY_NUMBER);
// company1.setCompanyType(KEY_TYPE);
// companylist.add(company1);
// bundle.putParcelableArrayList("Companyselected", companylist);
//skipintent.putExtras(bundle);
Intent intentofficer = new Intent(context.getApplicationContext(), Nodes.class);
intentofficer.putParcelableArrayListExtra("Officer", officerList);
Intent intentofficer1 = new Intent(context.getApplicationContext(), Nodes.class);
intentofficer1.putExtras(bundle);
// context.startActivity(intentofficer1);
intentofficer.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intentofficer1.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.getApplicationContext().startActivity(intentofficer);
Inside the activity, try to extract values with same keys as were used in adapter. Use
String companyNUMBER = skipintent.getStringExtra(KEY_NUMBER);
String companyTYPE = skipintent.getStringExtra(KEY_TYPE);
instead of
String companyNUMBER = skipintent.getStringExtra(company.getCompanyNumber());
String companyTYPE = skipintent.getStringExtra(company.getCompanyType());
UPDATE
To start activity inside the AsyncTask, pass data as a constructor parameter: new RetrieveFeedTask(company.getCompanyName()).
private String mCompanyName;
RetrieveFeedTask(String companyName) {
this.mCompanyName = companyName;
}
and then use it as usually to put in the intent:
intent.putExtra(KEY_NAME, mCompanyName);
UPDATE 2
As an alternative, you can pass data in the new RetrieveFeedTask().execute(company1.getCompanyNumber(), company1.getCompanyTitle(), company1.getCompanyType()) method and use them in doInBackground:
String doInBackground(String... data) {
String companyNumber = data[0];
String companyTitle = data[1];
String companyType = data[2];
// ...
}
I am not able to find any appropriate solution for below issue. I am using AsyncTask app sends request to server and it returns the JSON array as response, in postExecute method I parsed it, and problem is when I try to set the parsed data to TextView, textview not showing data. I am sure that server returned some data, and this data was parsed in postExecute and saved in global variables. TextViews also was declared as global variables, and defined in OnCreate method. thanks in advance!
Please check Code mentioned below:
public class CompanyData extends AppCompatActivity implements View.OnClickListener {
Button cComments;
String ssid,bin;
String extra, extra1;
TextView compData1, compData2, compData3, compData4, compData5, compData6, compTitle;
String title, kod_okpo, address, reg_date, fio, kod_oked, ovd ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_company_data);
cComments = (Button) findViewById(R.id.cComment);
cComments.setOnClickListener(this);
Bundle extras = getIntent().getExtras();
if (extras != null) {
extra = extras.getString("bin");
extra1 = extras.getString("ssid");
send_company_req(extra1, extra);
}
compTitle = (TextView) findViewById(R.id.companyTitle);
compData1 = (TextView) findViewById(R.id.compData1);
compData2 = (TextView) findViewById(R.id.compData2);
compData3 = (TextView) findViewById(R.id.compData3);
compData4 = (TextView) findViewById(R.id.compData4);
compData5 = (TextView) findViewById(R.id.compData5);
compData6 = (TextView) findViewById(R.id.compData6);
//Toast.makeText(this,"LOOOL" + title+bin+kod_okpo+address+reg_date+fio+kod_oked+ovd, Toast.LENGTH_SHORT).show();
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.cComment:
Intent companyData = new Intent(CompanyData.this, Comments.class);
companyData.putExtra("bin", bin);
companyData.putExtra("ssid", ssid);
startActivity(companyData);
startActivity(new Intent(this, Comments.class));
break;
}
}
private void send_company_req(final String ssid, final String searchData) {
class GetJSON extends AsyncTask<String, String, String> {
ProgressDialog loading;
String rStr;
#Override
protected void onPreExecute() {
super.onPreExecute();
loading = ProgressDialog.show(CompanyData.this, "Request...", null, true, true);
}
#Override
protected String doInBackground(String... params) {
String token = params[0];
String fi = params[1];
String uri = Quickstart.URL + "/car/info";
String param = null;
try {
param = "ssid=" + URLEncoder.encode(token, "UTF-8") +
"&bin=" + URLEncoder.encode(fi, "UTF-8") + "&dev=android";
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
try {
URL url = new URL(uri);
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setDoOutput(true);
con.setRequestMethod("POST");
con.setFixedLengthStreamingMode(param.getBytes().length);
con.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
con.setRequestProperty("Authorization", "Bearer " + token);
PrintWriter out = new PrintWriter(con.getOutputStream());
out.print(param);
out.close();
String response = "";
Scanner inStream = new Scanner(con.getInputStream());
while (inStream.hasNextLine()) {
response += (inStream.nextLine());
}
return response;
} catch (Exception e) {
return null;
}
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
loading.dismiss();
//Toast.makeText(CompanyData.this, s, Toast.LENGTH_LONG).show();
JSONArray jsonArrayComp;
try {
jsonArrayComp = new JSONArray(s.trim());
JSONObject jsonObjectComp = jsonArrayComp.getJSONObject(0);
try {
title = jsonObjectComp.getString("title");
kod_okpo = jsonObjectComp.getString("kod_okpo");
address = jsonObjectComp.getString("address");
reg_date = jsonObjectComp.getString("reg_date");
fio = jsonObjectComp.getString("fio");
kod_oked = jsonObjectComp.getString("kod_1_oked");
ovd = jsonObjectComp.getString("vidd");
Toast.makeText(CompanyData.this,"LOOOL" + title+bin+kod_okpo+address+reg_date+fio+kod_oked+ovd, Toast.LENGTH_LONG).show();
} catch (Exception ee) {
}
} catch (Exception e) {
//Toast.makeText(CompanyData.this, "Упс,:( что то пошло не так, попробуйте еще раз пожалуйста.", Toast.LENGTH_SHORT).show();
}
compTitle.setText(title);
compData1.setText(bin);
compData2.setText(kod_okpo);
compData3.setText(address);
compData4.setText(reg_date);
compData5.setText(fio);
compData6.setText(kod_oked + " - " + ovd);
}
}
GetJSON gj = new GetJSON();
gj.execute(ssid, searchData);
}
}
this is my LoginActivity class, i want to do add remember me option to this class.
public class LoginActivity extends Activity {
ProgressDialog prgDialog;
// Error Msg TextView Object
TextView errorMsg;
// Email Edit View Object
EditText emailET;
// Passwprd Edit View Object
EditText pwdET;
String email;
// Get Password Edit View Value
String password;
Button button;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_main);
// Find Error Msg Text View control by ID
errorMsg = (TextView) findViewById(R.id.login_error);
// Find Email Edit View control by ID
emailET = (EditText) findViewById(R.id.txt_email);
// Find Password Edit View control by ID
pwdET = (EditText) findViewById(R.id.txt_pwd);
// Instantiate Progress Dialog object
prgDialog = new ProgressDialog(this);
// Set Progress Dialog Text
prgDialog.setMessage("Please wait...");
// Set Cancelable as False
prgDialog.setCancelable(false);
button = (Button) findViewById(R.id.btlogin);
final Button button = (Button) findViewById(R.id.btlogin);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
try {
// Get Email Edit View Value
String email = emailET.getText().toString();
// Get Password Edit View Value
String password = pwdET.getText().toString();
// When Email Edit View and Password Edit View have values
// other than Null
if (Utility.isNotNull(email) && Utility.isNotNull(password)) {
// When Email entered is Valid
if (Utility.validate(email)) {
new LoginAsyncTask(LoginActivity.this).execute(
email, password);
Toast.makeText(getApplicationContext(),
"Asynctask started", Toast.LENGTH_SHORT)
.show();
}
// When Email is invalid
else {
Toast.makeText(getApplicationContext(),
"Please enter valid email",
Toast.LENGTH_LONG).show();
}
}
// When any of the Edit View control left blank
else {
Toast.makeText(
getApplicationContext(),
"Please fill the form, don't leave any field blank",
Toast.LENGTH_LONG).show();
}
} catch (Exception ex) {
}
}
});
TextView registerScreen = (TextView) findViewById(R.id.link_to_register);
// Listening to register new account link
registerScreen.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Switching to Register screen
Intent i = new Intent(getApplicationContext(),
RegisterActivity.class);
startActivity(i);
}
});
}
public class LoginAsyncTask extends AsyncTask<String, Integer, JSONObject> {
private JSONObject responseJson = null;
private Context contxt;
private Activity activity;
public LoginAsyncTask(Context context) {
// API = apiURL;
this.contxt = context;
}
// async task to accept string array from context array
#Override
protected JSONObject doInBackground(String... params) {
String path = null;
String response = null;
HashMap<String, String> request = null;
JSONObject requestJson = null;
DefaultHttpClient httpClient = null;
HttpPost httpPost = null;
StringEntity requestString = null;
ResponseHandler<String> responseHandler = null;
// get the username and password
Log.i("Email", params[0]);
Log.i("Password", params[1]);
try {
path = "http://192.168.0.xxx/xxxxxxx/xxxxxx/UserAuthentication";
new URL(path);
} catch (MalformedURLException e) {
e.printStackTrace();
}
try {
// set the API request
request = new HashMap<String, String>();
request.put(new String("Email"), params[0]);
request.put(new String("Password"), params[1]);
request.entrySet().iterator();
// Store locations in JSON
requestJson = new JSONObject(request);
httpClient = new DefaultHttpClient();
httpPost = new HttpPost(path);
requestString = new StringEntity(requestJson.toString());
// sets the post request as the resulting string
httpPost.setEntity(requestString);
httpPost.setHeader("Content-type", "application/json");
// Handles the response
responseHandler = new BasicResponseHandler();
response = httpClient.execute(httpPost, responseHandler);
responseJson = new JSONObject(response);
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
try {
responseJson = new JSONObject(response);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
return responseJson;
}
#Override
protected void onPostExecute(JSONObject result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
String myResJson;
try {
myResJson = responseJson.getString("status");
String test = myResJson;
if (test.equals("200")) {
Intent intent = new Intent(contxt, ActivityMenu.class);
contxt.startActivity(intent);
} else {
Intent intent = new Intent(contxt, LoginActivity.class);
contxt.startActivity(intent);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
After some research I was able to come up with this code to do the remember me option using shared preference.
public class MainActivity extends Activity {
public static String PREFS_NAME = "mypre";
public static String PREF_EMAIL = "email";
public static String PREF_PASSWORD = "password";
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
}
#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;
}
public void onStart() {
super.onStart();
// read email and password from SharedPreferences
getUser();
}
public void doLogin(View view) {
EditText txtuser = (EditText) findViewById(R.id.txt_user);
EditText txtpwd = (EditText) findViewById(R.id.txt_pwd);
String email = "u";
String password = "p";
if (txtuser.getText().toString().equals(email)
&& txtpwd.getText().toString().equals(password)) {
CheckBox ch = (CheckBox) findViewById(R.id.ch_rememberme);
if (ch.isChecked())
rememberMe(email, password); // save email and password
// show logout activity
showLogout(email);
} else {
Toast.makeText(this, "Invalid email or password", Toast.LENGTH_LONG)
.show();
}
}
public void getUser() {
SharedPreferences pref = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
String email = pref.getString(PREF_EMAIL, null);
String password = pref.getString(PREF_PASSWORD, null);
if (email != null || password != null) {
// directly show logout form
showLogout(email);
}
}
public void rememberMe(String user, String password) {
// save email and password in SharedPreferences
getSharedPreferences(PREFS_NAME, MODE_PRIVATE).edit()
.putString(PREF_EMAIL, user).putString(PREF_PASSWORD, password)
.commit();
}
public void showLogout(String email) {
// display log out activity
Intent intent = new Intent(this, ActivityMenu.class);
intent.putExtra("user", email);
startActivity(intent);
}
}
I need help to integrate these 2 classes. I tried but didn't work
this is my out put
public class LoginActivity extends Activity {
ProgressDialog prgDialog;
// Error Msg TextView Object
TextView errorMsg;
// Email Edit View Object
EditText emailET;
// Passwprd Edit View Object
EditText pwdET;
String email;
// Get Password Edit View Value
String password;
Button button;
public static String PREFS_NAME = "mypre";
public static String PREF_EMAIL = "email";
public static String PREF_PASSWORD = "password";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_login);
// Find Error Msg Text View control by ID
errorMsg = (TextView) findViewById(R.id.login_error);
// Find Email Edit View control by ID
emailET = (EditText) findViewById(R.id.txt_user);
// Find Password Edit View control by ID
pwdET = (EditText) findViewById(R.id.txt_pwd);
// Instantiate Progress Dialog object
prgDialog = new ProgressDialog(this);
// Set Progress Dialog Text
prgDialog.setMessage("Please wait...");
// Set Cancelable as False
prgDialog.setCancelable(false);
button = (Button) findViewById(R.id.btlogin);
final Button button = (Button) findViewById(R.id.btlogin);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
try {
// Get Email Edit View Value
String email = emailET.getText().toString();
// Get Password Edit View Value
String password = pwdET.getText().toString();
// When Email Edit View and Password Edit View have values
// other than Null
if (Utility.isNotNull(email) && Utility.isNotNull(password)) {
// When Email entered is Valid
if (Utility.validate(email)) {
if (emailET.getText().toString().equals(email)
&& pwdET.getText().toString()
.equals(password)) {
CheckBox ch = (CheckBox) findViewById(R.id.ch_rememberme);
if (ch.isChecked())
rememberMe(email, password); // save email
// and
// password
// show logout activity
showLogout(email);
}
new LoginAsyncTask(LoginActivity.this).execute(
email, password);
Toast.makeText(getApplicationContext(),
"Asynctask started", Toast.LENGTH_SHORT)
.show();
}
// When Email is invalid
else {
Toast.makeText(getApplicationContext(),
"Please enter valid email",
Toast.LENGTH_LONG).show();
}
}
// When any of the Edit View control left blank
else {
Toast.makeText(
getApplicationContext(),
"Please fill the form, don't leave any field blank",
Toast.LENGTH_LONG).show();
}
} catch (Exception ex) {
}
}
});
TextView registerScreen = (TextView) findViewById(R.id.link_to_register);
// Listening to register new account link
registerScreen.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Switching to Register screen
Intent i = new Intent(getApplicationContext(),
RegisterActivity.class);
startActivity(i);
}
});
}
public void onStart() {
super.onStart();
// read email and password from SharedPreferences
getUser();
}
public void getUser() {
SharedPreferences pref = getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
String email = pref.getString(PREF_EMAIL, null);
String password = pref.getString(PREF_PASSWORD, null);
if (email != null || password != null) {
// directly show logout form
showLogout(email);
}
}
public void rememberMe(String user, String password) {
// save email and password in SharedPreferences
getSharedPreferences(PREFS_NAME, MODE_PRIVATE).edit()
.putString(PREF_EMAIL, user).putString(PREF_PASSWORD, password)
.commit();
}
public void showLogout(String email) {
// display log out activity
Intent intent = new Intent(this, ActivityMenu.class);
intent.putExtra("user", email);
startActivity(intent);
}
public class LoginAsyncTask extends AsyncTask<String, Integer, JSONObject> {
private JSONObject responseJson = null;
private Context contxt;
private Activity activity;
public LoginAsyncTask(Context context) {
// API = apiURL;
this.contxt = context;
}
// async task to accept string array from context array
#Override
protected JSONObject doInBackground(String... params) {
String path = null;
String response = null;
HashMap<String, String> request = null;
JSONObject requestJson = null;
DefaultHttpClient httpClient = null;
HttpPost httpPost = null;
StringEntity requestString = null;
ResponseHandler<String> responseHandler = null;
// get the email and password
Log.i("Email", params[0]);
Log.i("Password", params[1]);
try {
path = "http://192.168.0.xxx/xxxxxxxx/xxxxx/UserAuthentication";
new URL(path);
} catch (MalformedURLException e) {
e.printStackTrace();
}
try {
// set the API request
request = new HashMap<String, String>();
request.put(new String("Email"), params[0]);
request.put(new String("Password"), params[1]);
request.entrySet().iterator();
// Store locations in JSON
requestJson = new JSONObject(request);
httpClient = new DefaultHttpClient();
httpPost = new HttpPost(path);
requestString = new StringEntity(requestJson.toString());
// sets the post request as the resulting string
httpPost.setEntity(requestString);
httpPost.setHeader("Content-type", "application/json");
// Handles the response
responseHandler = new BasicResponseHandler();
response = httpClient.execute(httpPost, responseHandler);
responseJson = new JSONObject(response);
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
try {
responseJson = new JSONObject(response);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
return responseJson;
}
#Override
protected void onPostExecute(JSONObject result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
String myResJson;
try {
myResJson = responseJson.getString("status");
String test = myResJson;
if (test.equals("200")) {
Intent intent = new Intent(contxt, ActivityMenu.class);
contxt.startActivity(intent);
} else {
Intent intent = new Intent(contxt, LoginActivity.class);
contxt.startActivity(intent);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
HI i have been trying to pass values from android form to php page through json and get the result through JSON i have got an example and implemented it. In that example i am passing username and password entered in android form to php page through json in the page it is retrieving the role of the details passed form database and passing the result to android class and my function is setting the retrieved value to a text filed and the result is displayed in the particular text field. Now want i want is i want to return the result as a String and retrieve it in MainActivity. I'm pasting the code below. Please help me.
MainActivity.class
public class MainActivity extends ActionBarActivity {
private EditText usernameField,passwordField,role;
private TextView status,method;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
usernameField = (EditText)findViewById(R.id.editText1);
passwordField = (EditText)findViewById(R.id.editText2);
role = (EditText)findViewById(R.id.editText3);
}
public void login(View view){
String username = usernameField.getText().toString();
String password = passwordField.getText().toString();
//method.setText("Get Method");
new SigninActivity(this,role,0).execute(username,password);
}
SigninActivity.class
public class SigninActivity extends AsyncTask<String,Void,String>{
private EditText roleField;
private Context context;
private int byGetOrPost = 0;
private static InputStream is;
//JSONObject jsonParser;
public SigninActivity(Context context,EditText roleField,int flag) {
this.context = context;
this.roleField = roleField;
this.is=null;
// this.jsonParser= new JSONObject();
}
#Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
try{
String username = (String)arg0[0];
String password = (String)arg0[1];
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("name", username));
params.add(new BasicNameValuePair("password", password));
/////////////////////////////////////////////////////////////////////////////
String link = "http://Myapp.com/login.php";
//URL url = new URL(link);
DefaultHttpClient httpClient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(params, "utf-8");
link+= "?" + paramString;
HttpGet httpGet = new HttpGet(link);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
StringBuilder sb = new StringBuilder();;
/////////////////////////////////////////////////////////////////////////////
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
String json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
return sb.toString();
}catch(Exception e){
return new String("Exception:-- " + e.getMessage());
}
}
protected void onPostExecute(String result){
this.roleField.setText(result);
}
}
Here the result is retrieved and set to the text filed in onPostExecute() function in SigninActivity class itself what i want to do is i want the value to be returned in MainActivity as a String to do further manipulations instead of using a textView
Its very simple
Use this for sending in the next activity
resp = new JSONObject(result);
JSONObject Login1Result = resp.getJSONObject("LoginResult");
String strMessage = Login1Result.getString("EmployeeID");
JSONObject status = Login1Result.getJSONObject("status");
if (status.getString("message").equalsIgnoreCase("OK"))
{
Intent i = new Intent(getApplicationContext(), next.class);
i.putExtra("new_variable_name",strMessage);
startActivity(i);
for getting it in next activity
{
Bundle extras = getIntent().getExtras();
String strEmployeeID="";
if (extras != null)
{
String value = extras.getString("new_variable_name");
strEmployeeID = value;
}
Intent i = new Intent(getApplicationContext(), nextTonext.class);
i.putExtra("new_variable_name",strEmployeeID);
startActivity(i);
}
You can try SharedPreferences, it's easy to use and quite powerful You can find it here
I have an async task which populates a spinner with data. The spinner data comes from objects in a list. My problem is when I set the onclick listener for the items in the list I also want the id from the object not just the name:
public class PortfolioGetAllLists extends AsyncTask<String, Void, String> {
Context c;
PortfolioGetAllBeers.OnArticleSelectedListener useThis;
private ProgressDialog Dialog;
public PortfolioGetAllLists (Context context, PortfolioGetAllBeers.OnArticleSelectedListener thisListener)
{
c = context;
useThis = thisListener;
Dialog = new ProgressDialog(c);
}
#Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
return readJSONFeed(arg0[0]);
}
protected void onPreExecute() {
Dialog.setMessage("Getting Brewery List");
Dialog.setTitle("Loading");
Dialog.setCancelable(false);
Dialog.show();
}
protected void onPostExecute(String result){
//decode json here
try{
JSONArray jsonArray = new JSONArray(result);
//acces listview
final ListView lv = (ListView) ((Activity) c).findViewById(R.id.allYourBeersList);
//make array list for beer
final List<String> tasteList = new ArrayList<String>();
tasteList.add("");
for(int i = 0; i < jsonArray.length(); i++) {
String bID = jsonArray.getJSONObject(i).getString("id");
String beer = jsonArray.getJSONObject(i).getString("name");
String rate = "na";
String beerID = "na";
//create object
ShortBeerInfo tempTaste = new ShortBeerInfo(beer, rate, beerID, bID);
//add to arraylist
tasteList.add(beer);
}
// Selection of the spinner
Spinner spinner = (Spinner) ((Activity) c).findViewById(R.id.portfolioSpinner2);
// Application of the Array to the Spinner
ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(c, android.R.layout.simple_spinner_item,tasteList );
spinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); // The drop down view
spinner.setAdapter(spinnerArrayAdapter);
//add on item selected
final Spinner portfolioType = (Spinner) ((Activity) c).findViewById(R.id.portfolioSpinner2);
portfolioType.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
String portfolioChoice = portfolioType.getSelectedItem().toString();
//Toast.makeText(((Activity) c).getApplicationContext(), portfolioChoice, Toast.LENGTH_LONG).show();
lv.setAdapter(null);
//get brewery beers
//get userID
//get user data
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(selectedItemView.getContext());
String userID = prefs.getString("userID", null);
try {
portfolioChoice = URLEncoder.encode(portfolioChoice, "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
//construct url
String url = "myURL";
Log.d("portfolio", url);
//async task goes here
//new PortfolioGetAllBeers(selectedItemView.getContext()).execute(url);
PortfolioGetAllBeers task = new PortfolioGetAllBeers(c);
task.setOnArticleSelectedListener(useThis);
task.execute(url);
}
#Override
public void onNothingSelected(AdapterView<?> parentView) {
// do nothing
}
});
}
catch(Exception e){
}
Dialog.dismiss();
}
public String readJSONFeed(String URL) {
StringBuilder stringBuilder = new StringBuilder();
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(URL);
try {
HttpResponse response = httpClient.execute(httpGet);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) {
HttpEntity entity = response.getEntity();
InputStream inputStream = entity.getContent();
BufferedReader reader = new BufferedReader(
new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
stringBuilder.append(line);
}
inputStream.close();
} else {
Log.d("JSON", "Failed to download file");
}
} catch (Exception e) {
Log.d("readJSONFeed", e.getLocalizedMessage());
}
return stringBuilder.toString();
}
}
This line below is the line which get the beers name, but I do not know how to get also the id from the object which sets the listview name:
String portfolioChoice = portfolioType.getSelectedItem().toString();
Update:
I have changed my above code to this to incorporate a custom adapter:
public class PortfolioGetAllLists extends AsyncTask<String, Void, String> {
Context c;
PortfolioGetAllBeers.OnArticleSelectedListener useThis;
private ProgressDialog Dialog;
public PortfolioGetAllLists (Context context, PortfolioGetAllBeers.OnArticleSelectedListener thisListener)
{
c = context;
useThis = thisListener;
Dialog = new ProgressDialog(c);
}
#Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
return readJSONFeed(arg0[0]);
}
protected void onPreExecute() {
Dialog.setMessage("Getting Brewery List");
Dialog.setTitle("Loading");
Dialog.setCancelable(false);
Dialog.show();
}
protected void onPostExecute(String result){
//decode json here
try{
JSONArray jsonArray = new JSONArray(result);
//acces listview
final ListView lv = (ListView) ((Activity) c).findViewById(R.id.allYourBeersList);
//make array list for beer
final List<ShortBeerInfo> tasteList = new ArrayList<ShortBeerInfo>();
//tasteList.add("");
for(int i = 0; i < jsonArray.length(); i++) {
String bID = jsonArray.getJSONObject(i).getString("id");
String beer = jsonArray.getJSONObject(i).getString("name");
String rate = "na";
String beerID = "na";
//create object
ShortBeerInfo tempTaste = new ShortBeerInfo(beer, rate, beerID, bID);
//add to arraylist
tasteList.add(tempTaste);
}
// Selection of the spinner
Spinner spinner = (Spinner) ((Activity) c).findViewById(R.id.portfolioSpinner2);
// Application of the Array to the Spinner
ShortBeerInfoAdapter<ShortBeerInfo> spinnerArrayAdapter = new ArrayAdapter<ShortBeerInfo>(c, android.R.layout.simple_spinner_item,tasteList );
spinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); // The drop down view
spinner.setAdapter(spinnerArrayAdapter);
//add on item selected
final Spinner portfolioType = (Spinner) ((Activity) c).findViewById(R.id.portfolioSpinner2);
portfolioType.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int position, long id) {
String portfolioChoice = portfolioType.getSelectedItem().toString();
//Toast.makeText(((Activity) c).getApplicationContext(), portfolioChoice, Toast.LENGTH_LONG).show();
lv.setAdapter(null);
//get brewery beers
//get userID
//get user data
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(selectedItemView.getContext());
String userID = prefs.getString("userID", null);
try {
portfolioChoice = URLEncoder.encode(portfolioChoice, "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
//construct url
String url = "myURL";
Log.d("portfolio", url);
//async task goes here
//new PortfolioGetAllBeers(selectedItemView.getContext()).execute(url);
PortfolioGetAllBeers task = new PortfolioGetAllBeers(c);
task.setOnArticleSelectedListener(useThis);
task.execute(url);
}
#Override
public void onNothingSelected(AdapterView<?> parentView) {
// do nothing
}
});
}
catch(Exception e){
}
Dialog.dismiss();
}
public String readJSONFeed(String URL) {
StringBuilder stringBuilder = new StringBuilder();
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(URL);
try {
HttpResponse response = httpClient.execute(httpGet);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) {
HttpEntity entity = response.getEntity();
InputStream inputStream = entity.getContent();
BufferedReader reader = new BufferedReader(
new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
stringBuilder.append(line);
}
inputStream.close();
} else {
Log.d("JSON", "Failed to download file");
}
} catch (Exception e) {
Log.d("readJSONFeed", e.getLocalizedMessage());
}
return stringBuilder.toString();
}
}
but on this line:
ShortBeerInfoAdapter<ShortBeerInfo> spinnerArrayAdapter = new ArrayAdapter<ShortBeerInfo>(c, android.R.layout.simple_spinner_item,tasteList );
I am getting shortbeerinfoadapter does not have type parameters
my short beer info adapter is:
public class ShortBeerInfoAdapter extends ArrayAdapter<ShortBeerInfo> {
Context context;
int layoutResourceId;
List<ShortBeerInfo> data = null;
public ShortBeerInfoAdapter(Context context, int layoutResourceId, List<ShortBeerInfo> data) {
super(context, layoutResourceId, data);
this.layoutResourceId = layoutResourceId;
this.context = context;
this.data = data;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
beerHolder holder = null;
if(row == null)
{
LayoutInflater inflater = ((Activity)context).getLayoutInflater();
row = inflater.inflate(layoutResourceId, parent, false);
holder = new beerHolder();
holder.txtBeer = (TextView)row.findViewById(R.id.breweryName);
holder.txtRate = (TextView)row.findViewById(R.id.breweryRate);
holder.txtBar = (RatingBar) row.findViewById(R.id.starbar);
row.setTag(holder);
}
else
{
holder = (beerHolder)row.getTag();
}
ShortBeerInfo beer = data.get(position);
holder.txtBeer.setText(beer.beer);
holder.txtRate.setText(beer.rate + " out of 5.00 Stars");
holder.numHolder= Float.parseFloat(beer.rate);
holder.txtBar.setNumStars(5);
holder.txtBar.setRating(holder.numHolder);
return row;
}
static class beerHolder
{
TextView txtBeer;
TextView txtRate;
RatingBar txtBar;
Float numHolder;
}
}
You have your ShortBeerInfo, which includes the name and ID. You take the beer name, add it to a list of strings, then create the ArrayAdapter from that list. The ArrayAdapter only contains the names.
To get the ID you will need a custom array adapter of type ShortBeerInfo. You'll need to override OnCreateView in the adapter to create the View object for the list item that only contains the beer name. (Or any other beer info you may want to display)
Then in your selection listener getSelectedItem will return a ShortBeerInfo, containing the ID of the selected beer.