Exchange messages between android apps with bluetooth - java

I have followed the below urls for the sample program.It us used to send a message to a paired blutooth device via an android app.
https://stackoverflow.com/a/22899728/1559331
IOException: read failed, socket might closed - Bluetooth on Android 4.3
What the code is trying to do is
1)Connect to paired device and writes data to it outputstream . The data to write is taken from edittext
2)The code also displays the data in the inputstream in an edittext
On testing it on a device , I could see that I am able to connect and write data to outputstream , but not able to read it.Even the Read button onclick is not working
main_activity_xml -- xml for UI used
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="wrap_content" android:orientation="horizontal"
android:layout_width="fill_parent">
<EditText
android:id="#+id/editText"
android:layout_height="wrap_content"
android:layout_weight="1"
android:layout_width="fill_parent"
android:inputType="number"
/>
<Button
android:id="#+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Submit"/>
<EditText
android:id="#+id/editText2"
android:layout_height="wrap_content"
android:layout_weight="1"
android:layout_width="fill_parent"
/>
<Button
android:id="#+id/button2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Read"
/>
</LinearLayout>
MainActivity.java - Main activity class
package com.example.dileep.blutooth_messenger;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.EmbossMaskFilter;
import android.graphics.PointF;
import android.os.ParcelUuid;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.InputFilter;
import android.text.format.DateUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TimePicker;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.lang.reflect.Method;
import java.util.Scanner;
import java.util.Set;
import java.util.UUID;
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final BluetoothSocketWrapper bluetoothSocketWrapper=new BluetoothSocketWrapper(getApplicationContext());
et = (EditText) findViewById(R.id.editText);
et.setFilters(new InputFilter[]{ new InputFilterMinMax("1", "100")});
final Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (bluetoothSocketWrapper.getSocket() != null) {
if (!bluetoothSocketWrapper.isConnected()) {
bluetoothSocketWrapper.init();
}
try {
bluetoothSocketWrapper.getOutputStream().write(et.getText().toString().getBytes());
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "Exception while writing to output stream-->" + e.getMessage(), Toast.LENGTH_SHORT).show();
}
finally {
try { bluetoothSocketWrapper.getOutputStream().close();}
catch (Exception e) {
Toast.makeText(getApplicationContext(), "Exception whileclosing output stream-->" + e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
Toast.makeText(getApplicationContext(), "Writing completed", Toast.LENGTH_SHORT).show();
}
else{
Toast.makeText(getApplicationContext(), "Not able to connect", Toast.LENGTH_SHORT).show();
}
}
});
et2 = (EditText) findViewById(R.id.editText2);
final Button button2 = (Button) findViewById(R.id.button2);
Toast.makeText(getApplicationContext(), "just beofre 2 nd listner", Toast.LENGTH_SHORT).show();
button2.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "second listener", Toast.LENGTH_SHORT).show();
if(bluetoothSocketWrapper.getSocket()!=null){
if(!bluetoothSocketWrapper.isConnected()) {
bluetoothSocketWrapper.init();
}
StringBuilder builder=new StringBuilder();
Scanner s = null;//.useDelimiter("\n");
try {
s = new Scanner(bluetoothSocketWrapper.getInputStream());
while(s.hasNext()){
builder.append(s.next());
}
Toast.makeText(getApplicationContext(), builder.toString(), Toast.LENGTH_SHORT).show();
et2.setText(builder.toString());
Toast.makeText(getApplicationContext(), "reading completed", Toast.LENGTH_SHORT).show();
} catch (IOException e) {
e.printStackTrace();
}
finally {
try { bluetoothSocketWrapper.getInputStream().close();}
catch (Exception e) {
Toast.makeText(getApplicationContext(), "Exception while closing input stream-->" + e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
}
else{
Toast.makeText(getApplicationContext(), "Not able to connect", Toast.LENGTH_SHORT).show();
}
}});
}
private OutputStream outputStream;
private InputStream inStream;
private EditText et;
private EditText et2;
}
BluetoothSocketWrapper class -->Used as a wrapper to bluetooth socket
package com.example.dileep.blutooth_messenger;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Context;
import android.os.ParcelUuid;
import android.util.Log;
import android.widget.Toast;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.lang.reflect.Method;
import java.net.Socket;
import java.util.Set;
import java.util.UUID;
public class BluetoothSocketWrapper {
private BluetoothSocket socket = null;
private OutputStream outputStream;
private InputStream inStream;
private Context context = null;
public BluetoothSocketWrapper(Context context) {
this.context = context;
init();
}
public void init() {
BluetoothAdapter blueAdapter = BluetoothAdapter.getDefaultAdapter();
if (blueAdapter == null) {
Toast.makeText(context, "Device doesnt Support Bluetooth", Toast.LENGTH_SHORT).show();
}
if (blueAdapter != null) {
if (blueAdapter.isEnabled()) {
Set<BluetoothDevice> bondedDevices = blueAdapter.getBondedDevices();
if (bondedDevices.size() > 0) {
Object[] devices = (Object[]) bondedDevices.toArray();
BluetoothDevice device = (BluetoothDevice) devices[0];
ParcelUuid[] uuids = device.getUuids();
// Toast.makeText(context,uuids[0].getUuid().toString(),Toast.LENGTH_LONG).show();
// BluetoothSocket socket=null;
try {
//socket = device.createRfcommSocketToServiceRecord(uuids[0].getUuid());
UUID SERIAL_UUID = UUID.fromString("00001101-0000-1000-8000-00805f9b34fb");
socket = device.createRfcommSocketToServiceRecord(SERIAL_UUID);
} catch (Exception e) {
Toast.makeText(context, "exc with 1st conn", Toast.LENGTH_LONG).show();
}
try {
socket.connect();
} catch (Exception e) {
Log.e("", e.getMessage());
try {
Toast.makeText(context, "tryiing fallback", Toast.LENGTH_LONG).show();
Class<?> clazz = socket.getRemoteDevice().getClass();
Class<?>[] paramTypes = new Class<?>[]{Integer.TYPE};
Method m = clazz.getMethod("createRfcommSocket", paramTypes);
Object[] params = new Object[]{Integer.valueOf(2)};
socket = (BluetoothSocket) m.invoke(socket.getRemoteDevice(), params);
socket.connect();
Toast.makeText(context, "Connected", Toast.LENGTH_LONG).show();
} catch (Exception e2) {
Toast.makeText(context, "Couldn't establish Bluetooth connection -->" + e2.getMessage(), Toast.LENGTH_LONG).show();
}
}
}
Log.e("error", "No appropriate paired devices.");
} else {
Log.e("error", "Bluetooth is disabled.");
}
}
}
public boolean isConnected(){
return this.socket.isConnected();
}
public OutputStream getOutputStream() throws IOException {
return this.socket.getOutputStream();
}
public InputStream getInputStream() throws IOException {
return this.socket.getInputStream();
}
public void close() throws IOException {
this.socket.close();
}
public BluetoothSocket getSocket(){
return socket;
}
}
InputFilter class used for edittext
package com.example.dileep.blutooth_messenger;
import android.text.InputFilter;
import android.text.Spanned;
public class InputFilterMinMax implements InputFilter {
private int min, max;
public InputFilterMinMax(int min, int max) {
this.min = min;
this.max = max;
}
public InputFilterMinMax(String min, String max) {
this.min = Integer.parseInt(min);
this.max = Integer.parseInt(max);
}
#Override
public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
try {
int input = Integer.parseInt(dest.toString() + source.toString());
if (isInRange(min, max, input))
return null;
} catch (NumberFormatException nfe) { }
return "";
}
private boolean isInRange(int a, int b, int c) {
return b > a ? c >= a && c <= b : c >= b && c <= a;
}
}
Can somebody please explain why the app and device getting hanged .Also please suggest the changes needed

