public function in class doesn't work properly - android

I have a "movie" class and a public function getName(), but the function doesn't return anything, and the logcat is just blank.
public class movie {
public String name45;
int dvd_no ;
public void addData( String name1 , int dvd_no1)
{
this.name45=name1 ;
this.dvd_no = dvd_no1 ;
Log.d("constructor name1", name1);
Log.d("constructor name45", name45);
}
public String getName()
{
return name45 ;
}
}
This is an activity which uses this method - the list always has blank entries.
public class MoviesList extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.movieslist);
ListView lvAllMoviesList = (ListView)findViewById(R.id.allmovieslist);
ArrayList<String> moviesNames = new ArrayList<String>();
// go through list of members and compare name with given name
for(movie movie : MovieReg_activity.movies) {
String name = movie.getName();
Log.d("Movie Name list", movie.getName());
moviesNames.add(name);
}
ArrayAdapter<String> AllMovieList = new ArrayAdapter<String>(MoviesList.this,android.R.layout.simple_list_item_1, moviesNames);
lvAllMoviesList.setAdapter(AllMovieList);
}
}
the code which generate objects and add values to it
public class MovieReg_activity extends Activity {
public static List<movie> movies = new ArrayList<movie>();
String movName ;
int dvdNo ;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.mov_reg_layout);
EditText etmovie_name = (EditText)findViewById(R.id.etmovname);
EditText etdvd_no = (EditText)findViewById(R.id.etdvds);
Button btMovie_submit = (Button)findViewById(R.id.btmovsubmit);
movName= etmovie_name.getText().toString();
// dvdNo = Integer.parseInt(etdvd_no.getText().toString()); // to string then to int :)
btMovie_submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int x=0 ;
movie movie = new movie() ;
movie.addData(movName, dvdNo);
movies.add(x,movie );
x++ ;
int size =movies.size() ;
Toast.makeText(MovieReg_activity.this, "no of movies added :"+size , Toast.LENGTH_SHORT).show();
}
});
}
}

You are setting the TAG parameter for the logs to the first string, try:
Log.d("DEBUG", "constructor name1 " + name1);
Log.d("DEBUG", "constructor name45 " + name45);
And then set your logcat filter to DEBUG

The problem was in taking the data from the user in the MovieReg_activity
and its solved by putting those two lines
EditText etmovie_name = (EditText)findViewById(R.id.etmovname);
movName= etmovie_name.getText().toString();
inside the button listener to be like this
public void onClick(View v) {
int x=0 ;
EditText etmovie_name = (EditText)findViewById(R.id.etmovname);
movName= etmovie_name.getText().toString();
movies.add(new movie(movName , dvdNo) );
String name3= movie.getName() ;
x++ ;
int size =movies.size() ;
Toast.makeText(MovieReg_activity.this, "no of movies added :"+size , Toast.LENGTH_SHORT).show();
}
});

Related

API should return data in JSON but not shown in layout

