Using an async task to download xml into String[] - java

So I'm trying to get an AsyncTask to go out and grab three different XML files. The issue is, I don't know how to then bring them back out of the AsyncTask
There is the GetXML Class:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import android.os.AsyncTask;
public class GetXML extends AsyncTask<String,Integer,String[]> {
#Override
protected String[] doInBackground(String... params) {
// TODO Auto-generated method stub
String[] retreiver = new String[3];
try {
retreiver = getXMLs();
return retreiver;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
for(int i=0;i<retreiver.length;i++){
retreiver[i]="<object_list><object><title>ERROR</title></object></object_list>";
}
return retreiver;
}
private static String[] getXMLs() throws Exception {
String[] urls = new String[3];
urls[0] = "http://www.parkland.hostoi.com/XML_Files/indoor.xml";
urls[1] = "http://www.parkland.hostoi.com/XML_Files/outdoor.xml";
urls[2] = "http://www.parkland.hostoi.com/XML_Files/events.xml";
BufferedReader reader = null;
URLConnection uc = null;
int i = 0;
for(i=0;i<urls.length;i++){
try {
URL url = new URL(urls[i]);
uc = url.openConnection();
uc.connect();
reader = new BufferedReader(new InputStreamReader(uc.getInputStream()));
StringBuffer buffer = new StringBuffer();
int read;
char[] chars = new char[1024];
while ((read = reader.read(chars)) != -1)
buffer.append(chars, 0, read);
urls[i]= buffer.toString();
}
finally {
if (reader != null)
reader.close();
}
}
return urls;
}
And then... what's next? Currently I have this bit on my Main Activity and I know it is the part causing the problems:
String[] xmls = new String[3];
GetXML taskA = new GetXML();
try {
xmls = taskA.get();
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (ExecutionException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
But all this does is causes a crash or a timeout or something.... No errors are showing up in LogCat.
I just don't know. This is my first android project, and it is killing me.

You can try this:
String[] xmls = new String[3];
GetXML taskA = new GetXML();
try {
xmls = taskA.execute().get();
} catch (InterruptedException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (ExecutionException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}

Your Task not execute because you never executed,
Need to call
taskA .execute();
Refer Below:
In main Activity:
GetXML taskA = new GetXML();
taskA.execute();
Your AsyncTask is:
public class GetXML extends AsyncTask<String,Integer,String[]> {
#Override
protected String[] doInBackground(String... params) {
// TODO Auto-generated method stub
String[] retreiver = new String[3];
try {
retreiver = getXMLs();
return retreiver;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
for(int i=0;i<retreiver.length;i++){
retreiver[i]="<object_list><object><title>ERROR</title></object></object_list>";
}
return retreiver;
}
private String[] getXMLs() throws Exception {
String[] urls = new String[3];
urls[0] = "http://www.parkland.hostoi.com/XML_Files/indoor.xml";
urls[1] = "http://www.parkland.hostoi.com/XML_Files/outdoor.xml";
urls[2] = "http://www.parkland.hostoi.com/XML_Files/events.xml";
BufferedReader reader = null;
URLConnection uc = null;
int i = 0;
for(i=0;i<urls.length;i++){
try {
URL url = new URL(urls[i]);
uc = url.openConnection();
uc.connect();
reader = new BufferedReader(new InputStreamReader(uc.getInputStream()));
StringBuffer buffer = new StringBuffer();
int read;
char[] chars = new char[1024];
while ((read = reader.read(chars)) != -1)
buffer.append(chars, 0, read);
urls[i]= buffer.toString();
}
finally {
if (reader != null)
reader.close();
}
}
return urls;
}
#Override
protected void onPostExecute(String[] result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
String[] xmls = result;
}
}
Result is populated in onPostExecute
Require Permission in manifest:
<uses-permission android:name="android.permission.INTERNET"/>

A nice example can be found in the docs.
You need to call the execute() method on your task, not get().
I'd also recommend at least implementing the onPostExecute() method as well in your AsyncTask.

Related

Reading music from asset folder

My project is list of music that user can set as ringtone.
All of my music is located in raw and it works correctly and also my ringtone name is a text in raw "zeallist".
My problem is that how to put my music in asset folder.
Here is my code that play music from raw:
public ArrayList<SongInfo> getAllSong(Context context) {
ArrayList<SongInfo> listSong = new ArrayList<SongInfo>();
RingtonesSharedPreferences pref = new RingtonesSharedPreferences(
context);
Field[] fields = R.raw.class.getFields();
for (int i = 0; i < fields.length - 1; i++) {
SongInfo info = new SongInfo();
try {
String name = fields[i].getName();
if (!name.equals("ringtones")) {
info.setFileName(name + ".mp3");
info.setFavorite(pref.getString(info.getFileName()));
int audioResource = R.raw.class.getField(name).getInt(name);
info.setAudioResource(audioResource);
}
// info.setName(name);
} catch (Exception e) {
}
listSong.add(info);
}
InputStream inputStream = context.getResources().openRawResource(
R.raw.zeallist);
BufferedReader reader = new BufferedReader(new InputStreamReader(
inputStream));
try {
String line;
int i = 0;
while ((line = reader.readLine()) != null) {
listSong.get(i).setName(line);
i++;
}
} catch (Exception e) {
// TODO: handle exception
} finally {
try {
reader.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return listSong;
}
How to change this part of my code to read them from asset and return my listsong ?
Core part I have finished.Some details you need do yourself
public ArrayList<SongInfo> getAllSong(Context context) throws IOException {
ArrayList<SongInfo> listSong = new ArrayList<SongInfo>();
RingtonesSharedPreferences pref = new RingtonesSharedPreferences(context);
String[] files = context.getAssets().list("Your songs path");
for (int i = 0; i < files.length - 1; i++) {
SongInfo info = new SongInfo();
String name = files[i];
if (!name.equals("ringtones")) {
info.setFileName(name + ".mp3");
info.setFavorite(pref.getString(info.getFileName()));
/* int audioResource = R.raw.class.getField(name).getInt(name);
info.setAudioResource(audioResource);*/ //fileName is enough to you
}
// info.setName(name);
listSong.add(info);
}
InputStream inputStream = context.getAssets().open("Your zeallist path");
BufferedReader reader = new BufferedReader(new InputStreamReader(
inputStream));
try {
String line;
int i = 0;
while ((line = reader.readLine()) != null) {
listSong.get(i).setName(line);
i++;
}
} catch (Exception e) {
// TODO: handle exception
} finally {
try {
reader.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return listSong;
}
When you want to play corresponding music, you could do like this
public void play(MediaPlayer mediaPlayer, Context context, String musicName) throws IOException {
AssetFileDescriptor assetFileDescriptor = context.getAssets().openFd(musicName);
mediaPlayer.setDataSource(assetFileDescriptor.getFileDescriptor(),
assetFileDescriptor.getStartOffset(),
assetFileDescriptor.getLength());
mediaPlayer.prepare();
mediaPlayer.start();
}
Hope this will solve your problem .
Right click on res folder and Create new folder called raw. Now copy paste few .MP3 files inside it. Check those links for better understanding.
link1
link2
From Assest folder
public void playBeep() {
try {
if (mp.isPlaying()) {
mp.stop();
mp.release();
mp = new MediaPlayer();
}
AssetFileDescriptor descriptor = getAssets().openFd("mysong.mp3");
mp.setDataSource(descriptor.getFileDescriptor(), descriptor.getStartOffset(), descriptor.getLength());
descriptor.close();
mp.prepare();
mp.setVolume(1f, 1f);
mp.setLooping(true);
mp.start();
} catch (Exception e) {
e.printStackTrace();
}
}
You can read file from asset using AssetManager
AssetManager assetManager = getAssets();
String[] files = assetManager.list("");
Note that this file is String array. So don't forget to initialize new file for each element of the array before iterating over it.

How to get client ip which is connected to android mobile hotspot in java scoket?

Is there any way to get client ip which is connected to android hotspot in java scoket, i have to send input values to client ip on submit
Here what i tried :
private class AttemptSubmit {
public ArrayList<String> getClientList1() {
ArrayList<String> clientList = new ArrayList<>();
BufferedReader br = null;
try {
br = new BufferedReader(new FileReader("/proc/net/arp"));
String line;
while ((line = br.readLine()) != null) {
String[] clientInfo = line.split(" +");
String mac = clientInfo[3];
if (mac.matches("..:..:..:..:..:..")) {
clientList.add(clientInfo[0]);
// TODO Auto-generated method stub
Socket socket = null;
DataOutputStream dataOutputStream = null;
DataInputStream dataInputStream = null;
try {
socket = new Socket(clientInfo[0], 8888);
dataOutputStream = new DataOutputStream(socket.getOutputStream());
dataInputStream = new DataInputStream(socket.getInputStream());
dataOutputStream.writeUTF(editUsername.getText().toString());
dataOutputStream.writeUTF(editPassword.getText().toString());
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally{
if (socket != null){
try {
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (dataOutputStream != null){
try {
dataOutputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (dataInputStream != null){
try {
dataInputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
} catch (java.io.IOException aE) {
aE.printStackTrace();
return null;
}
return getClientList1();
}
Submit action :
btnSubmit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
AttemptSubmit attemptSubmit= new AttemptSubmit();
attemptSubmit.getClientList1();
}
});
The problem is, when i click on submit button i'm getting this error "Unfortunately,Aqua has stooped."

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) {
}

Using Http response between multiple classes in Android?

class XXX implements Runnable
{
String lat,lon,str,taluka_name;
int name;
HttpResponse response;
HttpEntity entity;
InputStream is = null;
Toast s1;
StringBuilder sb=null;
TextView v;
Spinner s;
public String result[];
TextView tv;
LinearLayout ll1;
int i;
ArrayList<Integer> croplist;
public XXX(String t_n,String [] res,LinearLayout ll,TextView tv1)
{
croplist= new ArrayList<Integer>();
taluka_name = t_n;
result = res;
ll1= ll;
tv = tv1;
}
#Override
public void run() {
// TODO Auto-generated method stub
HttpClient httpclient = new DefaultHttpClient();
HttpPost request = new HttpPost("http://10.0.2.2/proagri115.php");
List<NameValuePair>login=new ArrayList<NameValuePair>();
login.add(new BasicNameValuePair("location", taluka_name));
try
{
UrlEncodedFormEntity entity=new UrlEncodedFormEntity(login);
request.setEntity(entity);
}
catch (UnsupportedEncodingException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
try
{
response = httpclient.execute(request);
entity = response.getEntity();
is = entity.getContent();
System.out.println("Executed the request");
}
catch (ClientProtocolException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
e.printStackTrace();
System.out.println("");
}
catch(Exception e)
{
}
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
sb = new StringBuilder();
sb.append(reader.readLine() + "\n");
String line="0";
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
is.close();
str=sb.toString();
Log.e("log_tag", "Success converting result "+sb.toString());
}
catch(Exception e)
{
Log.e("log_tag", "Error converting result "+e.toString());
System.out.println(str+"I have executed");
result = str.split(">>");
System.out.println("length"+result.length);
for(i=0;i<result.length;i++)
{
System.out.println("\n"+i+"=="+result[i]);
}
System.out.println("Notified");
}
}
}
public class help extends Activity{
int j;
Intent i;
String s,taluka_name;
EditText edt,edt1,edt2;
Double lat,lon;
Spinner spin;
String [] re;
TextView tv;
Layout lt;
LinearLayout lt1;
XXX runnable;
public void onCreate(Bundle savedinstancestate)
{
super.onCreate(savedinstancestate);
setContentView(R.layout.help);
lt1 = (LinearLayout)findViewById(R.id.ll1);
s =(String)getIntent().getSerializableExtra("Rainfall");
taluka_name =(String)getIntent().getSerializableExtra("location");
System.out.println(s);
tv = new TextView(this);
tv.setText("Crops for Your Selected Area are");
lt1.addView(tv);
try
{
runnable = new XXX(taluka_name,re,lt1,tv);
Thread threadX = new Thread(runnable);
System.out.println("till this");
threadX.start();
System.out.println("In Waited");
try
{
wait(500);
}
catch (IllegalMonitorStateException e)
{
System.out.println("IllegalMonitorStateException");
}
catch (InterruptedException e)
{
System.out.println("InterruptedException");
}
System.out.println("Out of Waited");
}
catch(Exception e)
{
System.out.println("Error again "+e);
}
try{
System.out.println("Final Result will be");
for(j=0;j<runnable.result.length;j++)
{
tv = new TextView(this);
tv.setText(runnable.result[j]);
System.out.println(runnable.result[j]);
lt1.addView(tv);
}
}
catch(Exception e)
{
}
}
}
I have main activity and thread XXX. I want to use the result of httprequest in XXX thread to be used in Main activity.But before XXX completes its operation main thread executes and
I get NullpointerException . How should I use network response in main activity . I have tried "synchronized block" . But It works for methods of single class.
How should I solve this problem?
You should use a synchronization mechanism whenever two threads need to cooperate and exchange information.
You can use a Handler to post an action back to the UI thread when the HTTP request completes in the background thread or better yet perform the background work in AsyncTask.
Here is a general example:
private class AsyncTaskExample extends AsyncTask<Param, Progress, Result> {
#Override
protected Result doInBackground(Param... params) {
// Performs some computation in a background thread.
// Use publishProgress() to publish progress updates which
// will take place in the UI thread in onProgressUpdate().
return ...;
}
#Override
protected void onProgressUpdate(Progress... progress) {
// Update progress information. Run in the UI thread.
}
#Override
protected void onPostExecute(Result result) {
// Update on completion. Run in the UI thread.
}
}
Note that AsyncTask is a generic class and requires three parameters: Param for input data to the background computation, Result for the result of the computation and Progress to represent progress update information.
Note also that doInBackground() is the only abstract method in AsyncTask, so at minimum you must override just this one method. In most cases, you will find onPostExecute() and onProgressUpdate() very useful as well. For more overridable methods and details see AsyncTask.
Once you have defined a task class you can launch the computation it represents in the background by in the following way:
new AsyncTaskExample().execute(param1, param2, ...);
Passing parameters (of type Param) to execute(). Note that this must be done in the UI thread.
At minimum, you need to use Thread.join to wait for the thread to complete.. But that would block on your UI thread which is really bad. You should really just do this the android way and use an AsyncTask
Read this:
http://developer.android.com/resources/articles/painless-threading.html
Here is what you should do:
import android.os.AsyncTask;
public class XXX extends AsyncTask<Integer, Integer, String[]> {
String lat, lon, str, taluka_name;
int name;
HttpResponse response;
HttpEntity entity;
InputStream is = null;
Toast s1;
StringBuilder sb = null;
TextView v;
Spinner s;
public String result[];
TextView tv;
LinearLayout ll1;
int i;
ArrayList<Integer> croplist;
public XXX(String t_n, String[] res, LinearLayout ll, TextView tv1) {
croplist = new ArrayList<Integer>();
taluka_name = t_n;
result = res;
ll1 = ll;
tv = tv1;
}
#Override
protected String[] doInBackground(Integer... params) {
// TODO Auto-generated method stub
HttpClient httpclient = new DefaultHttpClient();
HttpPost request = new HttpPost("http://10.0.2.2/proagri115.php");
List<NameValuePair> login = new ArrayList<NameValuePair>();
login.add(new BasicNameValuePair("location", taluka_name));
try {
UrlEncodedFormEntity entity = new UrlEncodedFormEntity(login);
request.setEntity(entity);
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
response = httpclient.execute(request);
entity = response.getEntity();
is = entity.getContent();
System.out.println("Executed the request");
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
e.printStackTrace();
System.out.println("");
} catch (Exception e) {
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
sb = new StringBuilder();
sb.append(reader.readLine() + "\n");
String line = "0";
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
str = sb.toString();
Log.e("log_tag", "Success converting result " + sb.toString());
} catch (Exception e) {
Log.e("log_tag", "Error converting result " + e.toString());
System.out.println(str + "I have executed");
result = str.split(">>");
System.out.println("length" + result.length);
for (i = 0; i < result.length; i++) {
System.out.println("\n" + i + "==" + result[i]);
}
System.out.println("Notified");
}
return result;
}
}
Then from your activity call:
new XXX(taluka_name,re,lt1,tv).execute();
Now the tricky thing is you need to get that result back to your UI thread.. The easiest way is to put the AsyncTask within the activity as an inner class, then in onPostExecute of the asyncTask you just call some function from your activity.
If you want the AsyncTask in a seperate file then you need to pass a reference of your class to the constructor of the AsyncTask and then you can call any public method of your activity from the asyncTask. Just remember that you can only call the activities methods in onPostExecute and in onProgressUpdate (do not call UI methods in doInBackground)

Text Resources in Android sdk

I have book with lessons about android . Now i realize help screen when i have many text . In book type about text . that android sdk can use txt files with many text . and in book typed code but when im use him , it doesent work (my app launch but i dont have any text on screen ) what's wrong? Help with right variant . my code :
package com.lineage.goddess;
import java.io.InputStream;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class LineageHelpActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.help);
openRawResource();
InputStream iFile = getResources().openRawResource(R.raw.lineagehelp);
TextView helpText =(TextView) findViewById(R.id.TextView_HelpText);
String strFile = inputStreamToString(iFile);
helpText.setText(strFile);
}
private String inputStreamToString(InputStream iFile) {
// TODO Auto-generated method stub
return null;
}
private void openRawResource() {
// TODO Auto-generated method stub
}
}
Well... for one, you are returning null from inputStreamToString(...). You need to implement it correctly before you can expect it to return anything.
change
private String inputStreamToString(InputStream iFile) {
// TODO Auto-generated method stub
return null;
}
with
private String inputStreamToString(InputStream iFile)
{
Writer writer = new StringWriter();
if(iFile!=null)
{
char[] buffer = new char[1024];
try{
Reader reader = new BufferedReader(
new InputStreamReader(iFile, "UTF-8"));
int n;
while ((n = reader.read(buffer)) != -1) {
writer.write(buffer, 0, n);
}
} catch (UnsupportedEncodingException e) {
return e.toString();
} catch (IOException e) {
return e.toString();
}finally
{
try {
iFile.close();
} catch (IOException e) {
return e.toString();
}
}
}
String result = writer.toString();
return result;
}

Categories

Resources