I have a viewpager with four webview fragments. Im trying to get a GoBack Action to my WebView which is inside of a fragment. But i cant implement it right into my code here is the code of my webview in my fragments. I also can't seem to get a downloadListener to work either. Sorry I am kinda new to fragments and trying to understand how they work.
Code:
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebSettings.RenderPriority;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.LinearLayout;
public class Fragment1 extends Fragment {
private static final String WebSettings = null;
private WebView webView;
private Bundle webViewBundle;
[user=439709]@override[/user]
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
LinearLayout ll = (LinearLayout) inflater.inflate(R.layout.fragment_1,
container, false);
webView = (WebView) ll.findViewById(R.id.webview);
webView.setWebViewClient(new WebViewClient());
webView.getSettings().setLoadWithOverviewMode(true);
webView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setBuiltInZoomControls(true);
webView.getSettings().setSupportZoom(true);
webView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
webView.getSettings().setAllowFileAccess(true);
webView.getSettings().setDomStorageEnabled(true);
webView.getSettings().setRenderPriority(RenderPriority.HIGH);
if (webViewBundle == null) {
try{
webView.loadUrl("http://www.google.com");
}catch (Exception e){
e.printStackTrace();}
} else {
webView.restoreState(webViewBundle);
}
return ll;
}
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
[user=439709]@override[/user]
public void onPause() {
super.onPause();
webViewBundle = new Bundle();
webView.saveState(webViewBundle);
}
}
dfuse06 said:
I have a viewpager with four webview fragments. Im trying to get a GoBack Action to my WebView which is inside of a fragment. But i cant implement it right into my code here is the code of my webview in my fragments. I also can't seem to get a downloadListener to work either. Sorry I am kinda new to fragments and trying to understand how they work.
Code:
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebSettings.RenderPriority;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.LinearLayout;
public class Fragment1 extends Fragment {
private static final String WebSettings = null;
private WebView webView;
private Bundle webViewBundle;
[user=439709]@override[/user]
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
LinearLayout ll = (LinearLayout) inflater.inflate(R.layout.fragment_1,
container, false);
webView = (WebView) ll.findViewById(R.id.webview);
webView.setWebViewClient(new WebViewClient());
webView.getSettings().setLoadWithOverviewMode(true);
webView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setBuiltInZoomControls(true);
webView.getSettings().setSupportZoom(true);
webView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
webView.getSettings().setAllowFileAccess(true);
webView.getSettings().setDomStorageEnabled(true);
webView.getSettings().setRenderPriority(RenderPriority.HIGH);
if (webViewBundle == null) {
try{
webView.loadUrl("http://www.google.com");
}catch (Exception e){
e.printStackTrace();}
} else {
webView.restoreState(webViewBundle);
}
return ll;
}
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
[user=439709]@override[/user]
public void onPause() {
super.onPause();
webViewBundle = new Bundle();
webView.saveState(webViewBundle);
}
}
Click to expand...
Click to collapse
You will need to override the onKeyUp method in the Activity. Then search for the fragment there and call a method of your subclass of Fragment which you want to be executed when the back key is pressed.
nikwen said:
You will need to override the onKeyUp method in the Activity. Then search for the fragment there and call a method of your subclass of Fragment which you want to be executed when the back key is pressed.
Click to expand...
Click to collapse
So I can't actually do this inside the fragment?
Sent from my SCH-I535 using Tapatalk 2
dfuse06 said:
So I can't actually do this inside the fragment?
Sent from my SCH-I535 using Tapatalk 2
Click to expand...
Click to collapse
I do not think so.
nikwen said:
I do not think so.
Click to expand...
Click to collapse
That must be all my errors then.
Sent from my SCH-I535 using Tapatalk 2
nikwen said:
You will need to override the onKeyUp method in the Activity. Then search for the fragment there and call a method of your subclass of Fragment which you want to be executed when the back key is pressed.
Click to expand...
Click to collapse
could you post a example on how it should look. This is driving me nuts nothing is working
dfuse06 said:
could you post a example on how it should look. This is driving me nuts nothing is working
Click to expand...
Click to collapse
Google!!!
Check those:
http://stackoverflow.com/questions/12210906/fragment-activity-catch-onkeydown-and-use-in-fragment
http://stackoverflow.com/questions/10631425/android-webview-inside-fragment-how-to-add-goback
nikwen said:
Google!!!
Check those:
http://stackoverflow.com/questions/12210906/fragment-activity-catch-onkeydown-and-use-in-fragment
http://stackoverflow.com/questions/10631425/android-webview-inside-fragment-how-to-add-goback
Click to expand...
Click to collapse
lol!!! I have googled it. Looked on stackoverflow posted on stack
http://stackoverflow.com/questions/16379973/goback-and-download-listener-in-webview-fragment
tried all kinda codes I found from there and no luck!
dfuse06 said:
lol!!! I have googled it. Looked on stackoverflow posted on stack
http://stackoverflow.com/questions/16379973/goback-and-download-listener-in-webview-fragment
tried all kinda codes I found from there and no luck!
Click to expand...
Click to collapse
Post your code (or the important parts of it) so that we can find your errors.
Having the same issue
dfuse06 said:
lol!!! I have googled it. Looked on stackoverflow posted on stack
tried all kinda codes I found from there and no luck!
Click to expand...
Click to collapse
I'm having the same issue. Did you find resolution? If so, please post it.
Related
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.
I've run into a little trouble and I'm wondering if someone can help me out.
I have a button with several sound effects that go with it. I'm wanting to play a different sound each time the button is pressed, but I just can't get things to work out. Can someone show me the way? Any help would be huge. This is the only thing keeping me from finishing. Here's a little code:
Code:
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class Main extends Activity {
private SoundManager mSoundManager;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mSoundManager = new SoundManager();
mSoundManager.initSounds(getBaseContext());
mSoundManager.addSound(1, R.raw.finn_whatthejugisthat);
mSoundManager.addSound(2, R.raw.finn_wordtoyourmother);
Button SoundButton = (Button)findViewById(R.id.Button1);
SoundButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
mSoundManager.playSound(1);
mSoundManager.playSound(2);
}
});
}
}
If you want to play a different sound with each click, then you'll have to keep a global counter variable or global string that you change to the next audio file name with each click of the button--sort of a circular buffer. The code you have there tries to play both sounds on the same click and likely mixes them together at the same time if "playSound()" is asynchronous, but I don't know what the SoundManager class is so I have no idea.
Gene Poole said:
If you want to play a different sound with each click, then you'll have to keep a global counter variable or global string that you change to the next audio file name with each click of the button--sort of a circular buffer. The code you have there tries to play both sounds on the same click and likely mixes them together at the same time if "playSound()" is asynchronous, but I don't know what the SoundManager class is so I have no idea.
Click to expand...
Click to collapse
Okay, so I understand what you mean, but I don't know how to say that in Java. Could you give a short example? As for SoundManager, it's really a useless class I have that I was using to play my media. You can take a look here:
Code:
package com.andrew.finnandjake;
import java.util.HashMap;
import android.content.Context;
import android.media.AudioManager;
import android.media.SoundPool;
public class SoundManager {
private SoundPool mSoundPool;
private HashMap<Integer, Integer> mSoundPoolMap;
private AudioManager mAudioManager;
private Context mContext;
public SoundManager()
{
}
public void initSounds(Context theContext) {
mContext = theContext;
mSoundPool = new SoundPool(4, AudioManager.STREAM_MUSIC, 0);
mSoundPoolMap = new HashMap<Integer, Integer>();
mAudioManager = (AudioManager)mContext.getSystemService(Context.AUDIO_SERVICE);
}
public void addSound(int Index,int SoundID)
{
mSoundPoolMap.put(1, mSoundPool.load(mContext, SoundID, 1));
}
public void playSound(int index) {
int streamVolume = mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
mSoundPool.play(mSoundPoolMap.get(index), streamVolume, streamVolume, 1, 0, 1f);
}
public void playLoopedSound(int index) {
int streamVolume = mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
mSoundPool.play(mSoundPoolMap.get(index), streamVolume, streamVolume, 1, -1, 1f);
}
}
OK, I see it uses SoundPool. First, change your definition for addSound to:
Code:
public void addSound(int Index,int SoundID)
{
mSoundPoolMap.put([COLOR="Red"]Index[/COLOR], mSoundPool.load(mContext, SoundID, 1));
}
Here's code that should work to do a different tone each push and loop back to the beginning.
Code:
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class ButtonSound extends Activity{
private SoundManager mSoundManager;
private int next=0;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mSoundManager=new SoundManager();
mSoundManager.initSounds(getBaseContext());
mSoundManager.addSound(0,R.raw.freeze);
mSoundManager.addSound(1,R.raw.ascend);
mSoundManager.addSound(2,R.raw.bubble);
mSoundManager.addSound(3,R.raw.chiff);
Button SoundButton=(Button)findViewById(R.id.button1);
SoundButton.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v){
mSoundManager.playSound(next);
next++;
if(next>3)
next=0;
}
});
}
}
Gene Poole said:
OK, I see it uses SoundPool. First, change your definition for addSound to:
Code:
public void addSound(int Index,int SoundID)
{
mSoundPoolMap.put([COLOR="Red"]Index[/COLOR], mSoundPool.load(mContext, SoundID, 1));
}
Here's code that should work to do a different tone each push and loop back to the beginning.
Code:
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class ButtonSound extends Activity{
private SoundManager mSoundManager;
private int next=0;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mSoundManager=new SoundManager();
mSoundManager.initSounds(getBaseContext());
mSoundManager.addSound(0,R.raw.freeze);
mSoundManager.addSound(1,R.raw.ascend);
mSoundManager.addSound(2,R.raw.bubble);
mSoundManager.addSound(3,R.raw.chiff);
Button SoundButton=(Button)findViewById(R.id.button1);
SoundButton.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v){
mSoundManager.playSound(next);
next++;
if(next>3)
next=0;
}
});
}
}
Click to expand...
Click to collapse
Mkay, so I adjusted my code according to the example and everything came back error free; however, when I run the app and click the button, nothing happens. No sound, but no force close either.
I ran the Debugger and it's telling me that the SoundPool sample is not ready. "Sample 1 not READY", "Sample 2 not READY", etc.
I don't know. I assume you used different names for your sound files. I just grabbed those out of the "notifications" directory of my phone.
Gene Poole said:
I don't know. I assume you used different names for your sound files. I just grabbed those out of the "notifications" directory of my phone.
Click to expand...
Click to collapse
Alright, that's cool. Thanks a lot for all of the help. I owe you one.
Hi there,
I would like some advice on what I should look for if I want to implement the following basic scenario:
the app starts with an activity (call it Activity_1) which contains a button
on clicking the button, takes me to a different activity (call it Activity_2)
next time i start the app, it takes me directly to Activity_2
and Activity_1 won't be seen again
So how can I change the startup activity?
What's happening is that Android is not closing your app in between starts, it's only backgrounding it. One thing you could do is to override the onResume() method in your Activity_2 to call finish() if for instance you have set some variable, let's call it appPaused and it would act just like you had pressed the back button (which will also take you back to Activity_1).
Like below:
Code:
package com.test.example;
import android.app.Activity;
import android.os.Bundle;
public class Activity_2 extends Activity
{
boolean appPaused = false;
[user=439709]@override[/user]
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
}
[user=439709]@override[/user]
public void onPause()
{
appPaused = true;
}
[user=439709]@override[/user]
public void onResume()
{
if(appPaused)
finish();
}
}
thanks for the answer. i want to consider that the app is closed, like after restarting the device. i don't want it to be able to start with Activity_1 unless, let's say, i re-install the app.
i also had an idea about having a 3rd activity as the main one defined in the manifest, which on create changes to one of the other activities. but i don't know how that would be implemented. would it work?
octobclrnts said:
What's happening is that Android is not closing your app in between starts, it's only backgrounding it. One thing you could do is to override the onResume() method in your Activity_2 to call finish() if for instance you have set some variable, let's call it appPaused and it would act just like you had pressed the back button (which will also take you back to Activity_1).
Like below:
Code:
package com.test.example;
import android.app.Activity;
import android.os.Bundle;
public class Activity_2 extends Activity
{
boolean appPaused = false;
[user=439709]@override[/user]
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
}
[user=439709]@override[/user]
public void onPause()
{
appPaused = true;
}
[user=439709]@override[/user]
public void onResume()
{
if(appPaused)
finish();
}
}
Click to expand...
Click to collapse
Oh, I'm sorry, I misunderstood your question the first time. If you don't want an activity to be shown except for say the first time after an install (maybe it's a login screen or similar), I would in my main activity, use the SharedPreferences class to see if I have a preference set like below:
Code:
package com.test.example;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
public class Activity_Start extends Activity
{
boolean appPaused = false;
[user=439709]@override[/user]
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
if(!prefs.contains("loggedIn"))
{
//run activity only if never run before
startActivity(new Intent(this,Activity_Logon.class));
}
else
{
//do something else every other time
}
}
}
Code:
package com.test.example;
import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
public class Activity_Logon extends Activity
{
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
doLogon();
finish();
}
private void doLogon()
{
//logon code
SharedPreferences.Editor edit = PreferenceManager.getDefaultSharedPreferences(this).edit();
edit.putBoolean("loggedIn",true);
}
}
oh, ok. so from what I get SharedPreferences is a db where you can quickly save variables between sessions. great, I'll try it
octobclrnts said:
Oh, I'm sorry, I misunderstood your question the first time. If you don't want an activity to be shown except for say the first time after an install (maybe it's a login screen or similar), I would in my main activity, use the SharedPreferences class to see if I have a preference set like below:
Code:
package com.test.example;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
public class Activity_Start extends Activity
{
boolean appPaused = false;
[user=439709]@override[/user]
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
if(!prefs.contains("loggedIn"))
{
//run activity only if never run before
startActivity(new Intent(this,Activity_Logon.class));
}
else
{
//do something else every other time
}
}
}
Code:
package com.test.example;
import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
public class Activity_Logon extends Activity
{
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
doLogon();
finish();
}
private void doLogon()
{
//logon code
SharedPreferences.Editor edit = PreferenceManager.getDefaultSharedPreferences(this).edit();
edit.putBoolean("loggedIn",true);
}
}
Click to expand...
Click to collapse
K-RAD said:
oh, ok. so from what I get SharedPreferences is a db where you can quickly save variables between sessions. great, I'll try it
Click to expand...
Click to collapse
That's absolutely right. You can store Strings and primitive values indexed by String keys.
octobclrnts said:
That's absolutely right. You can store Strings and primitive values indexed by String keys.
Click to expand...
Click to collapse
in the second activity, doLogon() needed an edit.apply() at the end. it works somehow, but the problem is when i press the back button, it still takes me to the first activity, and i don'twant to see it anymore after i press the button. here's my code
Code:
package com.example.onetimeactivity;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends Activity {
[user=439709]@override[/user]
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
if(!prefs.contains("loggedIn"))
{
//run activity only if never run before
Button b = (Button) findViewById(R.id.button1);
b.setOnClickListener(new OnClickListener() {
[user=439709]@override[/user]
public void onClick(View arg0) {
startActivity(new Intent(MainActivity.this, SecondActivity.class));
}
});
}
else
{
//do something else every other time
startActivity(new Intent(this,SecondActivity.class));
}
}
}
Code:
package com.example.onetimeactivity;
import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
public class SecondActivity extends Activity
{
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
doLogon();
}
private void doLogon()
{
//logon code
SharedPreferences.Editor edit = PreferenceManager.getDefaultSharedPreferences(this).edit();
edit.putBoolean("loggedIn",true);
edit.apply();
}
}
i managed to resolve it by adding android:noHistory="true" to the manifest. however, now i really can't see the first activity, not even if i rebuild the code ))
K-RAD said:
in the second activity, doLogon() needed an edit.apply() at the end. it works somehow, but the problem is when i press the back button, it still takes me to the first activity, and i don'twant to see it anymore after i press the button. here's my code
Click to expand...
Click to collapse
K-RAD said:
in the second activity, doLogon() needed an edit.apply() at the end. it works somehow, but the problem is when i press the back button, it still takes me to the first activity, and i don'twant to see it anymore after i press the button. here's my code
Click to expand...
Click to collapse
Thanks for catching my mistake. You're right that it does need an apply (or before API level 9, commit()) call.
If you don't want to see the activity MainActivity anymore, then you have to make some changes to your structure. You should make an Activity that will be the one that always shows when the user opens the app. That activity is the one who should check the SharedPreferences for your entry. If the entry does not exist, it should call the one-time-activity. Then the one-time-activity should do it's work and save the entry and call finish() to go back to the main activity (the one you usually want to be shown). This way the activity stack will be correct for the back key functionality.
what it sounds like you want is something like a splash/logon screen
like previously said use sharedprefs.
in the splash/logon call the sharedpref and make the default false (I use booleans, you can use ints or strings):
so it would be like this
Code:
SharedPreferences settings;
SharedPreferences.Editor editor;
boolean splash;
[user=439709]@override[/user]
public void onCreate() {
settings = getSharedPreferences("settings", 0);
splash = settings.getboolean("splash", false);
editor = settings.edit();
if(splash == false){
setContentView(//the view you are using);
//do everything else you need to do
button.setonclicklistener(new OnClickListener(){
editor.putboolean("splash", true);
editor.commit();
finish();
});
}else{
//open up your second activity
finish();
}
if its a login screen, when the user clicks logout you would do the editor and change "splash" to false.
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.
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!