TextView Into and Integer - Android Software Development

I am trying to pass information from a text view into an ImageView to move the ImageView. The problem is I can't use the TextView information because it is defined as a TextView. So is there a way I can get it to use the TextView as an integer?

Do you mean you want to convert the text string in the textview to an integer? There's the java.lang.Integer class which has a static member parseInt() which might do what you need:
http://developer.android.com/reference/java/lang/Integer.html#parseInt(java.lang.String)

Not completely sure what your looking for but if I read it right,
imageView.setMethod(parseInt(textView.getText()))
setMethod being which ever method your trying to set the int into.

I need the data from my accelerometer code which looks like so:
package com.bobhoil.tdodger;
import android.app.Activity;
import android.os.Bundle;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.widget.TextView;
public class TestActivity extends Activity implements SensorEventListener {
private TextView accelXValue;
private TextView accelYValue;
private TextView accelZValue;
private SensorManager sensorManager = null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
setContentView(R.layout.test);
accelXValue = (TextView) findViewById(R.id.accel_x_value);
accelYValue = (TextView) findViewById(R.id.accel_y_value);
accelZValue = (TextView) findViewById(R.id.accel_z_value);
accelXValue.setText("0.00");
accelYValue.setText("0.00");
accelZValue.setText("0.00");
}
public void onSensorChanged(SensorEvent sensorEvent) {
synchronized (this) {
if (sensorEvent.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
accelXValue.setText(Float.toString(sensorEvent.values[0]));
accelYValue.setText(Float.toString(sensorEvent.values[1]));
accelZValue.setText(Float.toString(sensorEvent.values[2]));
}
}
}
public void onAccuracyChanged(Sensor arg0, int arg1) {
}
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(this, sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_GAME);
}
@Override
protected void onStop() {
sensorManager.unregisterListener(this);
super.onStop();
}
}
Click to expand...
Click to collapse
I need to put that into my imageview and use scrollby to move the imageview around the screen.

I'm not too familiar with imageviews, are you using XMLs for the layout or creating the imageViews programmaticly? I'm assuming the textViews and imageViews are in seperate classes. Thus the easiest way to get the text from the textViews would be to first give them the "protected" token rather than "private" and reference them directly.
Code:
imageView.scrollBy(parseInt(TestActivity.accelXValue.getText()));

I have tried that before but no matter what I try I get an error. Here is the error:
Cannot make a static reference to the non-static field TestActivity.accelXValue
Click to expand...
Click to collapse
So then I change it to static and get the following error:
The method parseInt(CharSequence) is undefined for the type TestActivity
Click to expand...
Click to collapse
I can't seem to get something that seems so simple to work.

Related

ImageView Scrolls But Disappears

Okay so after working hard I finally have scrolling somewhat working using the information from the accelerometer. I am using scrollBy() to make it move. But it scrolls I guess what you could say "in spot". It disappears when it goes outside its bounds. Here is my code:
Code:
package com.bobhoil.tdodger;
import android.app.Activity;
import android.os.Bundle;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.widget.ImageView;
import android.widget.TextView;
public class TestActivity extends Activity implements SensorEventListener {
private int accelXValue;
private int accelYValue;
private TextView accelZValue;
private ImageView mobil1;
private SensorManager sensorManager = null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
setContentView(R.layout.test);
accelZValue = (TextView) findViewById(R.id.accel_z_value);
mobil1 = (ImageView) findViewById(R.id.mobil);
accelZValue.setText("0.00");
}
public void onSensorChanged(SensorEvent sensorEvent) {
synchronized (this) {
if (sensorEvent.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
accelXValue = (int) sensorEvent.values[0];
accelYValue = (int) sensorEvent.values[1];
accelZValue.setText(Float.toString(sensorEvent.values[2]));
}
mobil1.scrollBy(accelXValue,accelYValue);
}
}
public void onAccuracyChanged(Sensor arg0, int arg1) {
}
@Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(this, sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_GAME);
}
@Override
protected void onStop() {
sensorManager.unregisterListener(this);
super.onStop();
}
}
Can I get some assistance please?
Okay so I tried using a few other ways of moving the imageview but it is still doing the same thing. Is it that I am using a absolute view??
I'd definitely recommend against using an AbsoluteLayout, but I'm guessing that you intend for the ImageView to move within another layout and instead you're telling the ImageView to move within itself. Basically, the scroll methods scroll the content of a view, so you would want to scroll a parent view if you're intending to move the ImageView.
So right now it isn't scrolling the ImageView? It is scrolling within the ImageView?
So now I need to figure out how to move a view in a view?
Just making sure I understood this.
Can I get some more help? I really need this for my game..