I am trying to pass my json response to an adapter class, i am getting response from the rest api but still the json object array is not passing to the adapter class after the retrofit handler class converts the json response into object array. i am not getting any log error or warning but when i try to use this activty in my android app i am getting no results.
public class HistoryActivity extends AppBaseActivity {
#BindView(R.id.history_header)
RelativeLayout history_header;
#BindView(R.id.history_list)
ListView history_list;
#BindView(R.id.no_history_view)
LinearLayout no_history_view;
#BindView(R.id.hdr_back)
TextView hdr_back;
private String address;
private String category;
private String distance;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_history);
unbinder= ButterKnife.bind(this);
backBtnSet();
updateHeader();
Intent intent=getIntent();
if(intent!=null && intent.hasExtra("mid")){
String mId=intent.getStringExtra("mid");
address=intent.getStringExtra("address");
category=intent.getStringExtra("category");
distance=intent.getStringExtra("distance");
fetchHistory(mId);
}else {
activityFinish();
}
}
private void backBtnSet() {
final int height= (int) getResources().getDimension(R.dimen.dp_24);
hdr_back.getViewTreeObserver()
.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
Drawable img = getBaseContext().getResources().getDrawable(
R.drawable.ic_backarrow);
img.setBounds(0, 0, height,
height);
hdr_back.setCompoundDrawables(img, null, null, null);
hdr_back.getViewTreeObserver().removeOnGlobalLayoutListener(this);
}
});
}
private void updateHeader() {
TextView hView= history_header.findViewById(R.id.hdr_title);
hView.setText(getString(R.string.history_small));
}
private void fetchHistory(String mId) {
JsonObject jObject=ParamConvertor.getCustomerHistory(userInfo.getId(),
userInfo.getAccessKey(),mId);
Call<ArrayList<HistoryCustomer>> call=apiService.getCustomerHistory(jObject);
call.enqueue(new RetrofitHandlerFull<ArrayList<HistoryCustomer>>(this,
networkHandler,1));
AppLogger.printPostBodyCall(call);
}
//Problem persists from here
private INetworkHandler<ArrayList<HistoryCustomer>> networkHandler
= new INetworkHandler<ArrayList<HistoryCustomer>>() {
#Override
public void onResponse(ArrayList<HistoryCustomer> data, String msg, int num) {
if(data!=null && !data.isEmpty()){
updateList(data);
dataPresent(true);
}else{
dataPresent(false);
}
}
#Override
public void onFailure(String msg, int error) {
dataPresent(false);
}
};
private void updateList(ArrayList<HistoryCustomer> data){
HistoryAdapter adapter=new HistoryAdapter(this,data,
address,category);
history_list.setAdapter(adapter);
}
private void dataPresent(boolean isPresent){
if(isPresent){
no_history_view.setVisibility(View.GONE);
history_list.setVisibility(View.VISIBLE);
}else{
no_history_view.setVisibility(View.VISIBLE);
history_list.setVisibility(View.GONE);
}
}
#OnClick(R.id.hdr_back)
void onCLicks(View view){
switch (view.getId()){
case R.id.hdr_back:
activityFinish();
break;
}
}
}
As per your code, it seems fine to me can you check your endpoint which you are calling may be it might returning null or empty object.

Can't pass multi integers at the same time in intent

