I am creating a little remote controller for my Android tablet. Basically I have a server that sends json containing a Youtube video ID.
In my android app I have a working background service, and I keep checking the id in a loop and whenever I get a new video id I try to pass it to the ACTION_VIEW intent. It only works once the app is launched. but whenever I send a new value, the service detects it and outputs it as log but the Youtube app doesn't get the new video.
Here is my code..
What am I missing exactly?
package com.example.testytbot;
import android.app.Activity;
import android.app.Application;
import android.app.IntentService;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.media.AudioManager;
import android.net.Uri;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.security.Provider;
import java.util.Timer;
import java.util.TimerTask;
import javax.net.ssl.HttpsURLConnection;
import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.Build;
import android.os.Handler;
import android.os.IBinder;
import android.os.SystemClock;
import android.support.annotation.RequiresApi;
import android.util.Log;
import android.view.KeyEvent;
import android.widget.Toast;
public class YT extends Service {
private static final String DEFAULT_EXTRA = "";
private final IBinder mBinder = new LocalBinder();
public class LocalBinder extends Binder {
YT getService() {
return YT.this;
}
}
public String oldvidID = "";
public int onStartCommand(Intent intent, int flags, int startId) {
new Timer().scheduleAtFixedRate(new TimerTask() {
#RequiresApi(api = Build.VERSION_CODES.O)
#Override
public void run() {
String url = "https://mywebsite.com/tv/vid";
JSONObject jObject = null;
try {
jObject = new JSONObject(getJSON(url));
try {
String theId = jObject.getString("id");
//System.out.println("THE ID IIIIIIIIIIIIIIIS:::: " + theId);
if (!theId.equals("") && !oldvidID.equals(theId)) {
System.out.println("Server ID :::: " + theId);
System.out.println("\nAPP ID :::: " + theId);
Intent intent;
intent = new Intent(Intent.ACTION_VIEW, Uri.parse("vnd.youtube://" + theId));
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
try {
getBaseContext().startActivity(intent);
} catch(ActivityNotFoundException e) {
System.out.println(e);
}
oldvidID = theId;
}
} catch (JSONException e) {
e.printStackTrace();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, 0, 4000);
return START_STICKY;
}
#Override
public IBinder onBind(Intent intent) {
return mBinder;
}
public static String getJSON(String url) {
HttpsURLConnection con = null;
try {
URL u = new URL(url);
con = (HttpsURLConnection) u.openConnection();
con.connect();
BufferedReader br = new BufferedReader(new InputStreamReader(con.getInputStream()));
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
sb.append(line + "\n");
}
br.close();
return sb.toString();
} catch (MalformedURLException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
} finally {
if (con != null) {
try {
con.disconnect();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
return null;
}
}
Thank you!
Related
I am trying to build an app for class and am having trouble with handling data that is gathered in another thread. The data does not seems to being passed through the handlers handleMessage method.
This is my main activity
import android.content.Context;
import android.content.res.Resources;
import android.os.Handler;
import android.os.Message;
import android.support.constraint.ConstraintLayout;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.FrameLayout;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URL;
import java.nio.Buffer;
import java.util.*;
public class MainActivity extends AppCompatActivity implements BookListFragment.OnFragmentInteractionListener {
ArrayList<Book> names;
private boolean twoPane = false;
BookListFragment blf;
BookDetailsFragment bdf;
// Handler bookHandler;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
twoPane = findViewById(R.id.container2) == null;
names = new ArrayList<Book>();
final EditText searchBar = findViewById(R.id.searchbar);
final Handler bookHandler = new Handler(new Handler.Callback() {
#Override
public boolean handleMessage(Message msg) {
String response = (String) msg.obj;
try{
JSONArray tmp = new JSONArray(response);
for(int i = 0; i < tmp.length(); i++){
JSONObject a = tmp.getJSONObject(i);
int id = a.getInt("book_id");
String title = a.getString("title");
Log.d("BOOK_id", a.getInt("book_id")+"");
String author = a.getString("author");
int published = a.getInt("published");
String coverUrl = a.getString("cover_url");
Book book = new Book(id,title,author,published,coverUrl);
names.add(book);
}
} catch (Exception e){
Log.d("FAIL", e.toString());
}
return false;
}
});
Thread t = new Thread(){
#Override
public void run() {
String searchString = searchBar.getText().toString();
URL bookURL;
try {
bookURL = new URL("https://kamorris.com/lab/audlib/booksearch.php?search="+searchString);
BufferedReader reader = new BufferedReader(new InputStreamReader(bookURL.openStream()));
String response = "",tmpResponse;
tmpResponse = reader.readLine();
while(tmpResponse != null){
response = response + tmpResponse;
tmpResponse = reader.readLine();
}
Log.d("Handler", response);
Message msg = Message.obtain();
msg.obj = response;
bookHandler.handleMessage(msg);
} catch (Exception e) {
Log.e("Fail", e.toString());
}
}
};
t.start();
Button button = findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Thread t = new Thread(){
#Override
public void run() {
String searchString = searchBar.getText().toString();
URL bookURL;
try {
bookURL = new URL("https://kamorris.com/lab/audlib/booksearch.php?search="+searchString);
BufferedReader reader = new BufferedReader(new InputStreamReader(bookURL.openStream()));
String response = "",tmpResponse;
tmpResponse = reader.readLine();
while(tmpResponse != null){
response = response + tmpResponse;
tmpResponse = reader.readLine();
}
JSONArray bookOBJ= new JSONArray(response);
Message msg = Message.obtain();
msg.obj = bookOBJ;
bookHandler.handleMessage(msg);
} catch (Exception e) {
Log.d("Fail", e.toString());
}
}
};
t.start();
}
});
}
The code is suppose to get data from an api and then in the handleMessage method it is suppose to parse the data into a book object that contains two int and three string variables. The problem is that the handler never executes any code.
The execution should be that the debugger log should have the response string with the data from the API and then the id of every book in the JSON file, but it only has the data from the api displayed.
Hi I want to control alarmManager time by json file
I copied this code from a blog but it did not work
and i wish someone help me to solve this problem i was tired of the many attempts and did not find the solution even if i add permission INTERNET and READ PHONE STATES Here is my code :
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.mypro.json/com.mypro.json.MainActivity}: java.lang.NumberFormatException: Invalid long: ""
brodreviv.java
import android.app.AlarmManager;
import android.app.AlertDialog;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.util.Log;
import org.json.JSONObject;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.util.concurrent.ExecutionException;
public class brodreviv extends BroadcastReceiver {
public brodreviv() {
}
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (Intent.ACTION_BOOT_COMPLETED.equals(action)) {
startServiceByAlarm(context);
}
}
public static void startServiceByAlarm(Context context) {
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(context, Sherlocs.class);
PendingIntent pendingIntent = PendingIntent.getService(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
long startTime = System.currentTimeMillis();
assert alarmManager != null;
final ParseJson parsejsons = new ParseJson();
try {
parsejsons.execute().get();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, startTime, Long.parseLong(parsejsons.getTimer1()), pendingIntent);
}
}
Sherlocs.java
import android.annotation.SuppressLint;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.support.annotation.Nullable;
import java.util.Objects;
import java.util.concurrent.ExecutionException;
public class Sherlocs extends Service {
#Override
public void onCreate() {
super.onCreate();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
scheduleAlarm();
return super.onStartCommand(intent, flags, startId);
}
#Override
public void onDestroy() {
super.onDestroy();
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#SuppressLint("NewApi")
public void scheduleAlarm() {
final ParseJson parsejsons = new ParseJson();
try {
parsejsons.execute().get();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (isAlarmWorking()) {
return;
}
((AlarmManager) Objects.requireNonNull(getSystemService(ALARM_SERVICE))).setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), Long.parseLong(parsejsons.getTimer2()), PendingIntent.getBroadcast(getApplicationContext(), 0, new Intent(getApplicationContext(), AlarmReciever.class), 0));
}
private boolean isAlarmWorking() {
boolean isWorking = false;
if (PendingIntent.getBroadcast(getApplicationContext(), 0, new Intent(getApplicationContext(), AlarmReciever.class), PendingIntent.FLAG_UPDATE_CURRENT) == null) {
isWorking = true;
}
return isWorking;
}
}
ParseJson.java
import android.os.AsyncTask;
import android.util.Log;
import org.json.JSONObject;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
public class ParseJson extends AsyncTask {
private String timer1 = "";
private String timer2 = "";
#Override
protected Object doInBackground(Object... params) {
this.parse();
return this;
}
private void parse()
{
Gethttp sh = new Gethttp();
String url = "https://api.myjson.com/bins/14z1pr";
String jsonStr = sh.makeServiceCall(url);
try {
JSONObject jsonRoot = new JSONObject(jsonStr);
timer1 = jsonRoot.getString("FirstAlarm");
timer2 = jsonRoot.getString("SecondAlarm");
}
catch(Exception e)
{
Log.d("FirstAlarm : ", "exception");
Log.d("SecondAlarm : ", "exception");
}
}
public String getTimer1()
{
return timer1;
}
public String getTimer2()
{
return timer2;
}
public class Gethttp {
private final String TAG = Gethttp.class.getSimpleName();
public Gethttp() {
}
public String makeServiceCall(String reqUrl) {
String response = null;
try {
URL url = new URL(reqUrl);
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
// read the response
InputStream in = new BufferedInputStream(conn.getInputStream());
response = convertStreamToString(in);
} catch (MalformedURLException e) {
Log.e(TAG, "MalformedURLException: " + e.getMessage());
} catch (ProtocolException e) {
Log.e(TAG, "ProtocolException: " + e.getMessage());
} catch (IOException e) {
Log.e(TAG, "IOException: " + e.getMessage());
} catch (Exception e) {
Log.e(TAG, "Exception: " + e.getMessage());
}
return response;
}
private String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line;
try {
while ((line = reader.readLine()) != null) {
sb.append(line).append('\n');
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
}}
myjson.json
{
"FirstAlarm": "20000",
"SecondAlarm": "50000"
}
In our android application we have photo album capabilities. Which users are able to create their albums from their photos and after that we want users to be able to create a pdf file from that albums.(We are doing the same thing in IOS)
For achiving this, I've implemented the below solution. But when I executed the createPrintableFile method it creates and empty pdf file and I couldnt find why?
Does anyone have any idea about it
package com.kidokit.kidokit.helper;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Rect;
import android.graphics.pdf.PdfDocument;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.print.PrintAttributes;
import android.print.pdf.PrintedPdfDocument;
import android.support.annotation.RequiresApi;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.Toast;
import com.kidokit.kidokit.R;
import com.kidokit.kidokit.network.NetworkModels;
import com.kidokit.kidokit.ui.StorybookView;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
public class MAPdfCreator
{
private FileOutputStream pdfFile = null;
private String filePath = null;
private Activity act;
private LayoutInflater inflater;
public MAPdfCreator(Activity act) throws FileNotFoundException
{
filePath = act.getFilesDir()+"/KidoKitAlbum.pdf";
pdfFile = new FileOutputStream(filePath);
this.act = act;
inflater = LayoutInflater.from(this.act);
}
public void createPrintableFile(List<NetworkModels.GetPhotosInAlbumRes.Photo> photos) throws IOException {
ArrayList<View> result = new ArrayList<View>();
int index = 0;
for (NetworkModels.GetPhotosInAlbumRes.Photo photo : photos) {
View myImageLayout = inflater.inflate(R.layout.view_storybook, null, false);
final StorybookView sbv = (StorybookView) myImageLayout.findViewById(R.id.sbv);
sbv.measure(480,853);
sbv.layout(0,0,480,853);
if (index == 0) {
/*
sbv.setTemplateLayout(R.layout.view_sb_cover);
sbv.setImage(photo.photoFile);
sbv.setLabel(photo.photoTitle);
sbv.setDate(photo.photoDate);
sbv.closeEditMode();
*/
} else {
sbv.setTemplateLayout(photo.getLayoutResource());
if (photo.photoFile != null && !photo.photoFile.equals("")) {
sbv.setImage(photo.photoFile);
}
if (photo.photoTitle != null) {
sbv.setLabel(photo.photoTitle);
}
if (photo.photoDate != null) {
sbv.setDate(photo.photoDate);
}
sbv.closeEditMode();
}
result.add(sbv);
index++;
}
convertViewsToPdf(result);
}
public void convertViewsToPdf(ArrayList<View> views) throws IOException {
if (Build.VERSION.SDK_INT >= 19) {
PrintAttributes printAttrs = new PrintAttributes.Builder().
setColorMode(PrintAttributes.COLOR_MODE_COLOR).
setMediaSize(PrintAttributes.MediaSize.NA_LETTER).
setResolution(new PrintAttributes.Resolution("KDK_LBL", "PRINT_SERVICE", 480, 853)).
setMinMargins(PrintAttributes.Margins.NO_MARGINS).
build();
PdfDocument document = new PdfDocument();
int index = 0;
for (View view : views) {
PdfDocument.PageInfo pageInfo = new PdfDocument.PageInfo.Builder(480,853,index).create();
PdfDocument.Page page = document.startPage(pageInfo);
view.draw(page.getCanvas());
document.finishPage(page);
index++;
}
document.writeTo(pdfFile);
document.close();
pdfFile.close();
File file = new File(filePath);
if(!file.exists()) {
System.out.println("FILE DOES NOT EXIST");
return;
}
this.openPdfFile();
}
}
public void openPdfFile()
{
Uri path = Uri.parse("content://"+act.getPackageName()+"/"+filePath);
Intent fileViewIntent = new Intent(Intent.ACTION_VIEW);
fileViewIntent.setDataAndType(path, "application/pdf");
String packageName = "com.adobe.reader";
fileViewIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
fileViewIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
try {
act.startActivity(fileViewIntent);
} catch(ActivityNotFoundException e){
try {
act.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id="+packageName)));
} catch (android.content.ActivityNotFoundException anfe) {
act.startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/details?id="+packageName)));
}
} catch(Exception e){
Toast.makeText(act, "Can not open file: (" + filePath +")", Toast.LENGTH_SHORT).show();
}
}
}
This is the code which calls the abow createPrintableFile method
private void printAlbum(final int albumId)
{
NetworkManager.getPhotosInAlbum(albumId,new TokenCallback<NetworkModels.GetPhotosInAlbumRes>() {
#Override
public void onResponse(Call<NetworkModels.GetPhotosInAlbumRes> call, Response<NetworkModels.GetPhotosInAlbumRes> response) {
super.onResponse(call, response);
if (response.code() == 200) {
if (response.body().success) {
NetworkModels.GetPhotosInAlbumRes result = response.body();
try {
MAPdfCreator creator = new MAPdfCreator(currrentContext);
creator.createPrintableFile(result.photos);
} catch (java.io.IOException e) {
e.printStackTrace();
}
} else {
activity.progressDialog.dismiss();
activity.showSnackbar(activity.getText(R.string.unknown_error).toString());
}
} else {
activity.showSnackbar(activity.getText(R.string.server_error).toString());
}
}
#Override
public void onFailure(Call<NetworkModels.GetPhotosInAlbumRes> call, Throwable t) {
super.onFailure(call, t);
activity.showSnackbar(activity.getText(R.string.connection_error).toString());
activity.progressDialog.dismiss();
}
});
}
Im new to Android and I need a little help. I have a class witch values from one table located on remote mysql and its working fine on 2.3 but on 4.x Im getting errors when I start it. I have read somewhere its because I`m not using AsyncTask. I tried to implement it on existing working code but there is one error, so please help because I tried everything to get this to work but no success.
Here is the existing code that works on 2.3
package com.stole.fetchtest;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ListActivity;
import android.net.ParseException;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ArrayAdapter;
import android.widget.Toast;
public class FetchData extends ListActivity {
#SuppressWarnings("unchecked")
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String result = null;
InputStream is = null;
StringBuilder sb = null;
ArrayList<?> nameValuePairs = new ArrayList<Object>();
List<String> r = new ArrayList<String>();
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(
"http://www.url.com/fetch.php");
httppost.setEntity(new UrlEncodedFormEntity(
(List<? extends NameValuePair>) nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
} catch (Exception e) {
Toast.makeText(getBaseContext(), e.toString(), Toast.LENGTH_LONG)
.show();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "UTF-8"));
sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
} catch (Exception e) {
Toast.makeText(getBaseContext(), e.toString(), Toast.LENGTH_LONG)
.show();
}
try {
JSONArray jArray = new JSONArray(result);
JSONObject json_data = null;
for (int i = 0; i < jArray.length(); i++) {
json_data = jArray.getJSONObject(i);
r.add(json_data.getString("names"));
}
setListAdapter(new ArrayAdapter<String>(this, R.layout.names_row, r));
} catch (JSONException e1) {
Toast.makeText(getBaseContext(), e1.toString(), Toast.LENGTH_LONG)
.show();
} catch (ParseException e1) {
Toast.makeText(getBaseContext(), e1.toString(), Toast.LENGTH_LONG)
.show();
}
}}
And then I tried to add AsyncTask, according to some tutorials found online, and it`s looking like this:
package com.stole.fetchtest;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ListActivity;
import android.net.ParseException;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ArrayAdapter;
import android.widget.Toast;
public class FetchData extends ListActivity {
String result = null;
InputStream is = null;
StringBuilder sb = null;
ArrayList<?> nameValuePairs = new ArrayList<Object>();
List<String> r = new ArrayList<String>();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
new task().execute();
}
public class task extends AsyncTask<String, String, Void> {
#SuppressWarnings("unchecked")
#Override
protected Void doInBackground(String... params) {
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://www.url.com/fetch.php");
httppost.setEntity(new UrlEncodedFormEntity(
(List<? extends NameValuePair>) nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
} catch (Exception e) {
Toast.makeText(getBaseContext(), e.toString(),
Toast.LENGTH_LONG).show();
}
try {
BufferedReader reader = new BufferedReader(
new InputStreamReader(is, "iso-8859-1"));
sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
} catch (Exception e) {
Toast.makeText(getBaseContext(), e.toString(),
Toast.LENGTH_LONG).show();
}
return null;
}
protected void onPostExecute(Void v) {
try {
JSONArray jArray = new JSONArray(result);
JSONObject json_data = null;
for (int i = 0; i < jArray.length(); i++) {
json_data = jArray.getJSONObject(i);
r.add(json_data.getString("naziv"));
}
setListAdapter(new ArrayAdapter(this, R.layout.names_row, r));
} catch (JSONException e1) {
Toast.makeText(getBaseContext(), e1.toString(),
Toast.LENGTH_LONG).show();
} catch (ParseException e1) {
Toast.makeText(getBaseContext(), e1.toString(),
Toast.LENGTH_LONG).show();
}
}
}
}
The error I`m getting is at
setListAdapter(new ArrayAdapter(this, R.layout.names_row, r));
and it says "The constructor ArrayAdapter(FetchData.task, int, List) is undefined"
Thanks!
it should use the activity context not the task context..
setListAdapter(new ArrayAdapter(FetchData.this, R.layout.names_row, r));
I am using a spinner when selected starts an intent and the class that is started gets and XML feed and displays it.
I am trying to call a different XML file based on what is selected by the user. I am not sure how the value can be passed to my XMLfunctions.java and once selected can the other classes reference that data?
HERE is my Eclipse Package Download
My thourghts were to have a multidimensional array with the titles for the spinner and the coinsiding XML url:
package com.patriotsar;
import android.app.Activity;
import android.content.Intent;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.Toast;
public class patriosar extends Activity {
private Button goButton;
private String array_spinner[];
String url = "http://www.patriotsar.com";
Intent i = new Intent(Intent.ACTION_VIEW);
Uri u = Uri.parse(url);
Context context = this;
Spinner areaspinner;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
array_spinner=new String[4];
array_spinner[0]="George Washington","gw.xml";
array_spinner[1]="BENJAMIN FRANKLIN","bf.xml";
array_spinner[2]="THOMAS JEFFERSON","tj.xml";
array_spinner[3]="PATRICK HENRY","ph.xml";
goButton = (Button)findViewById(R.id.goButton);
areaspinner = (Spinner) findViewById(R.id.areaspinner);
ArrayAdapter<String> adapter =
new ArrayAdapter<String> (this,
android.R.layout.simple_spinner_item,array_spinner);
areaspinner.setAdapter(adapter);
goButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v){
try {
// Start the activity
i.setData(u);
startActivity(i);
} catch (ActivityNotFoundException e) {
// Raise on activity not found
Toast.makeText(context, "Browser not found.", Toast.LENGTH_SHORT);
}
}
});
areaspinner.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
int item = areaspinner.getSelectedItemPosition();
if(item != 0){
Intent myIntent = new Intent(patriosar.this, ShowXMLPAR.class);
startActivityForResult(myIntent, 0);
}
else {
// finish();
}
}
public void onNothingSelected(AdapterView<?> arg0) {
}
});
}
}
I then have a listener that calls an intent ShowXMLPAR.class when an item other then default is selected. The ShowXMLPAR class calls a function from XMLfunctions.java class and then shows the data that is returned. So the second value in the selected array item needs to be passed to to both pages I guess.
ShowXMLPAR.java:
package com.patriotsar;
import java.util.ArrayList;
import java.util.HashMap;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import com.patriotsar.XMLfunctions;
import android.app.ListActivity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
public class ShowXMLPAR extends ListActivity {
private Button backButton;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.listplaceholder);
backButton = (Button)findViewById(R.id.backButton);
backButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view){
Intent myIntent = new Intent(view.getContext(), patriosar.class);
startActivityForResult(myIntent, 0);
}
});
ArrayList<HashMap<String, String>> mylist = new ArrayList<HashMap<String, String>>();
String xml = XMLfunctions.getXML();
Document doc = XMLfunctions.XMLfromString(xml);
int numResults = XMLfunctions.numResults(doc);
if((numResults <= 0)){
Toast.makeText(ShowXMLPAR.this, "Geen resultaten gevonden", Toast.LENGTH_LONG).show();
finish();
}
NodeList nodes = doc.getElementsByTagName("result");
for (int i = 0; i < nodes.getLength(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
Element e = (Element)nodes.item(i);
map.put("main_content", XMLfunctions.getValue(e, "content"));
map.put("name", XMLfunctions.getValue(e, "name"));
mylist.add(map);
}
//
ListAdapter adapter = new SimpleAdapter(ShowXMLPAR.this, mylist , R.layout.listlayout,
new String[] {"main_content", "name" },
new int[] { R.id.item_title, R.id.item_subtitle });
setListAdapter(adapter);
}
}
XMLfunctions.java:
package com.patriotsar;
import java.io.IOException;
import java.io.StringReader;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
public class XMLfunctions {
public final static Document XMLfromString(String xml){
Document doc = null;
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
try {
DocumentBuilder db = dbf.newDocumentBuilder();
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(xml));
doc = db.parse(is);
} catch (ParserConfigurationException e) {
System.out.println("XML parse error: " + e.getMessage());
return null;
} catch (SAXException e) {
System.out.println("Wrong XML file structure: " + e.getMessage());
return null;
} catch (IOException e) {
System.out.println("I/O exeption: " + e.getMessage());
return null;
}
return doc;
}
/** Returns element value
* #param elem element (it is XML tag)
* #return Element value otherwise empty String
*/
public final static String getElementValue( Node elem ) {
Node kid;
if( elem != null){
if (elem.hasChildNodes()){
for( kid = elem.getFirstChild(); kid != null; kid = kid.getNextSibling() ){
if( kid.getNodeType() == Node.TEXT_NODE ){
return kid.getNodeValue();
}
}
}
}
return "";
}
public static String getXML(){
String line = null;
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet httpPost = new HttpGet("http://www.patriotsar.com/patriot_quotes.xml");
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
line = EntityUtils.toString(httpEntity);
} catch (UnsupportedEncodingException e) {
line = "<results status=\"error\"><msg>Can't connect to server</msg></results>";
} catch (MalformedURLException e) {
line = "<results status=\"error\"><msg>Can't connect to server</msg></results>";
} catch (IOException e) {
line = "<results status=\"error\"><msg>Can't connect to server</msg></results>";
}
return line;
}
public static int numResults(Document doc){
Node results = doc.getDocumentElement();
int res = -1;
try{
res = Integer.valueOf(results.getAttributes().getNamedItem("count").getNodeValue());
}catch(Exception e ){
res = -1;
}
return res;
}
public static String getValue(Element item, String str) {
NodeList n = item.getElementsByTagName(str);
return XMLfunctions.getElementValue(n.item(0));
}
}
Sorry I am still learning but am excited to get into more advanced (for me) programming. Any Help would be awesome.
As of now the app works but calls the same xml no matter what.
I'm not following your description very well, but if you are wanting to pass data between Activities via Intents then make sure the data you pass can either be included as an Extra, or if you prefer to send actual objects then make sure your objects implement the Parcelable interface.