How select inbox msg by default display on spinner - java

In the system when I select msg that msg by default display on spinner.I require this project those select item display only spinner.If I change item not show previous select item display on spinner.
list.java
Spinner sp1;
TextView entry;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.list);
sp1=(Spinner) findViewById(R.id.spinner1);
entry = (TextView)findViewById(R.id.TextView123);
getFilesnames();
}
private void getFilesnames() {
// TODO Auto-generated method stub
String[] filenames=getApplicationContext().fileList();
List<String> list=new ArrayList<String>();
for(int i=0;i<filenames.length;i++){
list.add(filenames[i]);
}
ArrayAdapter<String> filenameAdapter=new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item,list);
sp1.setAdapter(filenameAdapter);
}
public void onClick(View v) {
// TODO Auto-generated method stub
String selectFile = String.valueOf(sp1.getSelectedItem());
openFile(selectFile);
}
private void openFile(String selectFile) {
// TODO Auto-generated method stub
String value = "";
FileInputStream fis;
try {
fis = openFileInput(selectFile);
byte[] input = new byte[fis.available()];
while(fis.read(input) != -1){
value += new String(input);
}
fis.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
entry.setText(value);
}

Check whether list has value after binding like following code:
private void getFilesnames() {
// TODO Auto-generated method stub
String[] filenames=getApplicationContext().fileList();
List<String> list=new ArrayList<String>();
for(int i=0;i<filenames.length;i++){
list.add(filenames[i]);
}
/***
check here list has value or not
***/
if(list.size() <= 0) {
list.add("You string.....");
}
ArrayAdapter<String> filenameAdapter=new ArrayAdapter<String>(this,android.R.layout.simple_spinner_item,list);
sp1.setAdapter(filenameAdapter);
}

Related

Android ArrayIndexOutOfBoundsException..?

So I'm making an Android soundboard app and get this exception and my app crashes when I click the last button of the soundboard app.
[THE CODE]
public class newBoard extends Activity {
int selectedSoundId;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final MediaPlayer player = new MediaPlayer();
final Resources res = getResources();
// just keep them in the same order, e.g. button01 is tied to backtoyou
final int[] buttonIds = { R.id.button1, R.id.button2, R.id.button3,
R.id.button4, R.id.button5, R.id.button6, R.id.button7,
R.id.button8, R.id.button9, R.id.button10, R.id.button11,
R.id.button12, R.id.button13, R.id.button14, R.id.button15,
R.id.button16, R.id.button16, R.id.button17, R.id.button18,
R.id.button19, R.id.button20, R.id.button21, R.id.button22,
R.id.button23, R.id.button24, R.id.button25, R.id.button26,
R.id.button27, R.id.button28, R.id.button29, R.id.button30,
R.id.button31, R.id.button32 };
final int[] soundIds = { R.raw.bengalka, R.raw.cista_psihologija,
R.raw.da_ne, R.raw.dejo_narkomane, R.raw.dizi_se,
R.raw.fejslifting, R.raw.fotomale, R.raw.gladan_sam,
R.raw.jasna_pero, R.raw.jeben_vam_mater, R.raw.kae_ivanisevic,
R.raw.kae_to_fora, R.raw.kaj_gledas, R.raw.kaj_vi_gledate,
R.raw.kineza_crnaca, R.raw.kozo_nepodojena, R.raw.marino,
R.raw.mater_zbrgljavu, R.raw.muha, R.raw.nema_papira,
R.raw.nered, R.raw.ne_spominji_majku, R.raw.nisam_se_uroko,
R.raw.odfurati_doktoru, R.raw.pljacka, R.raw.pusi_ke,
R.raw.sava_sava, R.raw.tebe_i_magazin, R.raw.tog_vani_nema,
R.raw.za_dom_spremni, R.raw.zrigati };
View.OnClickListener listener = new View.OnClickListener() {
public void onClick(View v) {
// find the index that matches the button's ID, and then reset
// the MediaPlayer instance, set the data source to the
// corresponding
// sound effect, prepare it, and start it playing.
for (int i = 0; i < buttonIds.length; i++) {
if (v.getId() == buttonIds[i]) {
selectedSoundId = soundIds[i];
AssetFileDescriptor afd = res
.openRawResourceFd(soundIds[i]);
player.reset();
try {
player.setDataSource(afd.getFileDescriptor(),
afd.getStartOffset(), afd.getLength());
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
player.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
player.start();
break;
}
}
}
};
// set the same listener for every button ID, no need
// to keep a reference to every button
for (int i = 0; i < buttonIds.length; i++) {
Button soundButton = (Button) findViewById(buttonIds[i]);
registerForContextMenu(soundButton);
soundButton.setOnClickListener(listener);
}
}
}
The exception shows on this line:
selectedSoundId = soundIds[i];
selectedSoundId = soundIds[i];
final int[] buttonIds = 33 Value - you have two R.id.button16 in your buttonIds
final int[] soundIds = 31 Value
So it is crash.
Off-by-two: There are 33 button ids and 31 sound ids. Button 16 is duplicated.
For mapping resource ids and other integers, consider a map, such as SparseIntArray.

An error connecting to Android Spinner

I am working on an Android app where I have a Spinner, and on the base of which item I choose, the app will read in text file number 1 or number 2, etc... I have written a code, but when I run it on my device, it says that "The application has stopped unexpectedly".
Here is my code:
public class MainActivity extends Activity implements OnClickListener, OnItemSelectedListener {
Spinner spinner;
String textSource = "";
TextView textMsg;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textMsg = (TextView) findViewById(R.id.textmsg);
spinner=(Spinner) findViewById(R.id.spinner1);
List<String> list = new ArrayList<String>();
list.add("list 1");
list.add("list 2");
list.add("list 3");
ArrayAdapter<String> adapter=new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item,list);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(this);
URL textUrl;
String stringText = "";
try {
textUrl = new URL(textSource);
BufferedReader bufferReader = new BufferedReader(
new InputStreamReader(textUrl.openStream(), "ISO-8859-1"));
//ISO-8859-1
String StringBuffer;
//String stringText = "";
while ((StringBuffer = bufferReader.readLine()) != null) {
stringText += StringBuffer;
}
bufferReader.close();
textMsg.setText(stringText);
//textMsg.setText(string123);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
textMsg.setText(e.toString());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
textMsg.setText(e.toString());
}
}
#Override
public void onItemSelected(AdapterView<?> parent, View arg1, int pos,
long arg3) {
// TODO Auto-generated method stub
String Text = parent.getSelectedItem().toString();
if(Text.equals("list 1")) {
textSource = "path/to/textfile 1";
}
else if(Text.equals("list 2")){
textSource = "path/to/textfile 2";
}
else {
}
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
}
How should I solve this problem?
Thanks for helping
I would suggest you to use
String Text = spinner.getSelectedItem().toString();
instead of
String Text = parent.getSelectedItem().toString();
So that it becomes :
#Override
public void onItemSelected(AdapterView<?> parent, View arg1, int pos,
long arg3) {
String Text = spinner.getSelectedItem().toString();
if(Text.equals("list 1")) {
textSource = "path/to/textfile 1";
}
else if(Text.equals("list 2")){
textSource = "path/to/textfile 2";
}
else {
}
// then put your URL code here as follows
URL textUrl;
String stringText = "";
try {
textUrl = new URL(textSource);
BufferedReader bufferReader = new BufferedReader(
new InputStreamReader(textUrl.openStream(), "ISO-8859-1"));
//ISO-8859-1
String StringBuffer;
while ((StringBuffer = bufferReader.readLine()) != null) {
stringText += StringBuffer;
}
bufferReader.close();
textMsg.setText(stringText);
//textMsg.setText(string123);
} catch (MalformedURLException e) {
e.printStackTrace();
textMsg.setText(e.toString());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
textMsg.setText(e.toString());
}
}
Since you are calling textUrl = new URL(textSource); inside oncreate() method textSource will be always " ". Better create a method and pass the new textSource value based on onItemSelected .
Sample for Your reference: By Default Link1 will be passed
#Override
public void onItemSelected(AdapterView<?> parent, View arg1, int pos,
long arg3) {
String Text = parent.getSelectedItem().toString();
if (Text.equals("list 1")) {
Method("path/to/textfile 1");
} else if (Text.equals("list 2")) {
Method("path/to/textfile 2");
} else {
}
// TODO Auto-generated method stub
}
Method :
public void Method(String textSource) {
URL textUrl;
String stringText = "";
try {
textUrl = new URL(textSource);
BufferedReader bufferReader = new BufferedReader(
new InputStreamReader(textUrl.openStream(), "ISO-8859-1"));
// ISO-8859-1
String StringBuffer;
// String stringText = "";
while ((StringBuffer = bufferReader.readLine()) != null) {
stringText += StringBuffer;
}
bufferReader.close();
textMsg.setText(stringText);
// textMsg.setText(string123);
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
textMsg.setText(e.toString());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
textMsg.setText(e.toString());
}
}