So I want to pass the data between the activities,so I've make that there's 3 separate integers should be send to the second activity,but i don't know why,the emulator keeps adding all of them. Basically,I making an app, at case of my course - i need to create an app that keeping score,in my case,app would keep the score,number of fouls,and number of corners during the football match. To set the data,we are clicking in special button (press score to increment score etc.) when we want to go to the second activity and see the detailed statistics we should see like 3 goals,6 fouls,and like 2 corners for team "A" during the match,but when i clicking in buttons (suppose that is 1 time for goal,2 times for fouls,and 3 times for corner the app should be like 1 goal,2 fouls,3 corner's but it keep adding all of integers,and it's like 6 goals,6 fouls,6 corners. What can be wrong?
Count activity (here program storage the value of integers)
public class CountActivity extends AppCompatActivity {
public int team_a_score;
public int team_a_foul;
public int team_a_corner;
public int team_b_score;
public int team_b_foul;
public int team_b_corner;
private Button goToDetailedStats;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_count);
goToDetailedStats = (Button) findViewById(R.id.go_to_stats);
goToDetailedStats.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
openDetailedScore();
}
});
}
private void openDetailedScore() {
Intent intent = new Intent(this,DeatiledScoreActivity.class);
intent.putExtra("",team_a_score);
intent.putExtra("",team_a_foul);
intent.putExtra("",team_a_corner);
startActivity(intent);
}
public void resetScore(View view) {
team_a_score = 0;
display_a_score(team_a_score);
team_b_score = 0;
display_b_score(team_b_score);
}
private void display_a_score (int a_score){
TextView team_a_score_tv = (TextView) findViewById(R.id.team_a_score_tv);
team_a_score_tv.setText(String.valueOf(a_score));
}
private void display_b_score (int b_score){
TextView team_b_score_tv = (TextView) findViewById(R.id.team_b_score_tv);
team_b_score_tv.setText(String.valueOf(b_score));
}
public void increment_a_score(View view) {
team_a_score = team_a_score+1;
display_a_score(team_a_score);
}
public void increment_a_foul(View view) {
team_a_foul = team_a_foul+1;
}
public void increment_a_corner(View view) {
team_a_corner = team_a_corner+1;
}
public void increment_b_score(View view) {
team_b_score = team_b_score+1;
display_b_score(team_b_score);
}
public void increment_b_foul(View view) {
team_b_foul = team_b_foul+1;
}
public void increment_b_corner(View view) {
team_b_corner = team_b_corner+1;
}
}
Detailed activity have to receive data that we send as intent from Counting activity.
public class DeatiledScoreActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_deatiled_score);
int team_a_score_detail_int = 0;
int team_a_foul_detail_int = 0;
int team_a_corner_detail_int = 0;
int team_b_score_detail_int = 0;
int team_b_foul_detail_int = 0;
int team_b_corner_detail_int = 0;
Intent goal_intent = getIntent();
int goal = goal_intent.getIntExtra("", team_a_score_detail_int);
display_a_goal(goal);
Intent foul_intent = getIntent();
int foul = foul_intent.getIntExtra("", team_a_foul_detail_int);
display_a_foul(foul);
Intent corner_intent = getIntent();
int corner = corner_intent.getIntExtra("", team_a_corner_detail_int);
display_a_corner(corner);
}
public void display_a_goal(int score) {
TextView a_score = (TextView) findViewById(R.id.team_a_goal_detail);
a_score.setText(String.valueOf(score));
}
public void display_a_foul(int foul){
TextView a_foul = (TextView) findViewById(R.id.team_a_foul_detail);
a_foul.setText(String.valueOf(foul));
They cannot have the same key:
intent.putExtra("",team_a_score);
intent.putExtra("",team_a_foul);
intent.putExtra("",team_a_corner);
So in order to make it work set:
intent.putExtra("some",team_a_score);
intent.putExtra("some2",team_a_foul);
intent.putExtra("some4",team_a_corner);
Intent putExtra method accepts two arguments key - value.

Inner class issue when using onclicklistener

I keep getting repeated issues with: variable is accessed from within inner class
every time i want to use an object etc from an onclicklistener etc.
I know the problem is that its not set to final, but if i set to final im not able to do anything to it before pressing the onclicklistener button...
Example i have an EditText field, which is filled with getText from an object, then i want to press an apply button and the object with the new text from the textfield.
This doesnt work when the object need to be final for the "inner class" to use it.
How do i best handle this? i keep running into this bloody phenonemon...
public class EditPicture extends Activity{
private EditText text;
private Button applyBtn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
UUID itemID = (UUID)getIntent().getSerializableExtra("itemUUID");
PictureItem pi = new PictureItem("","");
final ArrayList<PictureItem> tempArray = PictureTalkFragment.array;
for(int i = 0; i < tempArray.size(); i++){
if(itemID.equals(tempArray.get(i).getId())){
pi = tempArray.get(i);
tempArray.remove(i);
}
}
setContentView(R.layout.picturetalk_edit_pic);
text = (EditText)findViewById(R.id.editName);
text.setText(pi.getTitle());
applyBtn = (Button)findViewById(R.id.applyChangeBtn);
applyBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
tempArray.add(pi);
}
});
}
}
you should define tempArray variable outside of onCreate method.
public class EditPicture extends Activity{
private EditText text;
private Button applyBtn;
ArrayList<PictureItem> tempArray
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
UUID itemID = (UUID)getIntent().getSerializableExtra("itemUUID");
PictureItem pi = new PictureItem("","");
tempArray = PictureTalkFragment.array;
for(int i = 0; i < tempArray.size(); i++){
if(itemID.equals(tempArray.get(i).getId())){
pi = tempArray.get(i);
tempArray.remove(i);
}
}
setContentView(R.layout.picturetalk_edit_pic);
text = (EditText)findViewById(R.id.editName);
text.setText(pi.getTitle());
applyBtn = (Button)findViewById(R.id.applyChangeBtn);
applyBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
tempArray.add(pi);
}
});
}
}
The problem is that you add th picture to a temporary array which is not accesible when you click on it. I think that you can do something like this to define the array outside the inCreate function.
public class EditPicture extends Activity{
private EditText text;
private Button applyBtn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
UUID itemID = (UUID)getIntent().getSerializableExtra("itemUUID");
PictureItem pi = new PictureItem("","");
final ArrayList<PictureItem> tempArray = PictureTalkFragment.array;
for(int i = 0; i < tempArray.size(); i++){
if(itemID.equals(tempArray.get(i).getId())){
pi = tempArray.get(i);
tempArray.remove(i);
}
}
setContentView(R.layout.picturetalk_edit_pic);
text = (EditText)findViewById(R.id.editName);
text.setText(pi.getTitle());
applyBtn = (Button)findViewById(R.id.applyChangeBtn);
applyBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(PictureTalkFragment.array != null){
PictureTalkFragment.array.add(pi);
}
}
});
}
}