Related

Controlling an AsynTaskLoader using a button click

I have created an app that displays a list of 10 books based on a query keyword entered by the user.
I have used an EditText View for the user to enter the query.
I have also used an ImageButton for the search button.
I have used a custom class that extents AsyncTaskLoader to load content to my ListView.
I have called the initloader() method from the MainActivity of the app and has called my custom loader from the OnCreateLoader override method.
I want the loader to fetch the data only on a button click and not automatically when the activity starts.
Main Activity
package com.example.shara.booklistapp;
import android.app.LoaderManager;
import android.content.Context;
import android.content.Intent;
import android.content.Loader;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.provider.ContactsContract;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
import static android.app.LoaderManager.*;
import static com.example.shara.booklistapp.BookQueryUtils.LOG_TAG;
public class MainActivity extends AppCompatActivity implements LoaderManager.LoaderCallbacks<List<Blist>> {
private ListAdapter mAdapter;
private static final int BOOK_LOADER_ID = 1;
private String Book_list_request_url = "Michael Jackson";
private ProgressBar progressBar;
private NetworkInfo networkInfo;
private TextView emptytextview;
private EditText editText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView booklistview = findViewById(R.id.list);
progressBar = findViewById(R.id.progressbar);
mAdapter = new ListAdapter(this, new ArrayList<Blist>());
booklistview.setAdapter(mAdapter);
ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
networkInfo = connectivityManager.getActiveNetworkInfo();
emptytextview = (TextView) findViewById(R.id.emptytextview);
editText = findViewById(R.id.search_query_text_view);
booklistview.setEmptyView(emptytextview);
booklistview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Blist currentBook = mAdapter.getItem(position);
Uri currentbookk = Uri.parse(currentBook.getUrl());
startActivity(new Intent(Intent.ACTION_VIEW, currentbookk));
}
});
LoaderManager loaderManager = getLoaderManager();
loaderManager.initLoader(BOOK_LOADER_ID, null, this);
}
//Overriding the abstract methods of the Loadermanager
#Override
public Loader<List<Blist>> onCreateLoader(int id, Bundle bundle) {
Log.i(LOG_TAG, Book_list_request_url);
return new BlistLoader(this, Book_list_request_url);
}
#Override
public void onLoadFinished(Loader<List<Blist>> loader, List<Blist> blists) {
progressBar.setVisibility(View.GONE);
//Using the networkInfo variable declared earlier to check whether the system has internet connectivity and displays a message if there isn't one.
if (networkInfo == null) {
emptytextview.setText(R.string.no_network);
} else {
emptytextview.setVisibility(View.GONE);
}
mAdapter.clear();
if (blists != null && !blists.isEmpty()) {
mAdapter.addAll(blists);
}
}
#Override
public void onLoaderReset(Loader loader) {
Log.i(LOG_TAG, "Testing: onLoaderReset is successfully called");
mAdapter.clear();
}
}
Custom Loader class
package com.example.shara.booklistapp;
import android.content.AsyncTaskLoader;
import android.content.Context;
import android.util.Log;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageButton;
import org.json.JSONException;
import java.io.IOException;
import java.util.List;
public class BlistLoader extends AsyncTaskLoader<List<Blist>> {
private static final String LOG_TAG = BaseAdapter.class.getName();
private String mUrl;
public BlistLoader(Context context, String url) {
super(context);
mUrl = url;
}
#Override
protected void onStartLoading() {
Log.i(LOG_TAG, "Testing: onStartLoading is successfully called");
forceLoad();
}
#Override
public List<Blist> loadInBackground() {
Log.i(LOG_TAG, "Testing: loadInBackground is successfully called");
if (mUrl == null) {
return null;
}
List<Blist> blists = null;
try {
blists = BookQueryUtils.fetchBookList(mUrl);
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return blists;
}
}
XML that contains the ImageButton
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:orientation="horizontal">
<EditText
android:id="#+id/search_query_text_view"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="2"
android:hint="#string/hint" />
<ImageButton
android:id="#+id/search_button1"
android:layout_width="42dp"
android:layout_height="42dp"
android:src="#drawable/search" />
</LinearLayout>
<TextView
android:id="#+id/result"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:backgroundTint="#color/colorPrimaryDark"
android:backgroundTintMode="add"
android:text="Results" />
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<ListView
android:id="#+id/list"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_margin="10dp"
android:dividerHeight="1dp" />
<ProgressBar
android:id="#+id/progressbar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true" />
<TextView
android:id="#+id/emptytextview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="" />
</RelativeLayout>
</LinearLayout>
I want the oncreateloader method to only execute when the search button is clicked and not otherwise.
How can this be achieved? Does my code need heavy modification or is it just something that I missed altogether.
I have previously asked the same question here but I didn't get any answers.
Any help would be greatly appreciated.
Book query utils is for the HTTP request and JSON parsing.
package com.example.shara.booklistapp;
import android.net.Uri;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
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.URL;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
/**
* Created by shara on 12/17/2017.
*/
public final class BookQueryUtils {
public static final String LOG_TAG = BookQueryUtils.class.getName();
private BookQueryUtils() {
}
private static URL createURL(String search_query) throws MalformedURLException {
URL url = null;
String q = "q";
try {
final String base_URL = "https://www.googleapis.com/books/v1/volumes?";
Uri final_Url = Uri.parse(base_URL).buildUpon()
.appendQueryParameter(q, search_query)
.build();
url = new URL(final_Url.toString());
Log.i(LOG_TAG, "The final Url is" + url);
} catch (MalformedURLException e) {
Log.e(LOG_TAG, "Url could not be formed", e);
}
return url;
}
private static String theHTTPRequest(URL url) throws IOException {
String jsonResponse = "";
if (url == null) {
return jsonResponse;
}
HttpURLConnection connectionUrl = null;
InputStream theInputStream = null;
try {
connectionUrl = (HttpURLConnection) url.openConnection();
connectionUrl.setReadTimeout(10000);
connectionUrl.setConnectTimeout(15000);
connectionUrl.setRequestMethod("GET");
connectionUrl.connect();
if (connectionUrl.getResponseCode() == 200) {
theInputStream = connectionUrl.getInputStream();
jsonResponse = readFromStream(theInputStream);
} else {
Log.e(LOG_TAG, "could not make the connection");
}
} catch (IOException e) {
Log.e(LOG_TAG, "Problem getting the requested data", e);
} finally {
if (connectionUrl != null) {
connectionUrl.disconnect();
}
if (theInputStream != null) {
theInputStream.close();
}
}
return jsonResponse;
}
private static String readFromStream(InputStream inputStream) throws IOException {
StringBuilder streamoutput = new StringBuilder();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, Charset.forName("UTF-8"));
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String urlline = bufferedReader.readLine();
while (urlline != null) {
streamoutput.append(urlline);
urlline = bufferedReader.readLine();
}
return streamoutput.toString();
}
private static List<Blist> extractFeatureFromJSON(String BlistJSON) throws JSONException {
if (TextUtils.isEmpty(BlistJSON)) {
return null;
}
List<Blist> blists = new ArrayList<>();
try {
String a = "";
JSONObject baseJSON = new JSONObject(BlistJSON);
JSONArray items = baseJSON.getJSONArray("items");
for (int i = 0; i < items.length(); i++) {
Blist blistss = new Blist();
JSONObject j = items.getJSONObject(i);
JSONObject vInfo = j.getJSONObject("volumeInfo");
if (vInfo.has("authors")) {
JSONArray athrs = vInfo.getJSONArray("authors");
if (athrs.length() != 0) {
for (int k = 0; k < athrs.length(); k++) {
a = athrs.getString(k);
blistss.setAuthor(a);
}
}
}
if (vInfo.has("imageLinks")) {
JSONObject thumbnail = vInfo.getJSONObject("imageLinks");
blistss.setImage(thumbnail.getString("thumbnail"));
}
blistss.setUrl(vInfo.getString("previewLink"));
blistss.setTitle(vInfo.getString("title"));
blistss.setPublisher(vInfo.getString("publisher"));
blists.add(blistss);
}
} catch (JSONException e) {
Log.e(LOG_TAG, "Could not parse JSON", e);
}
return blists;
}
public static List<Blist> fetchBookList(String query_url) throws IOException, JSONException {
URL url = createURL(query_url);
String JSONResponse = null;
try {
JSONResponse = theHTTPRequest(url);
} catch (IOException e) {
Log.e(LOG_TAG, "Could not fetch data");
}
List<Blist> blists = extractFeatureFromJSON(JSONResponse);
return blists;
}
}
This is my adapter for the listview.
package com.example.shara.booklistapp;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.provider.ContactsContract;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.SearchView;
import android.widget.TextView;
import java.io.InputStream;
import java.util.ArrayList;
/**
* Created by shara on 12/17/2017.
*/
public class ListAdapter extends ArrayAdapter<Blist> {
private ProgressBar progressBar;
public ListAdapter(#NonNull Context context, ArrayList<Blist> blists) {
super(context, 0, blists);
}
public String rslt;
#NonNull
#Override
public View getView(int position, #Nullable View convertView, #NonNull ViewGroup parent) {
View listitemview = convertView;
if (listitemview == null) {
listitemview = LayoutInflater.from(getContext()).inflate(R.layout.list_layout, parent, false);
}
Blist blist = getItem(position);
ImageView thumbnail = listitemview.findViewById(R.id.thumbnail_imageview);
new imageLoader(thumbnail).execute(blist.getImage());
progressBar = listitemview.findViewById(R.id.Image_Progress_bar);
progressBar.setVisibility(View.GONE);
TextView title = listitemview.findViewById(R.id.title_textview);
title.setText(blist.gettitle());
TextView author = listitemview.findViewById(R.id.author_textview);
author.setText(blist.getauthor());
TextView publisher = listitemview.findViewById(R.id.publisher_texview);
publisher.setText(blist.getpublisher());
return listitemview;
}
private class imageLoader extends AsyncTask<String, Void, Bitmap> {
ImageView bmImage;
public imageLoader(ImageView bmImage) {
this.bmImage = bmImage;
}
protected Bitmap doInBackground(String... urls) {
String urldisplay = urls[0];
Bitmap mIcon11 = null;
try {
InputStream in = new java.net.URL(urldisplay).openStream();
mIcon11 = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return mIcon11;
}
protected void onPostExecute(Bitmap result) {
bmImage.setImageBitmap(result);
}
}
}
Updated in Code
Initially set empty query
private String Book_list_request_url = "";
Create method for "Search Click(imagebutton)"
public void Search(View v)
{
Book_list_request_url = editText.getText().toString();
loaderManager.restartLoader(BOOK_LOADER_ID, null, this);
}
Add method to imagebutton
<ImageButton
android:id="#+id/search_button1"
android:layout_width="42dp"
android:layout_height="match_parent"
android:onClick="Search"
android:src="#drawable/ic_launcher_background" />

Bluetooth not writing or taking forever to read

import android.annotation.TargetApi;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothServerSocket;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
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;
#TargetApi(18)
public class MainActivity extends AppCompatActivity{
`int b = 0;
BluetoothAdapter BA = BluetoothAdapter.getDefaultAdapter();
BluetoothDevice device;
BluetoothSocket BS;
BluetoothServerSocket server;
UUID uuid = UUID.fromString("f63b93f5-56e0-47bb-8972-996e34cfb9a8");`
`#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);`
`Intent i = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivity(i);`
`Accept accept = new Accept();
accept.start();`
Set<BluetoothDevice> devices = BA.getBondedDevices();
for(BluetoothDevice bt : devices) {
try {
if (bt.getName().equals("Overlord")) {
device = BA.getRemoteDevice(bt.getAddress());
BS = device.createRfcommSocketToServiceRecord(uuid);
} else if (bt.getName().equals("Huawei Y5")) {
device = BA.getRemoteDevice(bt.getAddress());
BS = device.createRfcommSocketToServiceRecord(uuid);
}
}catch(IOException IOE){}
}
}
public interface MessageContents{
int MSG_MESSAGE = 0;
}
Handler handler = new Handler(){
public void handleMessage(Message msg) {
TextView tx = (TextView)findViewById(R.id.textView2);
switch(msg.what){
case MessageContents.MSG_MESSAGE:
byte[] readBuf = (byte[]) msg.obj;
// construct a string from the valid bytes in the buffer
String readMessage = new String(readBuf, 0, msg.arg1);
Log.d("TAG", readMessage);
tx.setText(readMessage);
break;
default:
tx.setText("No text");
}
}
};
class Connect extends Thread{
public void run(){
try {
try {
BS.connect();
Log.d("LOG", " e");
Log.d("LOG", "r" + BS.isConnected());
DataTransfer dataTransfer = new DataTransfer();
dataTransfer.start();
}catch(NullPointerException e){
Log.d("LOG", " meezaan");
}
}catch(IOException e){
Log.d("LOG", "t");
}
}
}
class Accept extends Thread{
public void run() {
try {
while (true) {
server = BA.listenUsingRfcommWithServiceRecord("Secure Connection", uuid);
server.accept();
Log.d("LOG", "accept");
}
}catch(IOException E) {
}
}
}
class DataTransfer extends Thread{
#Override
public void run() {
int d = 1;
InputStream receive = null;
Log.d("LOG", "On");
int numBytes;
byte[] buffer = new byte[1024];
try {
receive = BS.getInputStream();
Log.d("LOG", "pn");
while (BS.isConnected()) {
try {
if (d <= 5) {
Log.d("LOG", "did");
++d;
}
numBytes = receive.read(buffer);
handler.obtainMessage(MessageContents.MSG_MESSAGE, numBytes, -1, buffer).sendToTarget();
} catch (NullPointerException e) {
Log.d("LOG", "error read(null)");
}
}
Log.d("LOG", "pnA");
} catch (IOException IOE) {
Log.d("LOG", "error read(IOE)");
}
}
}
public void onOne(View view){
write("1".getBytes());
}
public void onClick(View view){
Button b1 = (Button) findViewById(R.id.button);
EditText pin = (EditText) findViewById(R.id.editText);
pin.setRawInputType(Configuration.KEYBOARD_QWERTY);
pin.setVisibility(View.VISIBLE);
b1.setVisibility(View.VISIBLE);
}
public void pin (View view) {
Button b1 = (Button)findViewById(R.id.button);
EditText pin = (EditText)findViewById(R.id.editText);
String pin1 = pin.getText().toString();
if (pin1.equals("")) {
Connect connect = new Connect();
connect.run();
pin.setVisibility(View.INVISIBLE);
b1.setVisibility(View.INVISIBLE);
} else {
Toast.makeText(getApplicationContext(), "Wrong Pin!"+pin1, Toast.LENGTH_SHORT).show();
pin.setVisibility(View.INVISIBLE);
b1.setVisibility(View.INVISIBLE);
}
}
public void onTwo(View v){
Toast.makeText(getApplicationContext(), "" + handler.hasMessages(MessageContents.MSG_MESSAGE) + " " + BS.isConnected(), Toast.LENGTH_SHORT).show();
}
public void write(byte[] Byte){
try {
OutputStream transfer = BS.getOutputStream();
try {
transfer.write(Byte);
}catch(NullPointerException e){
Log.d("LOG", "error write(null) " + BS.isConnected());}
}catch (IOException IOE){ Log.d("LOG", "b");
Log.d("LOG", "error write(IOE) " + BS.isConnected());}
}
}`
Hi, this is my code. After writing Bytes[] I don't receive anything on second device. When I remove 'numBytes = receive.read(buffer)' handler would work or display
'no text'
I think receive.read(buffer) waits for an input which means write is a problem or receive.read(buffer) is the problem. Please ignore names, logs with random letters in or device names or unnecessary imports or variables. Thank You :) Sorry I did not have time to indent everything. If you are viewing please put something like don't know.Thank you.

Issues in Android app while sending string to Java Application

Was trying to make a simple application that receives text from speech API and send it over to a java server.Tried debugging from traces. The code does not go beyond TRY block where i opened my socket.
Code Updated : Now the application is not crashing.But no message flow.
package info.androidhive.speechtotext;
import java.io.BufferedWriter;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.util.ArrayList;
import java.util.Locale;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.speech.RecognizerIntent;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
import static java.sql.DriverManager.println;
public class MainActivity extends Activity {
/**
* Declarations
*/
private TextView txtSpeechInput;
private ImageButton btnSpeak;
String str;
private final int REQ_CODE_SPEECH_INPUT = 100;
private String serverIpAddress = "";
private boolean connected = false;
TextView textIn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txtSpeechInput = (TextView) findViewById(R.id.txtSpeechInput);
btnSpeak = (ImageButton) findViewById(R.id.btnSpeak);
// hide the action bar
getActionBar().hide();
btnSpeak.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
promptSpeechInput();
}
});
}
/**
* Showing google speech input dialog
*/
private void promptSpeechInput() {
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.getDefault());
intent.putExtra(RecognizerIntent.EXTRA_PROMPT,
getString(R.string.speech_prompt));
try {
startActivityForResult(intent, REQ_CODE_SPEECH_INPUT);
} catch (ActivityNotFoundException a) {
Toast.makeText(getApplicationContext(),
getString(R.string.speech_not_supported),
Toast.LENGTH_SHORT).show();
}
}
/**
* Receiving speech input
*/
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case REQ_CODE_SPEECH_INPUT: {
if (resultCode == RESULT_OK && null != data) {
ArrayList<String> result = data
.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
txtSpeechInput.setText(result.get(0));
str = result.get(0);
setContentView(R.layout.activity_main);
Log.d("1- naval", " client oncreate");
Button button = (Button) findViewById(R.id.send);
textIn = (TextView) findViewById(R.id.textin);
/**
* Setting the text box with default value
*/
textIn.setText(str);
Log.d("settext", " 2-naval");
/**
* Here we need to fill in textin from MainActivity,
* where we received the speech API text
*/
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
if (!connected) {
serverIpAddress = "192.168.0.4";
if (!serverIpAddress.equals("")) {
Thread cThread = new Thread(new ClientThread());
cThread.start();
}
}
}
}
);
}
}
}
}
public class ClientThread implements Runnable {
public void run() {
try {
InetAddress serverAddr = InetAddress.getByName(serverIpAddress);
Log.d("ClientActivity", "C: Connecting...");
Socket socket = new Socket(serverAddr, 8888);
PrintWriter out = null;
out.println(str);
connected = true;
while (connected) {
try {
Log.d("ClientActivity", "C: Sending command.");
out = new PrintWriter(
new BufferedWriter(new OutputStreamWriter(
socket.getOutputStream())), true);
// WHERE YOU ISSUE THE COMMANDS
// out.println("Hey Server!");
Log.d("ClientActivity", "C: Sent.");
} catch (Exception e) {
Log.e("ClientActivity", "S: Error", e);
}
}
socket.close();
Log.d("ClientActivity", "C: Closed.");
} catch (Exception e) {
Log.e("ClientActivity", "C: Error", e);
connected = false;
}
}
}
}
Since, at the time of writing this answer, the author has yet to add a stacktrace I'll go over some basic solutions:
Make sure you've added INTERNET permission to your android manifest, otherwise your socket wont open <uses-permission android:name="android.permission.INTERNET" />
Open your socket on a background thread. Networking on the UI thread (eg. inside the onClick method) is prohibited on android
Add a stack trace if the above didn't solve your problem

Communication Android to PC using bluetooth to send a text file

Hello I am new to Android. I want to communicate android with pc to send a text file.
I am trying to communicate using following code.
I am using bluetooth dongle to pc.
When i run application it get crashed without any error. Please help me in communication.
enter code here
package com.exam.bluetooth2;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Set;
import java.util.UUID;
import android.R;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class Main extends Activity implements Runnable
{
protected static final String TAG = "TAG";
private static final int REQUEST_CONNECT_DEVICE = 1;
private static final int REQUEST_ENABLE_BT = 2;
Button mScan;
BluetoothAdapter mBluetoothAdapter;
private UUID applicationUUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
private ProgressDialog mBluetoothConnectProgressDialog;
private BluetoothSocket mBluetoothSocket;
BluetoothDevice mBluetoothDevice;
#Override
public void onCreate(Bundle mSavedInstanceState)
{
super.onCreate(mSavedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_list_item);
mScan = (Button) findViewById(R.id.button1);
mScan.setOnClickListener(new View.OnClickListener()
{
public void onClick(View mView)
{
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (mBluetoothAdapter == null)
{
Toast.makeText(Main.this, "Message1", 2000).show();
}
else
{
if (!mBluetoothAdapter.isEnabled())
{
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}
else
{
ListPairedDevices();
Intent connectIntent = new Intent(Main.this, DeviceListActivity.class);
startActivityForResult(connectIntent, REQUEST_CONNECT_DEVICE);
}
}
}
});
}
public void onActivityResult(int mRequestCode, int mResultCode, Intent mDataIntent)
{
super.onActivityResult(mRequestCode, mResultCode, mDataIntent);
switch (mRequestCode)
{
case REQUEST_CONNECT_DEVICE:
if (mResultCode == Activity.RESULT_OK)
{
Bundle mExtra = mDataIntent.getExtras();
String mDeviceAddress = mExtra.getString("DeviceAddress");
Log.v(TAG, "Coming incoming address " + mDeviceAddress);
mBluetoothDevice = mBluetoothAdapter.getRemoteDevice(mDeviceAddress);
mBluetoothConnectProgressDialog = ProgressDialog.show(this, "Connecting...", mBluetoothDevice.getName() + " : " + mBluetoothDevice.getAddress(), true, false);
Thread mBlutoothConnectThread = new Thread(this);
mBlutoothConnectThread.start();
Toast.makeText(getBaseContext(), mBluetoothDevice.getAddress(), 10000).show();
//pairToDevice(mBluetoothDevice); This method is replaced by progress dialog with thread
}
break;
case REQUEST_ENABLE_BT:
if (mResultCode == Activity.RESULT_OK)
{
ListPairedDevices();
Intent connectIntent = new Intent(Main.this, DeviceListActivity.class);
startActivityForResult(connectIntent, REQUEST_CONNECT_DEVICE);
}
else
{
Toast.makeText(Main.this, "Message", 2000).show();
}
break;
}
}
private void ListPairedDevices()
{
Set<BluetoothDevice> mPairedDevices = mBluetoothAdapter.getBondedDevices();
if (mPairedDevices.size() > 0)
{
for (BluetoothDevice mDevice : mPairedDevices)
{
Log.v(TAG, "PairedDevices: " + mDevice.getName() + " " + mDevice.getAddress());
}
}
// Object device = null;
// String dv = device.toString();
// if(dv.contains("00:1B:EE:82:31:1E"))
// {
// mBluetoothDevice = (BluetoothDevice) device;
// }
}
public void run()
{
try
{
mBluetoothSocket = mBluetoothDevice.createRfcommSocketToServiceRecord(applicationUUID);
mBluetoothAdapter.cancelDiscovery();
mBluetoothSocket.connect();
mHandler.sendEmptyMessage(0);
String messsage = "Welcome to SmarTec";
byte[] tosend=messsage.getBytes();
OutputStream out=mBluetoothSocket.getOutputStream();
out.write(tosend);
}
catch (IOException eConnectException)
{
Log.d(TAG, "CouldNotConnectToSocket", eConnectException);
closeSocket(mBluetoothSocket);
return;
}
}
private void closeSocket(BluetoothSocket nOpenSocket)
{
try
{
nOpenSocket.close();
Log.d(TAG, "SocketClosed");
}
catch (IOException ex)
{
Log.d(TAG, "CouldNotCloseSocket");
}
}
private Handler mHandler = new Handler()
{
#Override
public void handleMessage(Message msg)
{
mBluetoothConnectProgressDialog.dismiss();
Toast.makeText(Main.this, "Device Connected", 5000).show();
// Intent in = new Intent(getBaseContext(), Option.class);
// startActivity(in);
}
};
/* public void sendtext(View v) {//button click
Set<BluetoothDevice> bd = mBluetoothAdapter.getBondedDevices();
sendDataToPairedDevice("message1");
}
private void sendDataToPairedDevice(String message ){
byte[] toSend = message.getBytes();
try {
UUID applicationUUID = UUID.fromString("8ce255c0-200a-11e0-ac64- 0800200c9a66");
BluetoothSocket socket = mBluetoothDevice.createInsecureRfcommSocketToServiceRecord(applicationUUID);
OutputStream mmOutStream = socket.getOutputStream();
mmOutStream.write(toSend);
} catch (IOException e) {
Log.e( "Exception during write", e.toString());
}
}
*/
}
enter code here
package com.exam.bluetooth2;
import java.util.Set;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
public class DeviceListActivity extends Activity
{
protected static final String TAG = "TAG";
private BluetoothAdapter mBluetoothAdapter;
private ArrayAdapter<String> mPairedDevicesArrayAdapter;
#Override
protected void onCreate(Bundle mSavedInstanceState)
{
super.onCreate(mSavedInstanceState);
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
setContentView(R.layout.device_list);
setResult(Activity.RESULT_CANCELED);
mPairedDevicesArrayAdapter = new ArrayAdapter<String>(this, R.layout.device_name);
ListView mPairedListView = (ListView) findViewById(R.id.paired_devices);
mPairedListView.setAdapter(mPairedDevicesArrayAdapter);
mPairedListView.setOnItemClickListener(mDeviceClickListener);
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
Set<BluetoothDevice> mPairedDevices = mBluetoothAdapter.getBondedDevices();
if (mPairedDevices.size() > 0)
{
findViewById(R.id.title_paired_devices).setVisibility(View.VISIBLE);
for (BluetoothDevice mDevice : mPairedDevices)
{
mPairedDevicesArrayAdapter.add(mDevice.getName() + "\n" + mDevice.getAddress());
}
}
else
{
String mNoDevices = getResources().getText(R.string.none_paired).toString();
mPairedDevicesArrayAdapter.add(mNoDevices);
}
}
#Override
protected void onDestroy()
{
super.onDestroy();
if (mBluetoothAdapter != null)
{
mBluetoothAdapter.cancelDiscovery();
}
}
private OnItemClickListener mDeviceClickListener = new OnItemClickListener()
{
public void onItemClick(AdapterView<?> mAdapterView, View mView, int mPosition, long mLong)
{
mBluetoothAdapter.cancelDiscovery();
String mDeviceInfo = ((TextView) mView).getText().toString();
String mDeviceAddress = mDeviceInfo.substring(mDeviceInfo.length() - 17);
Log.v(TAG, "Device_Address " + mDeviceAddress);
Bundle mBundle = new Bundle();
mBundle.putString("DeviceAddress", mDeviceAddress);
Intent mBackIntent = new Intent();
mBackIntent.putExtras(mBundle);
setResult(Activity.RESULT_OK, mBackIntent);
finish();
}
};
}
Vijay,
You need to check few thinks below:
Add bluetooth permission in manifest file.
If device is not supporting bluetooth, then you get bluetooth adapter value null. So need to check that also.
Also its better to create broadcast receiver with bluetooth actions.

My connection between php and android by json not working

I developed an app to connect my android app to remote server and display data in listview.
I did everything but the data doesn't show up in the listview.
These are the files I used to accomplish that, please help me:
MediaActivity.java
package com.shadatv.shada;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Locale;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.net.ParseException;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
public class MediaActivity extends OptionsMenu {
Locale locale;
// boolean mybooks;
Configuration config = new Configuration();
static SharedPreferences sharedPreferenceid;
static SharedPreferences.Editor editorid;
public static final String Myid = "Myid";
String myid = "";
InputStream is = null;
StringBuilder sb = null;
String resultt = "";
JSONArray jArray;
String result = null;
public DAOCanticles cantDatabase = null;
int numberofrowssss;
int responseCode;
String targetcover, targetbname, targetauthname;
public String caNameField = "", caLinkField = "", caImgField = "";
// ///////////////////ONLINE BESTSALED//////////////////////
String caNameJson, caLinkJson, caImgJson;
public ArrayList<String> caNameHolder = new ArrayList<String>();
public ArrayList<String> caLinkHolder = new ArrayList<String>();
public ArrayList<String> caImgHolder = new ArrayList<String>();
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.media);
cantDatabase = new DAOCanticles(this);
new LoadData().execute();
}
// =============================================================================
public void onClickPrograms(View view) {
startActivity(new Intent("com.shadatv.ProgramsActivity"));
}
// =============================================================================
public void onClickCanticles(View view) {
startActivity(new Intent("com.shadatv.CanticlesActivity"));
}
// =============================================================================
public void onClickDocumentaries(View view) {
startActivity(new Intent("com.shadatv.DocumentariesActivity"));
}
// =============================================================================
private class LoadData extends AsyncTask<Void, Void, Void> {
public ProgressDialog progressDialog1;
#Override
protected Void doInBackground(Void... params) {
cantDatabase.deletetable();
getCanticlesByJSON();
addCanticles();
return null;
}
#Override
// can use UI thread here
protected void onPreExecute() {
CharSequence contentTitle = getString(R.string.loading);
this.progressDialog1 = ProgressDialog.show(MediaActivity.this, "",
contentTitle);
}
// -------------------------------------------//
#Override
protected void onPostExecute(final Void unused) {
this.progressDialog1.dismiss();
}
}
// =============================================================================
public void getCanticlesByJSON() {
try {
HttpClient httpclient = new DefaultHttpClient();
try {
} catch (Exception e) {
Log.e("my_log_tag", e.toString());
}
// buffered reader
try {
HttpPost httppost = new HttpPost(
"http://dt-works.com/ags/shadatv/canticles/android_data");
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
BufferedReader reader = new BufferedReader(
new InputStreamReader(is, "UTF-8"), 80);
sb = new StringBuilder();
sb.append(reader.readLine() + "\n");
String line = "0";
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = EntityUtils.toString(entity);
//result = sb.toString();
} catch (Exception e) {
Log.e("my_log_tag", e.toString());
}
try {
result = result.substring(1);
jArray = new JSONArray(result);
JSONObject json_data = null;
for (int i = 0; i < jArray.length(); i++) {
json_data = jArray.getJSONObject(i);
caNameJson = json_data.getString("ca_name");
caLinkJson = json_data.getString("ca_link");
caImgJson = json_data.getString("ca_link");
caNameHolder.add(caNameJson);
caLinkHolder.add(caLinkJson);
caImgHolder.add(caImgJson);
}
} catch (JSONException e) {
Log.e("my_log_tag", e.toString());
}
} catch (ParseException e) {
Log.e("my_log_tag", e.toString());
} catch (Exception e) {
Log.e("my_log_tag", e.toString());
}
}
// =============================================================================
public void addCanticles() {
try {
for (int i = 0; i < caNameHolder.size(); i++) {
caNameField = caNameHolder.get(i);
caLinkField = caLinkHolder.get(i);
caImgField = caImgHolder.get(i);
cantDatabase.createCanticle(caNameField, caLinkField,
caImgField);
}
} catch (Exception e) {
Log.e("my_log_tag", "notfilled yet");
}
}
}
CanticlesActivity.java
package com.shadatv.shada;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.zip.ZipInputStream;
import javax.crypto.Cipher;
import javax.crypto.CipherInputStream;
import javax.crypto.CipherOutputStream;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import android.content.SharedPreferences;
import android.database.Cursor;
public class CanticlesActivity extends Activity {
int read;
boolean flage;
final Context context = this;
String picpath="http://img.youtube.com/vi/";
ArrayList<String> getCaName = new ArrayList<String>();
ArrayList<String> getCaLink = new ArrayList<String>();
ArrayList<String> getCaImg = new ArrayList<String>();
String targetCaName;
String targetCaLink;
String targetCaImg;
File sdcard = Environment.getExternalStorageDirectory();
File shadaRoot = new File (sdcard.getAbsolutePath() + "/Shada_Folder");
BitmapFactory.Options options = new BitmapFactory.Options();
Bitmap bm ;
ImageView img ;
public DAOCanticles cantDatabase =null;
byte[] encoded;
String value;
String useriddd;
//=============================================================================
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.canticles);
cantDatabase = new DAOCanticles(this);
new LoadData().execute();
}
//=============================================================================
private class LoadData extends AsyncTask<Void, Void, Void> {
private ProgressDialog progressDialog;
#Override
// can use UI thread here
protected void onPreExecute() {
CharSequence contentTitle = getString(R.string.loading);
this.progressDialog = ProgressDialog.show(CanticlesActivity.this,"",contentTitle);
}
//-------------------------------------------//
#Override
protected void onPostExecute(final Void unused) {
this.progressDialog.dismiss();
showCanticles();
}
//-------------------------------------------//
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
// HTTP post
getCanticles();
return null;
}
}
//=============================================================================
public void getCanticles() {
try{
Cursor canticles = cantDatabase.getCanticlesList();
do{
getCaName.add(canticles.getString(0));
getCaLink.add(canticles.getString(1));
getCaImg.add(canticles.getString(2));
}
while(canticles.moveToNext());
}catch(Exception e){
}
}
//=============================================================================
public void Downloadimage(String imgURL) {
try {
String finlpth="";
finlpth=picpath + imgURL + "/2.jpg";
shadaRoot.mkdirs();
URL u = new URL(finlpth);
HttpURLConnection c = (HttpURLConnection) u.openConnection();
c.setRequestMethod("GET");
c.setDoOutput(true);
c.connect();
File DownloadedFile=new File(shadaRoot, imgURL + ".jpg");
// if(!outfile.exists())
FileOutputStream f = new FileOutputStream(DownloadedFile);
InputStream in = c.getInputStream();
byte[] buffer = new byte[1024];
int len1 = 0;
while ((len1 = in.read(buffer)) > 0) {
f.write(buffer, 0, len1);
}
f.close();
} catch (Exception e) {
Log.d("Downloader", e.getMessage());
}
}
//=============================================================================
public void showCanticles()
{
final ListView listview = (ListView) findViewById(R.id.listView1);
for(int i=0; i < getCaName.size(); i++)
{
String caName=getCaName.get(i);
String caLink=getCaLink.get(i);
String caImg=getCaImg.get(i);
Toast.makeText(getBaseContext(), caName, Toast.LENGTH_SHORT).show();
if(!caImg.equalsIgnoreCase("0"))
{
Downloadimage(caLink);
}
}
listview.setOnItemClickListener(new ListView.OnItemClickListener(){
public void onItemClick(AdapterView<?> parent, View v,
int position, long id) {
long selectedItemId = listview.getSelectedItemId();
ListAdapter adapterr = listview.getAdapter();
String selectedValue = (adapterr.getItem(position)).toString();
String selectedCaName=getCaName.get(position);
String selectedCaLink=getCaLink.get(position);
// // custom dialog
final Dialog dialog = new Dialog(context);
dialog.setContentView(R.layout.customdialogue);
dialog.setTitle(selectedCaName);
// set the custom dialog components - text, image and button
String selectedbookcover=getCaImg.get(position);
String test= shadaRoot+"/"+ selectedCaName;
String myJpgPath = test+".jpg";
TextView caLink = (TextView) dialog.findViewById(R.id.ca_link);
caLink.setText(selectedCaLink);
options.inSampleSize = 6;
Button dialogButton = (Button) dialog.findViewById(R.id.dialogButtonOK);
// if button is clicked, close the custom dialog
dialogButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
dialog.dismiss();
}
});
dialog.show();
dialog.getWindow().setLayout(350,350);
}
});
listview.setAdapter(new DataAdapter(
CanticlesActivity.this,
getCaName.toArray(new String[getCaName.size()]),
getCaLink.toArray(new String[getCaLink.size()]),
getCaImg.toArray(new String[getCaImg.size()])));
}
}
canticles.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/LinearLayout1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#drawable/bg1"
android:orientation="vertical" >
<ListView
android:id="#+id/listView1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:divider="#b5b5b5"
android:dividerHeight="1dp"
android:listSelector="#drawable/list_selector" >
</ListView>
</LinearLayout>
custom_grid.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#drawable/list_selector"
android:gravity="left"
android:orientation="horizontal"
android:padding="10dip" >
<!-- ListRow Left sied Thumbnail image -->
<ImageView
android:id="#+id/caImgView"
android:layout_width="57dip"
android:layout_height="84dip"
android:layout_alignLeft="#+id/linearLayout1"
android:layout_alignTop="#+id/linearLayout1"
android:paddingLeft="0dip"
android:scaleType="fitXY"
android:src="#drawable/noimage" />
<LinearLayout
android:id="#+id/linearLayout2"
android:layout_width="170dip"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/targetmonth1"
android:layout_alignTop="#+id/targetmonth1"
android:layout_marginLeft="16dp"
android:layout_toRightOf="#+id/targetmonth1"
android:orientation="vertical"
android:padding="0dip" >
<TextView
android:id="#+id/caNameView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="#+id/linearLayout1"
android:layout_centerHorizontal="true"
android:layout_gravity="center_horizontal"
android:text="dddddddd"
android:textColor="#040404"
android:textSize="13dip"
android:textStyle="bold"
android:typeface="sans" />
<TextView
android:id="#+id/caLinkView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/caNameView"
android:layout_alignRight="#+id/caNameView"
android:layout_below="#+id/caNameView"
android:layout_gravity="center_horizontal"
android:text="author"
android:textColor="#343434"
android:textSize="9dip"
android:typeface="sans" />
</LinearLayout>
<ImageView
android:id="#+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:src="#drawable/arrow" />
</RelativeLayout>
use this
public List< String> caNameHolder = new ArrayList< String>();
instead of
public ArrayList< String> caNameHolder = new ArrayList< String>();

Categories