Text input with DialogFragment

I am trying to get a value that user enters into a Dialog, using the recommended DialogFragment class for it, the Dialog constructs and runs fine, but I cannot return the value of the EditText parameter to the parent class, without get a Null pointer exception.
My DialogHost class, this constructs, returns and links the parent to its buttons.
Code:
package jo.app.co;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.LayoutInflater;
public class DialogHost extends DialogFragment {
public interface NoticeDialogListener {
public void onDialogPositiveClick(DialogFragment dialog);
public void onDialogNegativeClick(DialogFragment dialog);
}
NoticeDialogListener mListener;
[user=439709]@override[/user]
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mListener = (NoticeDialogListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString());
}
}
[user=439709]@override[/user]
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
LayoutInflater inflater = getActivity().getLayoutInflater();
builder.setView(inflater.inflate(R.layout.dialog_add, null))
.setPositiveButton("Save", new DialogInterface.OnClickListener() {
[user=439709]@override[/user]
public void onClick(DialogInterface dialog, int id) {
mListener.onDialogPositiveClick(DialogHost.this);
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
DialogHost.this.getDialog().cancel();
}
});
return builder.create();
}
}
My MainActivity
Code:
package jo.app.co;
import android.app.DialogFragment;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.widget.EditText;
public class MainActivity extends FragmentActivity implements DialogHost.NoticeDialogListener {
[user=439709]@override[/user]
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
showNoticeDialog();
}
public void showNoticeDialog() {
DialogFragment dialog = new DialogHost();
dialog.show(getFragmentManager(), "DialogHost");
}
[user=439709]@override[/user]
public void onDialogPositiveClick(DialogFragment dialog) {
EditText myText = (EditText) findViewById(R.id.item_added);
try {
Log.d ("IN TRY", myText.getText().toString());
}
catch (Exception e) {
Log.e ("IN CATCH", e.toString());
}
}
[user=439709]@override[/user]
public void onDialogNegativeClick(DialogFragment dialog) {
Log.d ("INMAIN", "REACHED NEG");
}
}
This is my layout for the add item dialog.
Code:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<EditText
android:id="@+id/item_added"
android:inputType="text"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="16dp"
android:layout_marginLeft="4dp"
android:layout_marginRight="4dp"
android:layout_marginBottom="4dp"
android:hint="@string/hint_add_item" />
</LinearLayout>
It's because in your main activity you are trying to call findViewById:
swapnilraj said:
Code:
[user=439709]@override[/user]
public void onDialogPositiveClick(DialogFragment dialog) {
EditText myText = (EditText) findViewById(R.id.item_added);
try {
Log.d ("IN TRY", myText.getText().toString());
}
catch (Exception e) {
Log.e ("IN CATCH", e.toString());
}
}
Click to expand...
Click to collapse
This is not possible since the layout of the activity is not the one the dialog is using. There are multiple ways of doing this, for instance call findViewById in the dialog's onPositiveButtonListener and pass that value through your interface. It might be that you need to use the LayoutInflator in the onCreateDialog, set
LinearLayout linearl = (LinearLayout) inflater.inflate(...) and get the EditText from there. You then call setView(linearL) instead.
SimplicityApks said:
It's because in your main activity you are trying to call findViewById:
This is not possible since the layout of the activity is not the one the dialog is using. There are multiple ways of doing this, for instance call findViewById in the dialog's onPositiveButtonListener and pass that value through your interface. It might be that you need to use the LayoutInflator in the onCreateDialog, set
LinearLayout linearl = (LinearLayout) inflater.inflate(...) and get the EditText from there. You then call setView(linearL) instead.
Click to expand...
Click to collapse
I tried calling findViewById method in the onClick method in the Dialog class, but the function is not defined for a DialogInterface.onClickListner, I modified it to linearl method you told but I cannot get it to work either.
Could you make the changes in the 2 snippets above, it would be very helpful!
You'll have to setup listeners fo this and pass the string or whetever you want to pass to back to the activity which in its turn can handle it (do it by itself or pass this to another fragement).
Although not so much votes (0) the last answer here on stackoverflow has exeactly what you need.