Repeat AsyncTask on the next code

I have a code that only takes information from a web vía Jsoup and I want to refresh this information every second. I tried with all the code that I've found in Google and stackoverflow with no luck. Thank you very much in advance. [SOLVED]
Now I'm trying to send an array from MainActivity to another Activity called "Activity_allday" with Bundle and Intent when viewallday() function is called pressing the "btviewallday" button but with no luck. Any suggestions?
LogCat error: Could not find a method viewallday(View) in the activity class com.example.Chispa.MainActivity for onClick handler on view class android.widget.Button with id 'btviewallday'.
I've noticed that the error comes from receiving two values at viewallday(View view, Pair p). How can I receive the "Pair p" value in my viewallday function?
Here is the new app code:
[MainActivity]
public class MainActivity extends Activity {
private TextView tvmax, tvmid, tvmin, tvactualval,tvvaloractual,tvdate;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvdate=(TextView)findViewById(R.id.tvdate);
tvvaloractual=(TextView)findViewById(R.id.tvvaloractual);
tvmax=(TextView)findViewById(R.id.tvmaximo);
tvmid=(TextView)findViewById(R.id.tvmedio);
tvmin=(TextView)findViewById(R.id.tvminimo);
new BackGroundTask().execute();
callAsynchronousTask();
}
public void callAsynchronousTask() {
final Handler handler = new Handler();
Timer timer = new Timer();
TimerTask doAsynchronousTask = new TimerTask() {
#Override
public void run() {
handler.post(new Runnable() {
public void run() {
try {
BackGroundTask performBackgroundTask = new BackGroundTask();
// PerformBackgroundTask this class is the class that extends AsynchTask
performBackgroundTask.execute();
} catch (Exception e) {
// TODO Auto-generated catch block
}
}
});
}
};
timer.schedule(doAsynchronousTask, 0, 1000); //execute in every 1000 ms
}
#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 class Pair
{
public String[] bar;
public String[] values;
}
public void viewallday(View view, Pair p) {
Intent intent = new Intent(this, Activity_allday.class);
Bundle bundle =new Bundle();
bundle.putStringArray("bar", p.bar);
intent.putExtras(bundle);
startActivity(intent);
}
class BackGroundTask extends AsyncTask<Void, Void, Pair> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
public String[] getValuesGraph(Document doc) {
int cont=24,var=7;
String bar[] = new String[cont];
/*
* Getting elements from the graphic in an array from 0-23. 0 it's 1:00am, 23 it's 00:00am
*/
for (cont=0; cont < 24; cont++){
String onMouseOver = doc.select("a").get(var+cont).attr("onMouseOver");
bar[cont] = onMouseOver.split("'")[9];
}
return bar;
}
public String[] getValuesFooter(Document doc) {
String values[] = new String[7];
/*
* Getting elements from the graphic footer
*/
String delimiters= "[ /]+";
Elements elements = doc.select("td.cabeceraRutaTexto");
elements.size(); // 6
/* Getting text from table */
values[0] = elements.get(0).text(); // TITLE
values[1] = elements.get(1).text(); // TEXT MAX VALUE
values[2] = elements.get(2).text(); // TEXT MIDDLE VALUE
values[3] = elements.get(3).text(); // TEXTO MIN VALUE
/* Getting numbers from table */
values[4] = elements.get(4).text().split(delimiters)[0]; // NUMBER MAX VALUE
values[5] = elements.get(5).text().split(delimiters)[0]; // NUMBER MIDDLE VALUE
values[6] = elements.get(6).text().split(delimiters)[0]; // NUMBER MIN VALUE
return values;
}
#Override
public Pair doInBackground(Void... params) {
Pair p = new Pair();
try {
URL url= new URL("http://www.myweb.com");
Document doc = Jsoup.connect(url.toString()).get();
p.bar = getValuesGraph(doc);
p.values = getValuesFooter(doc);
/*
* Getting elements from the graphic in an array from 0-23. 0 it's 1:00am, 23 it's 00:00am
*/
return p;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
public String ActualHourValue() {
Format formatter = new SimpleDateFormat("H");
String onlyhour = formatter.format(new Date());
return onlyhour;
}
public void ShowDateHour(){
Calendar c = Calendar.getInstance();
SimpleDateFormat df3 = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss a");
String formattedDate3 = df3.format(c.getTime());
tvdate.setText("Fecha y hora actuales : "+formattedDate3);
}
#Override
protected void onPostExecute(Pair p) {
int hour = Integer.parseInt(ActualHourValue());
tvvaloractual.setText(p.bar[hour]+" €/MWh");
tvmax.setText(p.values[4]+" €/MWh");
tvmid.setText(p.values[5]+" €/MWh");
tvmin.setText(p.values[6]+" €/MWh");
ShowDateHour();
/*super.onPostExecute(p.values);*/
}
}
}
[Activity_allday]
Public class Activity_allday extends MainActivity {
private TextView tvall;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.all_day_prices);
tvall = (TextView) findViewById(R.id.tvall);
Bundle bundle = this.getIntent().getExtras();
String[] bar=bundle.getStringArray("bar");
/*tvall.setText(bar[0]);*/
}
public void back (View view) {
finish();
}
}

