I have a problem with my Android client/server app. I would like to connect devices by WiFi Direct and send through some media files.
I made an Activity and Service for both Client and Server. Code is below.
ServerActivity:
import java.util.ArrayList;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.wifi.WpsInfo;
import android.net.wifi.p2p.WifiP2pConfig;
import android.net.wifi.p2p.WifiP2pDevice;
import android.net.wifi.p2p.WifiP2pDeviceList;
import android.net.wifi.p2p.WifiP2pInfo;
import android.net.wifi.p2p.WifiP2pManager;
import android.net.wifi.p2p.WifiP2pManager.ActionListener;
import android.net.wifi.p2p.WifiP2pManager.Channel;
import android.net.wifi.p2p.WifiP2pManager.PeerListListener;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class ServerActivity extends Activity {
private WifiP2pManager wifiManager;
private Channel wifichannel;
private BroadcastReceiver wifiServerReceiver;
private IntentFilter wifiServerReceiverIntentFilter;
private WifiP2pConfig config;
private String deviceName;
private Intent intent;
PeerListListener myPeerListListener;
ArrayList<WifiP2pDevice> peers = new ArrayList<WifiP2pDevice>();
WifiP2pDeviceList peerList;
TextView text;
EditText et2;
Button button1;
ListView listView;
ArrayAdapter<String> BTArrayAdapter;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.server_activity);
// Block auto opening keyboard
this.getWindow()
.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
BTArrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1);
listView = (ListView) findViewById(R.id.listView1);
listView.setAdapter(BTArrayAdapter);
wifiManager = (WifiP2pManager) getSystemService(Context.WIFI_P2P_SERVICE);
wifichannel = wifiManager.initialize(this, getMainLooper(), null);
wifiServerReceiverIntentFilter = new IntentFilter();
;
wifiServerReceiverIntentFilter.addAction(WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION);
wifiServerReceiverIntentFilter.addAction(WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION);
wifiServerReceiverIntentFilter.addAction(WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION);
wifiServerReceiverIntentFilter
.addAction(WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION);
intent = null;
registerReceiver(wifiServerReceiver, wifiServerReceiverIntentFilter);
button1 = (Button) findViewById(R.id.button1);
button1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
wifiManager.discoverPeers(wifichannel, null);
wifiManager.requestPeers(wifichannel, new PeerListListener() {
#Override
public void onPeersAvailable(WifiP2pDeviceList peerList) {
peers.clear();
peers.addAll(peerList.getDeviceList());
}
});
for (int i = 0; i < peers.size(); i++) {
WifiP2pDevice device = peers.get(i);
deviceName = device.deviceName;
config = new WifiP2pConfig();
config.deviceAddress = device.deviceAddress;
config.wps.setup = WpsInfo.PBC;
wifiManager.connect(wifichannel, config, new ActionListener() {
#Override
public void onSuccess() {
Toast.makeText(
getApplicationContext(),
"Połączono z: " + deviceName + "\n Mac: "
+ config.deviceAddress, Toast.LENGTH_SHORT).show();
}
#Override
public void onFailure(int reason) {
Toast.makeText(getApplicationContext(), "Nie udało się połączyć",
Toast.LENGTH_SHORT).show();
}
});
}
wifiManager.requestConnectionInfo(wifichannel,
new WifiP2pManager.ConnectionInfoListener() {
#Override
public void onConnectionInfoAvailable(final WifiP2pInfo info) {
// TODO Auto-generated method stub
String groupOwnerAddress = info.groupOwnerAddress.getHostAddress();
Toast.makeText(getApplicationContext(),
"GroupOwnAddress: " + groupOwnerAddress, Toast.LENGTH_SHORT)
.show();
}
});
StartServer(null);
}
});
}
public void StartServer(View v) {
// Construct our Intent specifying the Service
intent = new Intent(this, ServerService.class);
startService(intent);
}
}
ServerService:
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import android.app.IntentService;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.widget.Toast;
public class ServerService extends IntentService {
Handler mHandler;
private int port = 2178;
ServerSocket welcomeSocket = null;
Socket socket = null;
public ServerService() {
super("ServerService");
mHandler = new Handler();
}
#Override
protected void onHandleIntent(Intent intent) {
try {
mHandler.post(new DisplayToast(this, "Creating ServerSocket.."));
welcomeSocket = new ServerSocket(port);
welcomeSocket.setReuseAddress(true);
mHandler.post(new DisplayToast(this, "Waiting for connection on port: "
+ welcomeSocket.getLocalPort()));
socket = welcomeSocket.accept();
// while(true && flag){
// socket = welcomeSocket.accept();
mHandler.post(new DisplayToast(this, "Coneccted!"));
// }
mHandler.post(new DisplayToast(this, "Succes!"));
} catch (IOException e) {
mHandler.post(new DisplayToast(this, "IOException"));
} catch (Exception e) {
mHandler.post(new DisplayToast(this, "Exception"));
}
mHandler.post(new DisplayToast(this, "ServerService"));
}
/*
public void onDestroy() {
try {
welcomeSocket.close();
socket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
stopSelf();
}*/
}
class DisplayToast2 implements Runnable {
private final Context mContext;
String mText;
public DisplayToast2(Context mContext, String text) {
this.mContext = mContext;
mText = text;
}
public void run() {
Toast.makeText(mContext, mText, Toast.LENGTH_SHORT).show();
}
}
ClientActivity:
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.wifi.p2p.WifiP2pDevice;
import android.net.wifi.p2p.WifiP2pInfo;
import android.net.wifi.p2p.WifiP2pManager;
import android.net.wifi.p2p.WifiP2pManager.Channel;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.Toast;
public class ClientActivity extends Activity {
Button button;
private WifiP2pManager wifiManager;
private Channel wifichannel;
private BroadcastReceiver wifiClientReceiver;
private IntentFilter wifiClientReceiverIntentFilter;
private WifiP2pInfo wifiInfo;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.client_activity);
// Block auto opening keyboard
this.getWindow()
.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
wifiManager = (WifiP2pManager) getSystemService(Context.WIFI_P2P_SERVICE);
wifichannel = wifiManager.initialize(this, getMainLooper(), null);
wifiClientReceiver = new WiFiClientBroadcastReceiver(wifiManager, wifichannel, this);
wifiClientReceiverIntentFilter = new IntentFilter();
;
wifiClientReceiverIntentFilter.addAction(WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION);
wifiClientReceiverIntentFilter.addAction(WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION);
wifiClientReceiverIntentFilter.addAction(WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION);
wifiClientReceiverIntentFilter
.addAction(WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION);
wifiInfo = null;
registerReceiver(wifiClientReceiver, wifiClientReceiverIntentFilter);
button = (Button) findViewById(R.id.button);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
StartClient(null);
}
});
}
public void setNetworkToReadyState(boolean status, WifiP2pInfo info, WifiP2pDevice device) {
wifiInfo = info;
// targetDevice = device;
// connectedAndReadyToSendFile = status;
}
public void StartClient(View v) {
Intent intent = new Intent(this, ClientService.class);
intent.putExtra("wifiInfo", wifiInfo);
if (wifiInfo == null) {
Toast.makeText(this, "WifiInfo = null!", Toast.LENGTH_SHORT).show();
}
startService(intent);
}
}
ClientService:
import java.io.IOException;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import android.app.IntentService;
import android.content.Context;
import android.content.Intent;
import android.net.wifi.p2p.WifiP2pInfo;
import android.os.Handler;
import android.widget.Toast;
public class ClientService extends IntentService {
Handler mHandler;
private WifiP2pInfo wifiInfo;
private int port = 2178;
Socket clientSocket = null;
OutputStream os = null;
public ClientService() {
super("ClientService");
mHandler = new Handler();
}
#Override
protected void onHandleIntent(Intent intent) {
wifiInfo = (WifiP2pInfo) intent.getExtras().get("wifiInfo");
InetAddress targetIP = wifiInfo.groupOwnerAddress;
clientSocket = new Socket();
if(wifiInfo.isGroupOwner)
{
try {
mHandler.post(new DisplayToast(this, "Try to connect: /N IP: " + targetIP + "/nPort: " +port));
clientSocket.connect(new InetSocketAddress(targetIP, port));
mHandler.post(new DisplayToast(this, "Connected!"));
//os = clientSocket.getOutputStream();
} catch (IOException e) {
mHandler.post(new DisplayToast(this, "serwer IOException: " + e.getMessage()));
} catch (Exception e) {
mHandler.post(new DisplayToast(this, "serwer Exception"));
}
}else{
mHandler.post(new DisplayToast(this, "Group owner = " + wifiInfo.isGroupOwner));
}
}
/*
public void onDestroy()
{
try {
os.close();
clientSocket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
stopSelf();
}*/
}
class DisplayToast implements Runnable {
private final Context mContext;
String mText;
public DisplayToast(Context mContext, String text) {
this.mContext = mContext;
mText = text;
}
public void run() {
Toast.makeText(mContext, mText, Toast.LENGTH_SHORT).show();
}
}
AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="14"
android:targetSdkVersion="21" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".AppModeSelection"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service
android:name=".ServerService"
android:exported="false" />
<service
android:name=".ClientService"
android:exported="false" />
<activity android:name=".ServerActivity" >
</activity>
<activity android:name=".ClientActivity" >
</activity>
</application>
</manifest>
I am using two phones with WiFi Direct (Samsung GT-I9505 Android 4.4.2 and Samsung GT-I8190N Adroid 4.1.2). First of all I turned off all connections (BT, WIFI) and then connected by WiFi Direct. GT-I9505 is Server and other one is Client. While establishing a connection IOException error appears:
IOException: failed to connect to /192.168.49.1 (port 2178): connect failed: ECONNREFUSED (Connection refused)
I tried to use plenty of others Pors but nothing works. What I did wrong?
Thank you in advance for any help!
UPDATE:
I noticed that when I disconnect WiFi direct and connect again but in other direction it works but only for moment.
the main issue with your code is that you do need to make it event driven, in the current state I'm surprised that it even does anything really.
So, please try making it to something like following:
1. Start Discovering peers, once you get Peers Changed event, then do requestPeers
2. if you need some listener etc. to be ready for you on the other side, then you likely would identify those devices by advertising a service, so next look start discovery for services.
3. After you get service discovered, start 5-second timer to wait for any additional, reset the timer after each service discovered, and once the timer finally gets to run uninterrupted 5 seconds, you likely have discovered all services available at that time.
4. Select ONE service and connect to that device (you can not have multiple connection really).
5. Once you get event that you are connected, then use requestConnectionInfo to get info for the connection.
Then do remember that before you start you need to create the local service, so the other side can see it. Then, if your device gets selected as Group owner, you could keep the advertisement on, and let more clients connect to you. But if you are selected as Client, then you can not have incoming connections, so you should get rid of the advertisement.
Related
Working on an app that is supposed to generate random characters via a broadcast. I need to broadcast the random characters generated by my custom service, so that the main activity registered to intercept the broadcast can get the random numbers and display them on an EditText. The layout is shown here: app layout
The start button will trigger the random character generator service. The EditText will display the random numbers generated in real time (without any button press). The stop button will stop the service. The EditText won’t display any numbers. I have created a service(RandomCharacterService) and registered it in my manifest. Upon running the app, my app crashes. I am sure it is because I did not register my broadcast in my manifest, but I do not understand how to do that. And perhaps there is something wrong with how I am handling the broadcast in my main activity. In my button click method for the start button, I tried to do a for-loop, but this resulted in the app crashing as well.
AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.cs7455rehmarazzaklab8">
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name=".RandomCharacterService"></service>
</application>
MainActivityjava:
package com.example.cs7455rehmarazzaklab8;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.content.BroadcastReceiver;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.support.constraint.ConstraintLayout;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.Toast;
import java.util.Random;
public class MainActivity extends AppCompatActivity
{
private Button btnStart, btnStop;
private EditText myTV;
private Intent serviceIntent;
private RandomCharacterService myService;
private ServiceConnection myServiceConnection;
private boolean isServiceOn; //checks if the service is on
private int myRandomCharacter;
char MyRandomCharacter = (char)myRandomCharacter;
private boolean isRandomGeneratorOn;
private final int MIN = 65;
char m = (char)MIN;
private final int MAX = 26;
char x = (char)MAX;
private final String TAG = "Random Char Service: ";
private final String alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
private Context mContext;
private Random mRandom = new Random();
// Initialize a new BroadcastReceiver instance
private BroadcastReceiver mRandomCharReceiver = new BroadcastReceiver()
{
#Override
public void onReceive(Context context, Intent intent) {
// Get the received random number
myRandomCharacter = intent.getIntExtra("RandomCharacter",-1);
// Display a notification that the broadcast received
Toast.makeText(context,"Received : " + myRandomCharacter,Toast.LENGTH_SHORT).show();
}
};
#Override
protected void onCreate(Bundle savedInstanceState)
{
requestWindowFeature(Window.FEATURE_ACTION_BAR);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Get the application context
mContext = getApplicationContext();
btnStart = (Button) findViewById(R.id.StartButton);
btnStop = (Button) findViewById(R.id.StopButton);
myTV = (EditText)findViewById(R.id.RandomCharText);
// Register the local broadcast
LocalBroadcastManager.getInstance(mContext).registerReceiver(mRandomCharReceiver, new IntentFilter("BROADCAST_RANDOM_CHARACTER"));
// Change the action bar color
getSupportActionBar().setBackgroundDrawable(new ColorDrawable(Color.parseColor("#FFFF00BF")));
// Set a click listener for start button
btnStart.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
isServiceOn = true;
serviceIntent = new Intent(getApplicationContext(), RandomCharacterService.class);
startService(serviceIntent);
setRandomNumber();
// Generate a random char
myRandomCharacter = new Random().nextInt(x)+m;
// Initialize a new intent instance
Intent intent = new Intent("BROADCAST_RANDOM_CHARACTER");
// Put the random character to intent to broadcast it
intent.putExtra("RandomCharacter",myRandomCharacter);
// Send the broadcast
LocalBroadcastManager.getInstance(mContext).sendBroadcast(intent);
// Update the TextView with random character
myTV.setText(" " + myRandomCharacter );
}
});
btnStop.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view)
{
isServiceOn = false;
stopService(serviceIntent);
}
});
}
private void setRandomNumber()
{
myTV.setText("Random Character: " + (char)myService.getRandomCharacter());
String alphabet = myTV.getText().toString();
}
}
RandomCharacterService.java:
package com.example.cs7455rehmarazzaklab8;
import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.support.annotation.IntDef;
import android.support.annotation.Nullable;
import android.util.Log;
import java.util.Random;
public class RandomCharacterService extends Service
{
private int myRandomCharacter;
char MyRandomCharacter = (char)myRandomCharacter;
private boolean isRandomGeneratorOn;
private final int MIN = 65;
char m = (char)MIN;
private final int MAX = 26;
char x = (char)MAX;
private final String TAG = "Random Char Service: ";
private final String alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
class RandomCharacterServiceBinder extends Binder{
public RandomCharacterService getService()
{
return RandomCharacterService.this;
}
}
private IBinder myBinder = new RandomCharacterServiceBinder();
#Override
public int onStartCommand(Intent intent, int flags, int startId)
{
Log.i(TAG, "In OnStartCommand Thread ID is "+Thread.currentThread().getId());
isRandomGeneratorOn = true;
new Thread(new Runnable()
{
#Override
public void run()
{
startRandomGenerator();
}
}
).start();
return START_STICKY;
}
private void startRandomGenerator()
{
while(isRandomGeneratorOn)
{
char alphabet = 'A';
for (int i = 65; i < 90; i++)
{
try
{
Thread.sleep(1000);
if(isRandomGeneratorOn)
{
alphabet++;
myRandomCharacter = new Random().nextInt(x)+m;
Log.i(TAG, "Thread ID is "+Thread.currentThread().getId() + ", Random character is "+(char)myRandomCharacter);
}
}
catch(InterruptedException e)
{
Log.i(TAG, "Thread Interrupted.");
}
}
}
}
private void stopRandomGenerator()
{
isRandomGeneratorOn = false;
}
public int getRandomCharacter()
{
return myRandomCharacter;
}
public boolean isRandomGeneratorOn() {
return isRandomGeneratorOn;
}
#Override
public void onDestroy()
{
super.onDestroy();
stopRandomGenerator();
Log.i(TAG, "Service Destroyed.");
}
#Nullable
#Override
public IBinder onBind(Intent intent)
{
Log.i(TAG, "In onBind ...");
return myBinder;
}
}
Call Stack:callstack from running the app
Call Stack from attempting to press the stop button:crash from attempting to press stop button
Since you are using the bound service (using Ibinder). You will have to start the service by calling bindService instead of startService. But before that you need to initialize your ServiceConnection variable and better use the isServiceOn boolean as in the below example.
private ServiceConnection myServiceConnection = new ServiceConnection() {
#Override
// IBinder interface is through which we receive the service object for communication.
public void onServiceConnected(ComponentName name, IBinder binder) {
RandomCharacterServiceBinder myBinder = (RandomCharacterServiceBinder) binder;
isServiceOn = true;
myService = myBinder.getService();
Toast.makeText(context,"Service connected", Toast.LENGTH_SHORT).show();
}
#Override
public void onServiceDisconnected(ComponentName name) {
isServiceOn = false;
myService = null;
}
};
After onServiceConnected is called, you will get your service object. Most probably your service will be initialized before you perform a click. But just to ensure you can TOAST some message within it.
And you should start the service in Activity's onCreate method, so service will get some time in creation. So move the below code from you click listener to onCreate method.
serviceIntent = new Intent(getApplicationContext(), RandomCharacterService.class);
// startService(serviceIntent); <-- remove this line, call bindService
bindService(intent, myServiceConnection, Context.BIND_AUTO_CREATE);
and wait for the service connection Toast to appear.
I searched the web for examples displaying pdf documents within a app. Additionally i searched for a Downloader class because i want to load the pdf from the internet. After execution it just displays blank PDF page.
MainActivity.java just sends the pdf link to the DisplayPDF.java Activity:
package com.example.pdfviewevaluation;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
public final static String EXTRA_MESSAGE = "com.example.pdfviewevaluation.MESSAGE";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent intent = new Intent(this, DisplayPDF.class);
String url = "pdf link";
intent.putExtra(EXTRA_MESSAGE, url);
startActivity(intent);
}
}
DisplayPDF.java creates the Folder and PDF in the cache directory. Then it starts the Downloader with the pdf link and directory. Finally it should just show the pdf:
package com.example.pdfviewevaluation;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.ExecutionException;
public class DisplayPDF extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_display_pdf);
String pdfURL = getIntent().getStringExtra(MainActivity.EXTRA_MESSAGE);
File folder = new File(this.getCacheDir(), "pdf");
folder.mkdir();
File file = new File(folder, "Read.pdf");
try {
file.createNewFile();
} catch (IOException e1) {
e1.printStackTrace();
}
Downloader dl = new Downloader(pdfURL, file);
try {
dl.execute().get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
showPdf();
}
public void showPdf() {
File file = new File(this.getCacheDir()+"/pdf/Read.pdf");
PackageManager packageManager = getPackageManager();
Intent testIntent = new Intent(Intent.ACTION_VIEW);
testIntent.setType("application/pdf");
List list = packageManager.queryIntentActivities(testIntent, PackageManager.MATCH_DEFAULT_ONLY);
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
Uri uri = FileProvider.getUriForFile(this.getApplicationContext(), this.getApplicationContext().getPackageName() + ".provider", file);
intent.setDataAndType(uri, "application/pdf");
startActivity(intent);
}
}
Downloader.java connects to the pdf page and download the pdf from the given link to the desired directory:
package com.example.pdfviewevaluation;
import android.os.AsyncTask;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class Downloader extends AsyncTask<Void,Void,Void> {
private String fileURL;
private File directory;
public Downloader(String fileURL, File directory)
{
this.fileURL = fileURL;
this.directory = directory;
}
protected Void doInBackground(Void... params) {
try {
FileOutputStream f = new FileOutputStream(directory);
URL u = new URL(fileURL);
HttpURLConnection c = (HttpURLConnection) u.openConnection();
c.setRequestMethod("GET");
c.setDoOutput(true);
c.connect();
InputStream in = c.getInputStream();
byte[] buffer = new byte[1024];
int len1 = 0;
int i = 0;
while ((len1 = in.read(buffer)) > 0) {
f.write(buffer, 0, len1);
}
f.close();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
After many hours spending on my problem i searched for another solution on YouTube. These one are showing the solution:
https://www.youtube.com/watch?v=pGlqHeB5hdk
https://www.youtube.com/watch?v=8YPJCOxiklQ
AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.downloadingfiles">
<uses-sdk android:minSdkVersion="21"
android:targetSdkVersion="22" />
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
MainActivity.java:
import android.app.DownloadManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.Matrix;
import android.graphics.Rect;
import android.graphics.pdf.PdfRenderer;
import android.net.Uri;
import android.os.Environment;
import android.os.ParcelFileDescriptor;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.webkit.MimeTypeMap;
import android.webkit.URLUtil;
import android.widget.ImageView;
import android.widget.Toast;
import java.io.File;
public class MainActivity extends AppCompatActivity {
String myUrl = "http://www.orimi.com/pdf-test.pdf";
private ImageView imageView;
private int currentPage = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
registerReceiver(onComplete, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
DownloadManager.Request request = new DownloadManager.Request(Uri.parse(myUrl));
request.setTitle("File download.");
request.setDescription("File is being downloaded...");
request.allowScanningByMediaScanner();
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
String nameOfFile = URLUtil.guessFileName(myUrl, null, MimeTypeMap.getFileExtensionFromUrl(myUrl));
request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, nameOfFile);
DownloadManager manager = (DownloadManager) this.getSystemService(Context.DOWNLOAD_SERVICE);
manager.enqueue(request);
}
BroadcastReceiver onComplete=new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
render();
}
};
/**Called when the user clicks the "Next" button defined in activity_main.xml */
public void nextPage(View view) {
currentPage++;
render();
}
/**Called when the user clicks the "Previous" button defined in activity_main.xml */
public void previousPage(View view) {
currentPage--;
render();
}
private void render(){
try{
imageView = (ImageView) findViewById(R.id.image);
int REQ_WIDTH = imageView.getWidth();
int REQ_HEIGHT = imageView.getHeight();
Bitmap bitmap = Bitmap.createBitmap(REQ_WIDTH, REQ_HEIGHT, Bitmap.Config.ARGB_4444);
String nameOfFile = URLUtil.guessFileName(myUrl, null, MimeTypeMap.getFileExtensionFromUrl(myUrl));
File file = new File("/sdcard/Download/"+nameOfFile);
PdfRenderer renderer = new PdfRenderer(ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY));
if(currentPage < 0){
currentPage = 0;
}else if(currentPage >= renderer.getPageCount()){
currentPage = renderer.getPageCount() - 1;
}
Matrix m = imageView.getImageMatrix();
Rect rect = new Rect(0, 0, REQ_WIDTH, REQ_HEIGHT);
renderer.openPage(currentPage).render(bitmap, rect, m, PdfRenderer.Page.RENDER_MODE_FOR_DISPLAY);
imageView.setImageMatrix(m);
imageView.setImageBitmap(bitmap);
imageView.invalidate();
} catch (Exception e){
e.printStackTrace();
}
}
}
I have write some code for receiving data from Bluetooth module (HC-05), I want to read string '#900~' from Arduino, but I get nothing in response. I have made a connection with module, but nothing more. I need only reading on Android. It is probably easy task but I cannot get across :/. What am I doing wrong? it Below is my code:
package nichten.pneumobil;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.os.Handler;
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.TextView;
import android.widget.Toast;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Set;
import java.util.UUID;
public class MainApplication extends AppCompatActivity {
boolean doubleBackToExitPressedOnce = false;
private BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
static BluetoothSocket mmSocket;
static BluetoothDevice mmDevice;
static OutputStream mmOutputStream;
static InputStream mmInputStream;
private static final UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805f9b34fb");
private String BTdevice = "POJAZD1";
private boolean polaczenie = false;
Handler bluetoothIn;
final int handlerState = 0;
private ConnectedThread mConnectedThread;
private StringBuilder recDataString = new StringBuilder();
private Button btnModuleConnect;
private TextView txtModuleConnect;
private TextView txtTest;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_application);
btnModuleConnect = (Button) findViewById(R.id.btnModuleConnect);
txtModuleConnect = (TextView) findViewById(R.id.txtModuleConnect);
txtTest = (TextView) findViewById(R.id.txtTest);
if (!mBluetoothAdapter.isEnabled()) {
mBluetoothAdapter.enable();
}
btnModuleConnect.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
if (connectWithModule())
txtModuleConnect.setText("Connection status: Connected");
else
txtModuleConnect.setText("Connection status: Module not found");
} catch(IOException e){
e.printStackTrace();
}
}
});
bluetoothIn = new Handler() {
public void handleMessage(android.os.Message msg) {
if (msg.what == handlerState) {
String readMessage = (String) msg.obj;
recDataString.append(readMessage);
int endOfLineIndex = recDataString.indexOf("~");
if (endOfLineIndex > 0) {
String dataInPrint = recDataString.substring(0, endOfLineIndex);
int dataLength = dataInPrint.length();
if (recDataString.charAt(0) == '#')
{
txtTest.setText(recDataString);
}
recDataString.delete(0, recDataString.length());
dataInPrint = " ";
}
}
}
};
}
#Override
public void onBackPressed() {
if (doubleBackToExitPressedOnce) {
disconnectWithModule();
mBluetoothAdapter.disable();
finish();
}
this.doubleBackToExitPressedOnce = true;
Toast.makeText(this, "Please click BACK again to exit", Toast.LENGTH_SHORT).show();
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
doubleBackToExitPressedOnce=false;
}
}, 2000);
}
public boolean connectWithModule() throws IOException {
if(polaczenie){
try {
mmSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
mmDevice = null;
mmSocket = null;
mBluetoothAdapter = null;
}
Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
if (pairedDevices.size() > 0) {
for (BluetoothDevice device : pairedDevices) {
if(device.getName().equals(BTdevice)){
mmDevice = device;
break;
}
}
}
if (mmDevice != null) {
try {
mmSocket = mmDevice.createRfcommSocketToServiceRecord(uuid);
mmSocket.connect();
Toast.makeText(getApplicationContext(), "Połączono!", Toast.LENGTH_SHORT).show();
polaczenie = true;
mmOutputStream = mmSocket.getOutputStream();
mmInputStream = mmSocket.getInputStream();
return true;
} catch (Exception e2) {
Toast.makeText(getApplicationContext(),"Nie udało się połaczyć.", Toast.LENGTH_SHORT).show();
mmDevice = null;
try {
mmSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
mmSocket = null;
}
}
else if (mmDevice == null){
Toast.makeText(getApplicationContext(), "Nie ma sparowanych urządzeń.", Toast.LENGTH_SHORT).show();
polaczenie = false;
}
return false;
}
public void disconnectWithModule(){
if (polaczenie) {
try {
mmSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private class ConnectedThread extends Thread{
private final InputStream mmInStream;
private final OutputStream mmOutStream;
public ConnectedThread(BluetoothSocket socket) {
InputStream tmpIn = null;
OutputStream tmpOut = null;
try {
tmpIn = socket.getInputStream();
tmpOut = socket.getOutputStream();
} catch (IOException e) { }
mmInStream = tmpIn;
mmOutStream = tmpOut;
}
public void run() {
byte[] buffer = new byte[256];
int bytes;
while (true) {
try {
bytes = mmInStream.read(buffer);
String readMessage = new String(buffer, 0, bytes);
bluetoothIn.obtainMessage(handlerState, bytes, -1, readMessage).sendToTarget();
} catch (IOException e) {
break;
}
}
}
//write method
public void write(String input) {
byte[] msgBuffer = input.getBytes();
try {
mmOutStream.write(msgBuffer);
} catch (IOException e) {
Toast.makeText(getBaseContext(), "Connection Failure", Toast.LENGTH_LONG).show();
finish();
}
}
}
}
I am a beginner in Android (only 2 days with it :P), but I have no idea what to do. I also include my AndroidManifest, my other Activity, maybe it would help to find out what is wrong:
package nichten.pneumobil;
import android.bluetooth.BluetoothAdapter;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button btnNextScreen = (Button) findViewById(R.id.btnNextScreen);
btnNextScreen.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent nextScreen = new Intent(getApplicationContext(), MainApplication.class);
startActivity(nextScreen);
}
});
}
}
And manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="nichten.pneumobil">
<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity"
android:screenOrientation="landscape">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".MainApplication"
android:screenOrientation="landscape">
</activity>
</application>
</manifest>
Please help, as the code below that should send a GET request does not work.
Behaviour: after tapping the button it writes "Running", then uses some traffic, then after some time hangs and crashes.
My goal is to send HTTP GET and handle the response as a string. I have tried a lot of options but they failed.
I'll greatly appreciate any working way of HTTP requests that NOT run in the UI (main) thread. Requests in the main thread are no more allowed and throw a networkonmainthreadexception.
Thanks in advance!
AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity"
android:screenOrientation="portrait">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<uses-permission android:name="android.permission.INTERNET" />
MainActivity.java (I'll delete waste imports later):
package com.aohdhgdsb.helloworld;
import android.app.DownloadManager;
import android.content.Context;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.ImageView;
import android.widget.Toast;
import android.os.Handler;
import android.widget.TextView.OnEditorActionListener;
import android.view.inputmethod.EditorInfo;
import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import javax.net.ssl.HttpsURLConnection;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import android.os.AsyncTask;
import java.io.InputStream;
import java.net.URLConnection;
public class MainActivity extends AppCompatActivity {
public EditText Edit1;
public EditText Edit2;
public TextView Text1;
public ImageView Img1;
public Button But1;
#Override
protected void onCreate(Bundle savedInstanceState) {
showToast("Hi. I have started!\r\nv6");
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void showToast(String toast){
try {
Toast toast2 = Toast.makeText(getApplicationContext(),
"" + toast,
Toast.LENGTH_SHORT);
//toast2.setGravity(Gravity.TOP, 0, 0);
toast2.show();
} catch (Throwable e) {
showToast("Error while showing the toast!");
/*
Toast toast3 = Toast.makeText(getApplicationContext(),
"TOAST ERR: " + e,
Toast.LENGTH_LONG);
toast3.show();
*/
}
}
public String readStream(InputStream is) {
try {
ByteArrayOutputStream bo = new ByteArrayOutputStream();
int i = is.read();
while(i != -1) {
bo.write(i);
i = is.read();
}
return bo.toString();
} catch (IOException e) {
return "";
}
}
public void Go(View v) {
handleResponse("Running...");
Thread thread = new Thread(new Runnable(){
#Override
public void run() {
//******************************************
try{
URL url = new URL("http://example.com/");
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
try{
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
handleResponse(readStream(in));
} catch (Throwable e) {showToast("ERROR7: " + e);}
finally {
urlConnection.disconnect();
}
} catch (Throwable e) {
showToast("ERROR6: " + e);
}
//****************************************
}
});
thread.start();
}
public void handleResponse(String str){
Edit2 = (EditText) findViewById(R.id.editText2);
Edit2.setText(str);
}
}
Part of activity_main.xml:
<Button
style="?android:attr/buttonStyleSmall"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Go!"
android:id="#+id/button3"
android:layout_gravity="center_horizontal"
android:onClick="Go" />
<EditText
android:layout_width="match_parent"
android:layout_height="256dp"
android:id="#+id/editText2"
android:layout_gravity="center_horizontal"
android:layout_weight="8.25"
android:text="Nothing" />
Try using AsyncTask, simple example:
public class MyAsyncTask extends AsyncTask<String, Void, String> {
Context context;
//Constructor
public AsyncWS(Context context) {
this.context = context;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
//BEFORE Execution
//initialize a ProgressDialog, ...
}
#Override
protected String doInBackground(String... args) {
//MAke all the http calls
return result; //This is going to be sent to onPostExecute
}
#Override
protected void onPostExecute(String result) {
//After Execution, here you are working again in the main thread
super.onPostExecute(result);
//Make toasts, change views, stop ProgressDialogs
}
}
Call it with:
MyAsyncTask myAsyncTask = new MyAsyncTask (context);
myAsyncTask.execute(args); //args = String[]
Reference: http://developer.android.com/guide/components/processes-and-threads.html#WorkerThreads
I'm developing a app at the moment wich displayes a Map, your gps postition and a marker on this postition. Next Step is to recieve Data from a XML file. The XML I'm trying to use is http://webservice.recruit.co.jp/hotpepper/gourmet/v1/?key=899d70a29e983f4b&lat=33.58724&lng=130.3986&range=5&order=4
But poorly after launching the app (on a real device, newest version) the app terminates and displays nothing.
LogCat says FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.xmlparser/com.example.xmlparser.MainActivitz}: java.lang.nullPointerException
MainActivity.java
package com.example.xmlparser;
import android.app.Activity;
import android.content.Context;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import java.io.IOException;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
public class MainActivity extends Activity implements LocationListener {
private TextView latituteField;
private TextView longitudeField;
private LocationManager locationManager;
private String provider;
public String url = "http://webservice.recruit.co.jp/hotpepper/gourmet/v1/?key=899d70a29e983f4b&lat=33.58724&lng=130.3986&range=5&order=4";
public EditText feldname, id;
public HandleXml obj;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
latituteField = (TextView) findViewById(R.id.TextView02);
longitudeField = (TextView) findViewById(R.id.TextView04);
feldname = (EditText)findViewById(R.id.editText1);
id = (EditText)findViewById(R.id.editText2);
// Get the location manager
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
// Define the criteria how to select the location provider -> use
// default
Criteria criteria = new Criteria();
provider = locationManager.getBestProvider(criteria, false);
Location location = locationManager.getLastKnownLocation(provider);
// Initialize the location fields
if (location != null)
{
System.out.println("Provider " + provider + " has been selected.");
onLocationChanged(location);
}
else
{
latituteField.setText("Location not available");
longitudeField.setText("Location not available");
}
float lat1 = (float) (location.getLatitude()); //Getting the position
float lng1 = (float) (location.getLongitude());
GoogleMap mMap;
mMap = ((MapFragment) getFragmentManager().findFragmentById(R.id.fragment1)).getMap();
mMap.addMarker(new MarkerOptions()
.position(new LatLng(lat1, lng1))
.title("Your Position"));
LatLng bounds = new LatLng(lat1, lng1);
CameraUpdate cu = CameraUpdateFactory.newLatLng(bounds);
mMap.moveCamera(cu);
}
//Request updates at startup */
#Override
protected void onResume() {
super.onResume();
locationManager.requestLocationUpdates(provider, 400, 1, this);
}
/* Remove the locationlistener updates when Activity is paused */
#Override
protected void onPause() {
super.onPause();
locationManager.removeUpdates(this);
}
#Override
public void onLocationChanged(Location location) {
float lat = (float) (location.getLatitude()); //Getting the ' ''
float lng = (float) (location.getLongitude());
latituteField.setText(String.valueOf(lat));
longitudeField.setText(String.valueOf(lng));
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
Toast.makeText(this, "Enabled new provider " + provider,
Toast.LENGTH_SHORT).show();
}
#Override
public void onProviderDisabled(String provider) {
Toast.makeText(this, "Disabled provider " + provider,
Toast.LENGTH_SHORT).show();
}
public void open(View view)
{
feldname.setText(url);
obj = new HandleXml(url);
obj.fetchXML();
while(obj.parsingComplete);
feldname.setText(obj.getFeldName());
id.setText(obj.getId());
}
}
HandleXml.java
package com.example.xmlparser;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
public class HandleXml {
private String feldname = "name";
private String id = "id";
private String urlString = null;
private XmlPullParserFactory xmlFactoryObject;
public volatile boolean parsingComplete = true;
public HandleXml(String url)
{
this.urlString = url;
}
public String getFeldName()
{
return feldname;
}
public String getId()
{
return id;
}
public void parseXMLAndStoreIt(XmlPullParser myParser)
{
int event;
String text=null;
try
{
event = myParser.getEventType();
while (event != XmlPullParser.END_DOCUMENT)
{
String name=myParser.getName();
switch (event)
{
case XmlPullParser.START_TAG:
break;
case XmlPullParser.TEXT:
text = myParser.getText();
break;
case XmlPullParser.END_TAG:
if(name.equals("name_kana"))
{
feldname = text;
}
else if(name.equals("id"))
{
id =text;// myParser.getAttributeValue(null,"value");
}
else
{}
break;
}
event = myParser.next();
}
parsingComplete = false;
} catch (Exception e) {
e.printStackTrace();
}
}
public void fetchXML()
{
Thread thread = new Thread(new Runnable()
{
#Override
public void run()
{
try
{
URL url = new URL(urlString);
HttpURLConnection conn = (HttpURLConnection)
url.openConnection();
conn.setReadTimeout(10000 /* milliseconds */);
conn.setConnectTimeout(15000 /* milliseconds */);
conn.setRequestMethod("GET");
conn.setDoInput(true);
conn.connect();
InputStream stream = conn.getInputStream();
xmlFactoryObject = XmlPullParserFactory.newInstance();
XmlPullParser myparser = xmlFactoryObject.newPullParser();
myparser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES
, false);
myparser.setInput(stream, null);
parseXMLAndStoreIt(myparser);
stream.close();
} catch (Exception e)
{
e.printStackTrace();
}
}
});
thread.start();
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.xmlparser"
android:versionCode="1"
android:versionName="1.0" >
<permission
android:name="com.example.map.permission.MAPS_RECEIVE"
android:protectionLevel="signature" />
<uses-sdk
android:minSdkVersion="12"
android:targetSdkVersion="18" />
<uses-feature
android:glEsVersion="0x00020000"
android:required="true" />
<uses-permission android:name="com.vogella.android.locationapi.maps.permission.MAPS_RECEIVE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" android:debuggable="true">
<uses-library android:name="com.google.android.maps" />
<activity
android:name="com.example.xmlparser.MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value="AIzaSyC3DipaFNo1EC44rZ8N1AJKVAiUCNOtqZw"/>
<meta-data
android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version" />
</application>
</manifest>
I really hope one of you can tell me whats wrong with this code as it was working perfectly fine with only the map on it's own and the parser as an own program.