Error with a boolean method in my app

I am developing an app like Logo Quiz ... This is the activity, where you have to write the name of the logo:
public class Vie extends Activity implements OnClickListener {
ImageView img;
EditText et;
Button btn;
TextView txt;
MediaPlayer win_sound, wrong_sound;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.vie);
img = (ImageView) findViewById(R.id.img);
et = (EditText) findViewById(R.id.et);
btn = (Button) findViewById(R.id.btnCheck);
txt = (TextView) findViewById(R.id.txt);
win_sound = MediaPlayer.create(Vie.this, R.raw.win);
wrong_sound= MediaPlayer.create(Vie.this, R.raw.wrong);
setImageAndTagByIntent(img);
btn.setOnClickListener(this);
}
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
boolean mb = check(et, img);
Intent i = getIntent();
if (mb) {
// Sunet toast thread
txt.setText(title(img));
win_sound.start();
i.putExtra("score", "1");
setResult(RESULT_OK, i);
Thread t = new Thread() {
#Override
public void run() {
// TODO Auto-generated method stub
super.run();
try {
sleep(win_sound.getDuration());
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
} finally {
finish();
}
}
};
t.start();
}
if (!mb) {
// sunet toast thread
wrong_sound.start();
Toast t = Toast.makeText(getApplicationContext(),"Wrong answer! Please check if you have spelled corectly the name of the team!",Toast.LENGTH_LONG);
t.show();
}
}
private String title(ImageView img2) {
// TODO Auto-generated method stub
String s = (String) img2.getTag();
return s;
}
private void setImageAndTagByIntent(ImageView img2) {
// TODO Auto-generated method stub
// Trece si tagul!
Intent i = getIntent();
Bitmap back = i.getParcelableExtra("back");
Drawable b = new BitmapDrawable(getResources(), back);
img2.setImageDrawable(b);
String tag = i.getStringExtra("tag");
Object tag2 = (Object) tag;
img2.setTag(tag2);
}
private boolean check(EditText et2, ImageView img2) {
// TODO Auto-generated method stub
String s = et2.getText().toString();
s = WordUtils.capitalize(s);
String s1 = (String) img2.getTag();
boolean b;
if ((s1.contains("") && s.contentEquals(firstWord(s1)))||(s.contentEquals(s1) && !s1.contains(""))) {
b = true;
}else {
b=false;
}
return b;
}
private String firstWord(String s1) {
// TODO Auto-generated method stub
String arr[] = s1.split("//s");
return arr[0];
}
}
It works ... but when the name of the logo has two words and when I put only the first word, it says that it is wrong! It works only with the full name. Please Help Me!
Change the below condition:
private String firstWord(String s1) {
// TODO Auto-generated method stub
String arr[] = s1.split(" ");
return arr[0];
}
Also change your if condition:
((s1.contains(" ") && s.contentEquals(firstWord(s1)))||(s.contentEquals(s1) && !s1.contains(" ")))
I think it's a problem with your firstWord function. Try changing it to:
private String firstWord(String s1) {
String arr[] = s1.split(" ");
return arr[0];
}
Also, change this:
if ((s1.contains("") && s.contentEquals(firstWord(s1)))||(s.contentEquals(s1) && !s1.contains("")))
To:
if ((s1.contains(" ") && s.contentEquals(firstWord(s1)))||(s.contentEquals(s1) && !s1.contains(" ")))