How to use Navigation Drawer inside Tabs menu.

Hi guys.
I've been developing an app which has Swipeable menu in bottom and one of the pages , should have a Navigation Drawer to change its own Fragments.
MainActivity.java
Code:
package com.example.elizehprotowithshlkandvpis;
import com.example.elizehprotowithshlkandvpis.adapter.MainMenuAdapter;
import com.viewpagerindicator.TabPageIndicator;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.Menu;
public class MainActivity extends FragmentActivity {
private static final String[] CONTENT = { "Home", "AboutUs", "Maps", "Resturants", "Tours", "CustomerClub", "Neccesseries", "UrgentCall" };
private ViewPager mViewPager;
private FragmentPagerAdapter adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
adapter = new MainMenuAdapter(getSupportFragmentManager());
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(adapter);
TabPageIndicator indicator = (TabPageIndicator) findViewById(R.id.indicator);
indicator.setViewPager(mViewPager);
}
@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 static String[] getCONTENT() {
return CONTENT;
}
}
MainMenuAdapter.java
Code:
package com.example.elizehprotowithshlkandvpis.adapter;
import com.example.elizehprotowithshlkandvpis.MainActivity;
import com.example.menuclasses.AboutUs;
import com.example.menuclasses.CustomerClub;
import com.example.menuclasses.Maps;
import com.example.menuclasses.Neccesseries;
import com.example.menuclasses.Tours;
import com.example.menuclasses.UrgentCall;
import com.example.menuclasses.Resturants;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
public class MainMenuAdapter extends FragmentPagerAdapter {
private static final String[] CONTENT = { "Home", "AboutUs", "Maps", "Resturants", "Tours", "CustomerClub", "Neccesseries", "UrgentCall" };
private final int HOME_INDEX = 0;
private final int ABOUTUS_INDEX = 1;
private final int MAPS_INDEX = 2;
private final int RESTURANTS_INDEX = 3;
private final int TOURS_INDEX = 4;
private final int CUSTOMERCLUB_INDEX = 5;
private final int NECCESSERIES_INDEX = 6;
private final int URGENTCALL_INDEX = 7;
private final int NUMBEROFMENUS = CONTENT.length;
public MainMenuAdapter(FragmentManager fm) {
super(fm);
// TODO Auto-generated constructor stub
}
@Override
public CharSequence getPageTitle(int position) {
String[] CONTENT = MainActivity.getCONTENT();
return CONTENT[position % CONTENT.length].toUpperCase();
}
@Override
public Fragment getItem(int index) {
switch(index) {
case HOME_INDEX:
return new AboutUs();
case ABOUTUS_INDEX:
return new AboutUs();
case MAPS_INDEX:
return new Maps();
case RESTURANTS_INDEX:
return new Resturants();
case TOURS_INDEX:
return new Tours();
case CUSTOMERCLUB_INDEX:
return new CustomerClub();
case NECCESSERIES_INDEX:
return new Neccesseries();
case URGENTCALL_INDEX:
return new UrgentCall();
}
return null;
}
@Override
public int getCount() {
// TODO Auto-generated method stub
return NUMBEROFMENUS;
}
}
The Fragment that should contain a Navigation Drawer is Resturants , also drawer's mainactivity is implemented with Sherlock Library(SherlockFragmentActivity).
I'm puzzled how to call the SherlockFragmentActivity from the SherlockActivity
Thanks
Pouya_am said:
Hi guys.
I've been developing an app which has Swipeable menu in bottom and one of the pages , should have a Navigation Drawer to change its own Fragments.
MainActivity.java
Code:
package com.example.elizehprotowithshlkandvpis;
import com.example.elizehprotowithshlkandvpis.adapter.MainMenuAdapter;
import com.viewpagerindicator.TabPageIndicator;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.Menu;
public class MainActivity extends FragmentActivity {
private static final String[] CONTENT = { "Home", "AboutUs", "Maps", "Resturants", "Tours", "CustomerClub", "Neccesseries", "UrgentCall" };
private ViewPager mViewPager;
private FragmentPagerAdapter adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
adapter = new MainMenuAdapter(getSupportFragmentManager());
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(adapter);
TabPageIndicator indicator = (TabPageIndicator) findViewById(R.id.indicator);
indicator.setViewPager(mViewPager);
}
@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 static String[] getCONTENT() {
return CONTENT;
}
}
MainMenuAdapter.java
Code:
package com.example.elizehprotowithshlkandvpis.adapter;
import com.example.elizehprotowithshlkandvpis.MainActivity;
import com.example.menuclasses.AboutUs;
import com.example.menuclasses.CustomerClub;
import com.example.menuclasses.Maps;
import com.example.menuclasses.Neccesseries;
import com.example.menuclasses.Tours;
import com.example.menuclasses.UrgentCall;
import com.example.menuclasses.Resturants;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
public class MainMenuAdapter extends FragmentPagerAdapter {
private static final String[] CONTENT = { "Home", "AboutUs", "Maps", "Resturants", "Tours", "CustomerClub", "Neccesseries", "UrgentCall" };
private final int HOME_INDEX = 0;
private final int ABOUTUS_INDEX = 1;
private final int MAPS_INDEX = 2;
private final int RESTURANTS_INDEX = 3;
private final int TOURS_INDEX = 4;
private final int CUSTOMERCLUB_INDEX = 5;
private final int NECCESSERIES_INDEX = 6;
private final int URGENTCALL_INDEX = 7;
private final int NUMBEROFMENUS = CONTENT.length;
public MainMenuAdapter(FragmentManager fm) {
super(fm);
// TODO Auto-generated constructor stub
}
@Override
public CharSequence getPageTitle(int position) {
String[] CONTENT = MainActivity.getCONTENT();
return CONTENT[position % CONTENT.length].toUpperCase();
}
@Override
public Fragment getItem(int index) {
switch(index) {
case HOME_INDEX:
return new AboutUs();
case ABOUTUS_INDEX:
return new AboutUs();
case MAPS_INDEX:
return new Maps();
case RESTURANTS_INDEX:
return new Resturants();
case TOURS_INDEX:
return new Tours();
case CUSTOMERCLUB_INDEX:
return new CustomerClub();
case NECCESSERIES_INDEX:
return new Neccesseries();
case URGENTCALL_INDEX:
return new UrgentCall();
}
return null;
}
@Override
public int getCount() {
// TODO Auto-generated method stub
return NUMBEROFMENUS;
}
}
The Fragment that should contain a Navigation Drawer is Resturants , also drawer's mainactivity is implemented with Sherlock Library(SherlockFragmentActivity).
I'm puzzled how to call the SherlockFragmentActivity from the SherlockActivity
Thanks
Click to expand...
Click to collapse
That last sentence does not make sense I assume you mean from the Fragment?! Well to access the holding activity you need to add an interface to the Fragment which the activity will implement.
Am I understanding you correctly that have a horizontal ViewPager and one of the Fragments should have a Navigation drawer? To accomplish that you would still need the whole activity to hold the drawer and figure out a way to disable it when the user is on some other Fragment. But my question is why you want to use a navigation drawer in that case, because the drawer is meant for navigating on the same hierarchical level, but the different items are more independent than with the ViewPager. It doesn't really make sense to have both a drawer and horizontal swiping, even the YouTube app really bothers me with its swiping between suggestions and feed. I think what you need to use here is a spinner in the ActionBar, replacing the title of the Fragment.
SimplicityApks said:
That last sentence does not make sense I assume you mean from the Fragment?! Well to access the holding activity you need to add an interface to the Fragment which the activity will implement.
Am I understanding you correctly that have a horizontal ViewPager and one of the Fragments should have a Navigation drawer? To accomplish that you would still need the whole activity to hold the drawer and figure out a way to disable it when the user is on some other Fragment. But my question is why you want to use a navigation drawer in that case, because the drawer is meant for navigating on the same hierarchical level, but the different items are more independent than with the ViewPager. It doesn't really make sense to have both a drawer and horizontal swiping, even the YouTube app really bothers me with its swiping between suggestions and feed. I think what you need to use here is a spinner in the ActionBar, replacing the title of the Fragment.
Click to expand...
Click to collapse
Yeah you're right , I just want to use the drawer in order to change contents.
So as you suggest , I just have to use a simple tricks to make the drawer enable in desire Fragment.
I don't want to , I am asked to make it possible....