Calling method in second activity

I'm writing a tip app where the user selects a check, and then on the second activity the subtotal is displayed. However, I'm completely lost on how I display my subtotal. I have a getSubtotal() method but I don't know how to call it.
First Activity
public class TableListActivity extends Activity {
private ListView mListView;
private TableListAdapter mAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_table_list);
// Find the ListView, create an adapter that reads our list of checks,
// and connect the two
mListView = (ListView)findViewById(R.id.listView);
mAdapter = new TableListAdapter(this, DataStore.CHECKS);
mListView.setAdapter(mAdapter);
mListView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
// TODO Auto-generated method stub
Intent intent = new Intent (TableListActivity.this, PayCheckActivity.class);
intent.putExtra(PayCheckActivity.Extra_check, arg2);
startActivity(intent);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.table_list, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_refresh) {
// TODO do stuff here
Toast.makeText(this, "Refresh", Toast.LENGTH_SHORT).show();
return true;
}
return super.onOptionsItemSelected(item);
}}
Second Activity
public class PayCheckActivity extends Activity{
String Thank;
Button Sign;
Button fifteen;
Button eighteen;
Button twenty;
String sample;
public static final String Extra_check= "abc";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.paycheck);
Sign = (Button)findViewById(R.id.Sign);
fifteen= (Button)findViewById(R.id.fifteen);
eighteen= (Button)findViewById(R.id.eighteen);
twenty= (Button)findViewById(R.id.twenty);
Sign.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
Toast msg = Toast.makeText(getBaseContext(),"Thank You", Toast.LENGTH_LONG);
msg.show();
}});
fifteen.setOnClickListener(new OnClickListener()
{
public void onClick(View v)
{
Toast msg = Toast.makeText(getBaseContext(),"Thank Yolllllu", Toast.LENGTH_LONG);
msg.show();
}});}}
Check.java
public class Check {
private long id;
private String tableName;
private ArrayList<MenuItem> mItems = new ArrayList<MenuItem>();
private boolean hasBeenSigned = false;
public static class MenuItem {
public String name;
public Amount cost;
public MenuItem(String itemDescription, double cost) {
this.name = itemDescription;
this.cost = new Amount(cost);
}
}
public Check(long id, String tableName) {
this.id = id;
this.tableName = tableName;
}
public long getId() {
return id;
}
#Override
public String toString() {
// The ArrayAdapter uses toString to get the text to display in the list item
// We override toString here to display the table name
return tableName;
}
public void addItem(String itemDescription, double cost) {
mItems.add(new MenuItem(itemDescription, cost));
}
public String getTableName() {
return tableName;
}
public Amount getSubtotal() {
double total = 0;
for (MenuItem item : mItems) {
total += item.cost.getRawValue();
}
return new Amount(total);
}
public void markAsSigned() {
hasBeenSigned = true;
}
public int getItemCount() {
return mItems.size();
}
public MenuItem getMenuItemAt(int index) {
return mItems.get(index);
}}
Just a quick hint: You are sending some data to the second activity via Intent (onItemClick). In the second activity in onCreate, you can pick this data and call your getSubtotal method. Since it's not quite clear, what "Check" does, it's up to you how to instantiate it:
public class PayCheckActivity extends Activity{
// ...
protected void onCreate(Bundle savedInstanceState) {
Intent intent = getIntent();
if(intent != null) {
String value = intent.getStringExtra(PayCheckActivity.Extra_check);
Check check = .....
check.getSubtotal()
}
}
// ...
}

Categories

Resources