Convert Text File to String in java

i have a written a code to send a text file by converting it into string and sending it into a web service. Please can someone tell me other available methods for sending the string as stream to Web Service.
public class MainActivity extends Activity {
Button b1;
String s;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b1=(Button)findViewById(R.id.button1);
b1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
File upfile=new File("sdcard/text/testfile.txt");
try {
FileInputStream fin=new FileInputStream(upfile);
byte[] buffer= new byte[(int)upfile.length()];
new DataInputStream(fin).readFully(buffer);
fin.close();
s=new String(buffer,"UTF-8");
System.out.print(buffer);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// TODO Auto-generated method stub
Toast.makeText(MainActivity.this, s, 20).show();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
try this.
public void mReadJsonData() {
try {
File f = new File("sdcard/text/testfile.txt");
FileInputStream is = new FileInputStream(f);
int size = is.available();
byte[] buffer = new byte[size];
is.read(buffer);
is.close();
String text = new String(buffer);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Use this code to read the data from file and get it into string and do your process ahead according to your need--
File upfile=new File("sdcard/text/testfile.txt");
try {
final BufferedReader reader = new BufferedReader(new FileReader(upfile));
String encoded = "";
try {
String line;
while ((line = reader.readLine()) != null) {
encoded += line;
}
}
finally {
reader.close();
}
System.out.print(encoded);
}
catch (final Exception e) {
}

How to embed an Internet Request Code and get results that are implemented within one OnClickListener

I am creating an Online Dictionary Android App.
I am using JSON to request for definitions for a word which the user inputs.
This input is into the variable "text" everytime the search button is clicked.
The Inputted word is then appended into the API request URL which returns the definition......which is stored in variable "result" in the bottom method OnPost Execute()
My TextView should then be set to this String.
I Therefore put the entire JSON and HTTPrequest code within the onClickLIstener because the user input always changes and requests everytime, but im getting an error at the "throws ClientProtocolException" after the "public JSONObject lastTweet(String word)" the error is "Syntax error on tokens, delete these tokens" I am Using Enclipse Indigo.
Here Is my Code:
public class Dictionary extends Activity {
String finalresult;
HttpClient client = new DefaultHttpClient();
TextView ansa;
JSONObject json;
Button Search;
EditText input;
String text;
final static String URL = "http://api.wordnik.com/v4/word.json/";
final static String URL2 = "/definitions?api_key=<MY API KEY>";
String fresult;
Dictionary dic = new Dictionary();
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.dictionary);
ansa = (TextView) findViewById(R.id.ansa);
input = (EditText) findViewById(R.id.input);
Search = (Button) findViewById(R.id.search);
Search.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
text = input.getText().toString();
public JSONObject lastTweet(String word)
throws ClientProtocolException, IOException, JSONException{
new Read().execute("text");
StringBuffer strBuff = new StringBuffer();
strBuff.append(URL);
strBuff.append(word);
strBuff.append(URL2);
HttpGet get = new HttpGet(strBuff.toString());
HttpResponse r = client.execute(get);
int status = r.getStatusLine().getStatusCode();
if (status == 200){
HttpEntity e = r.getEntity();
String data = EntityUtils.toString(e);
JSONArray timeline = new JSONArray(data);
JSONObject last = timeline.getJSONObject(0);
return last;
}else{
Toast.makeText(Dictionary.this, "error", Toast.LENGTH_LONG);
return null;
}
}
class Read extends AsyncTask<String, Integer, String>{
#Override
public String doInBackground(String... params) {
// TODO Auto-generated method stub
try {
json = lastTweet(text);
return json.getString(params[0]);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
fresult = result;
// TODO Auto-generated method stub
}
}
ansa.setText(fresult);
}
});
}
public JSONObject lastTweet(String word)
throws ClientProtocolException, IOException, JSONException{
new Read().execute("text");
StringBuffer strBuff = new StringBuffer();
strBuff.append(URL);
strBuff.append(word);
strBuff.append(URL2);
HttpGet get = new HttpGet(strBuff.toString());
HttpResponse r = client.execute(get);
int status = r.getStatusLine().getStatusCode();
if (status == 200){
HttpEntity e = r.getEntity();
String data = EntityUtils.toString(e);
JSONArray timeline = new JSONArray(data);
JSONObject last = timeline.getJSONObject(0);
return last;
}else{
Toast.makeText(Dictionary.this, "error", Toast.LENGTH_LONG);
return null;
}
}
class Read extends AsyncTask<String, Integer, String>{
#Override
public String doInBackground(String... params) {
// TODO Auto-generated method stub
try {
json = lastTweet(text);
return json.getString(params[0]);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(String result) {
fresult = result;
// TODO Auto-generated method stub
}
}
}
Any Suggestions?
Have you tried moving the request code to another class?

Categories

Resources