Data That is Fetched From The Web Server Are Appending

I have this search function for my app that fetches data from web server using json, everything works completely except that everytime I search something, the data keeps on appending on my listview. For example if I search for a data with an id number 7 then press search button, the data is fetched and placed on the listview which what I want, but then if I search again the id number 7, there are now 2 instances of data with an id number of 7 in the listview. What I want is to refresh the listview for every search so that the only data that will appear on the listview is the current searched data.
MainActivity.java
Code:
package learn2crack.listview;
import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.EditText;
import learn2crack.listview.library.JSONParser;
public class MainActivity extends Activity {
ListView list;
TextView title;
Button Btngetdata;
ArrayList<HashMap<String, String>> oslist = new ArrayList<HashMap<String, String>>();
//JSON Node Names
private static final String TAG_NEWS = "news";
private static final String TAG_TITLE = "title";
JSONArray android = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
oslist = new ArrayList<HashMap<String, String>>();
Btngetdata = (Button)findViewById(R.id.getdata);
Btngetdata.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
new JSONParse().execute();
}
});
}
private class JSONParse extends AsyncTask<String, String, JSONObject> {
private ProgressDialog pDialog;
@Override
protected void onPreExecute() {
super.onPreExecute();
title = (TextView)findViewById(R.id.title);
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Getting Data ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
@Override
protected JSONObject doInBackground(String... args) {
JSONParser jParser = new JSONParser();
String url = "http://localhost/abc-news/news.php?json-request-news=";
EditText id = (EditText)findViewById(R.id.search_text);
url = url + id.getText().toString();
// Getting JSON from URL
JSONObject json = jParser.getJSONFromUrl(url);
return json;
}
@Override
protected void onPostExecute(JSONObject json) {
pDialog.dismiss();
try {
// Getting JSON Array from URL
android = json.getJSONArray(TAG_NEWS);
for(int i = 0; i < android.length(); i++){
JSONObject c = android.getJSONObject(i);
// Storing JSON item in a Variable
String title = c.getString(TAG_TITLE);
// Adding value HashMap key => value
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_TITLE, title);
oslist.add(map);
list=(ListView)findViewById(R.id.list);
ListAdapter adapter = new SimpleAdapter(MainActivity.this, oslist,
R.layout.list_v,
new String[] { TAG_TITLE }, new int[] {
R.id.title });
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(MainActivity.this, "You Clicked at "+oslist.get(+position).get("name"), Toast.LENGTH_SHORT).show();
}
});
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
I attached an image below to support this problem I'm encountering.
Code:
oslist.add(map);
you're adding to the list that drives the adapter, add does what it implies ... maybe you should go though some basics, copy and pasting code sometimes wastes more time that you think it would save in the long run.
Hope that helps
Can you explain it more clearly here?
clonedaccnt said:
Can you explain it more clearly here?
Click to expand...
Click to collapse
erm, add = add ? sorry to come across like this but not sure what you are expecting... a,b,c .add(d) == a,b,c,d
What do I need to do to my code so that the newly searched data will not append on the previous data that is fetched?
clonedaccnt said:
What do I need to do to my code so that the newly searched data will not append on the previous data that is fetched?
Click to expand...
Click to collapse
I thought that was clear, don't "add" to what you have? Are you aware of what an array is ? or a list? and an adapter? cause I think I would start there, you just keep adding to the list that powers the adapter. If you dont want to add to it just don't, either clear it or replace it.
so just to be clear, a list or map has the method .clear() <--- that clears it of all data
I've already solve the problem earlier, I was going to post that I've already solve it but found out that you've already replied on the thread, sorry. About the problem, yes I too used the .clear() of the ArrayList to clear the array before adding a new one, it's my first time to create an activity that pass the data on the same activity, I'm used to passing the data from one activity to another so I don't have a chance to encounter this kind of problem.
Anyways thanks for helping I will not have accomplished this without your help.

App crashes when when calling a method

Hello,
So I am new to Java programming and I want to develop a small and simple app for plant identification. But the app crashes when I call a function wich set the text of a TextView. It happens in the OnCreate when I switch to a second activity. I tried to call the method with only comments in it. It also works when I create a new instance of the MainActivity class. It crashes when I try to set the text of a TextView from the MainActivity layout. It is probably a simple and basic problem, but I've been searching for my error for hours now and I still can't get it. I want to understand what's wrong and move on the the next step
I use the layout of MainActivity in Morphe activity.
Code:
package com.gobtron.cleidfougeres;
import android.content.Intent;
import android.graphics.Color;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
public class Morphe extends MainActivity {
TextView MorphTextTop;
TextView LongFrondeTextTop;
TextView FormeLimbeTextTop;
TextView DisposFrondeTextTop;
TextView DescTextTop;
TextView EspeceTextTop;
TextView textView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TopText topText = new TopText();
topText.SetText();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_morphe, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
And this is the code for the method in TopText method (located in TopText.java)
Code:
public class TopText {
public void SetText() {
MainActivity mainac = new MainActivity();
mainac.MorphTextTop.setText("eeeee");
}
}
gobtron said:
Hello,
So I am new to Java programming and I want to develop a small and simple app for plant identification. But the app crashes when I call a function wich set the text of a TextView. It happens in the OnCreate when I switch to a second activity. I tried to call the method with only comments in it. It also works when I create a new instance of the MainActivity class. It crashes when I try to set the text of a TextView from the MainActivity layout. It is probably a simple and basic problem, but I've been searching for my error for hours now and I still can't get it. I want to understand what's wrong and move on the the next step
I use the layout of MainActivity in Morphe activity.
Code:
package com.gobtron.cleidfougeres;
import android.content.Intent;
import android.graphics.Color;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.TextView;
public class Morphe extends MainActivity {
TextView MorphTextTop;
TextView LongFrondeTextTop;
TextView FormeLimbeTextTop;
TextView DisposFrondeTextTop;
TextView DescTextTop;
TextView EspeceTextTop;
TextView textView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TopText topText = new TopText();
topText.SetText();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_morphe, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
And this is the code for the method in TopText method (located in TopText.java)
Code:
public class TopText {
public void SetText() {
MainActivity mainac = new MainActivity();
mainac.MorphTextTop.setText("eeeee");
}
}
Click to expand...
Click to collapse
Though you haven't posted a stack trace but I'm pretty sure a NullPointerException is being thrown in your code and this is because
Code:
public class TopText {
public void SetText() {
MainActivity mainac = new MainActivity();
mainac.MorphTextTop.setText("eeeee");
}
}
Is creating a new instance of Activity class MainActivity in which the field "MorphTextTop" is not initialized.......
All the fields in your main activity must be initialized in the onCreate method of the Activity after you have called " setContentView(R.layout.activity_main);"
The initialization would look something like
Code:
MorphTextTop = (TextView) findViewById(R.id."THIS_VIEWS_ID");
put your activity_main.xml here if you then I could give you the complete code.
What does your log say after the app crashes? And where's your actual MainActivity class?
Ok I finally found out the problem. Turns out that I was creating an instance of the TextView before setting the ContentView. Yay!

Categories

Resources