This question already has answers here:
How can I fix 'android.os.NetworkOnMainThreadException'?
(66 answers)
NetworkOnMainThreadException [duplicate]
(5 answers)
Closed 8 years ago.
When running the line
echoSocket = new Socket(serverHostname, 10008); My app crashes with error, NetworkOnMainThreadException error.
From what i have seen this related to trying to run Sockets on the UI thread. so how can i change my code (below) so it works?
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.os.Build;
public class MainActivity extends ActionBarActivity {
Button Bgo;
private static TextView TV1;
EditText Text;
String userInput;
Socket echoSocket = null;
PrintWriter out = null;
BufferedReader in = null;
String Responce = null;
String serverHostname;
int section = 0;
Boolean keepgoing = true;
Boolean g1o = true;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Bgo = (Button) findViewById(R.id.Go);
TV1 = (TextView) findViewById(R.id.tv1);
Text = (EditText) findViewById(R.id.Inputtext);
onclick();
}
public void send() {
// System.out.println("type the host name"); ->>updating
// serverHostname = new String(stdIn.readLine());
serverHostname = new String("192.168.1.105");
System.out.println("Attemping to connect to host " + serverHostname
+ " on port 10008.");
try {
echoSocket = new Socket(serverHostname, 10008);
out = new PrintWriter(echoSocket.getOutputStream(), true);
in = new BufferedReader(new InputStreamReader(
echoSocket.getInputStream()));
} catch (UnknownHostException e) {
TV1.setText("Don't know about host: " + serverHostname);
} catch (IOException e) {
TV1.setText("Couldn't get I/O for " + "the connection to: "
+ serverHostname);
}
TV1.setText("type VIEW-LOG for last 5 enteries (newset first) or DC to dissconect");
}
public void onclick() {
Bgo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (g1o = true) {
TV1.setText("conecting");
g1o = false;
send();
} else {
userInput = Text.getText().toString();
try {
if (userInput.equals("VIEW-LOG")) {
out.println(userInput);
int i = 0;
while (i < 5) {
Responce = in.readLine();
System.out.println(Responce);//this will be replace once this is working
i++;
}
} else if (userInput.equals("DC")) {
keepgoing = false;
System.out.println("dc");
out.println(userInput);
} else {
out.println(userInput);
System.out.println(in.readLine());
}
} catch (IOException e) {
}
}
}
});
}
public void Close() {
try {
out.close();
in.close();
echoSocket.close();
} catch (IOException e) {
}
}
}
XML:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/tv1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="PlaceHolder"
android:textAppearance="?android:attr/textAppearanceLarge" />
<EditText
android:id="#+id/Inputtext"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10" >
<requestFocus />
</EditText>
<Button
android:id="#+id/Go"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Go" />
</LinearLayout>
What this dose: one one button press it runs send(); that make the conection to a server. when it is pressed again it send the test in the edittext to the server and if it is DC it disconects from the server, if it is VIEW-LOG the server sends 5 lots of strings
This exception raises when you perform some network operation on main thread which android does not allow to do. Move your send method call to non-UI thread or better move your code into AsyncTask.
You should not perform any network related operation on main thread.
Either use a Handler http://developer.android.com/reference/android/os/Handler.html
OR
an AsyncTask http://developer.android.com/reference/android/os/AsyncTask.html
Related
In my activity, I want to take voice input when we click imageView and convert into text and display it in textfield and after we press button it converts it into french(currently it is fixed) and display it in textfield2.
I am using yandex translator.
My error::
When I click button for the first time nothing happens in textfield2 but in log, it display the correct translation.After my 2nd click,it changes the textfield2. But i want to show the translation after 1st click only.Why it is taking 2 click for working while my output is coming correct after 2nd click??
here is my XML file:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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"
tools:context=".MainActivity">
<Button
android:id="#+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button"
android:layout_centerHorizontal="true"
android:layout_below="#+id/textView"
tools:layout_editor_absoluteX="131dp"
tools:layout_editor_absoluteY="202dp" />
<ImageView
android:id="#+id/imageView"
android:layout_centerHorizontal="true"
android:layout_width="267dp"
android:layout_height="244dp"
app:srcCompat="#android:drawable/ic_btn_speak_now" />
<TextView
android:id="#+id/textView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textSize="30sp"
android:layout_below="#+id/imageView"
android:layout_centerHorizontal="true"
android:text="Text to be Translated" />
<TextView
android:id="#+id/textView2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/button"
android:text="Translated Text"
android:textSize="30sp"
/>
</RelativeLayout>
Here is my MainActivty:
package com.example.translator;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.speech.RecognizerIntent;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.Locale;
public class MainActivity extends AppCompatActivity {
final static int REQUEST_CODE_SPEECH=1000;
ImageView listen;
TextView ans,mresult;
Context context=this;
Button b;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listen=findViewById(R.id.imageView);
ans=findViewById(R.id.textView);
mresult=findViewById(R.id.textView2);
b=findViewById(R.id.button);
listen.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
speak();
}
});
b.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String textToBeTranslated = ans.getText().toString();
String languagePair = "en-fr"; //English to French ("<source_language>-<target_language>")
//Executing the translation function
Translate(textToBeTranslated,languagePair);
}
});
}
void Translate(String textToBeTranslated,String languagePair){
TranslatorBackgroundTask translatorBackgroundTask= new TranslatorBackgroundTask(context);
if(Build.VERSION.SDK_INT >=Build.VERSION_CODES.HONEYCOMB) {
translatorBackgroundTask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR,textToBeTranslated,languagePair);
} else {
translatorBackgroundTask.execute(textToBeTranslated,languagePair);
}
Log.d("Translation Result:", translatorBackgroundTask.t); // Logs the result in Android Monitor
mresult.setText(translatorBackgroundTask.t);
}
void speak(){
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, "hi say something!!!");
try{
startActivityForResult(intent,REQUEST_CODE_SPEECH);
}
catch(Exception e) {
Toast.makeText(MainActivity.this, "" + e.getMessage(),Toast.LENGTH_LONG).show();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch(requestCode){
case REQUEST_CODE_SPEECH:{
if(resultCode==RESULT_OK && data!=null) {
ArrayList<String>result=data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
ans.setText(result.get(0));
}
break;
}
}
}
}
Here is my API File:
package com.example.translator;
import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.Toast;
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;
public class TranslatorBackgroundTask extends AsyncTask<String, Void, String> {
//Declare Context
Context ctx;
public static String t="";
//Set Context
TranslatorBackgroundTask(Context ctx){
this.ctx = ctx;
}
#Override
public String doInBackground(String... params) {
//String variables
String textToBeTranslated = params[0];
String languagePair = params[1];
String jsonString;
try {
//Set up the translation call URL
String yandexKey = "MY-API-KEY";
String yandexUrl = "https://translate.yandex.net/api/v1.5/tr.json/translate?key=" + yandexKey
+ "&text=" + textToBeTranslated + "&lang=" + languagePair;
URL yandexTranslateURL = new URL(yandexUrl);
//Set Http Conncection, Input Stream, and Buffered Reader
HttpURLConnection httpJsonConnection = (HttpURLConnection) yandexTranslateURL.openConnection();
InputStream inputStream = httpJsonConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
//Set string builder and insert retrieved JSON result into it
StringBuilder jsonStringBuilder = new StringBuilder();
while ((jsonString = bufferedReader.readLine()) != null) {
jsonStringBuilder.append(jsonString + "\n");
}
//Close and disconnect
bufferedReader.close();
inputStream.close();
httpJsonConnection.disconnect();
//Making result human readable
String resultString = jsonStringBuilder.toString().trim();
//Getting the characters between [ and ]
resultString = resultString.substring(resultString.indexOf('[')+1);
resultString = resultString.substring(0,resultString.indexOf("]"));
//Getting the characters between " and "
resultString = resultString.substring(resultString.indexOf("\"")+1);
resultString = resultString.substring(0,resultString.indexOf("\""));
Log.d("Translation Result:", resultString);
t=resultString;
return jsonStringBuilder.toString().trim();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onPostExecute(String result) {
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
}
I think it's this line:
mresult.setText(TranslatorBackgroundTask.t);
Shouldn't it be:
mresult.setText(translatorBackgroundTask.t);
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
I'm writing a code for a client on an android device to send messages to a server and the server is supposed to reply to it. the layout is composed of an edit text field, a button and a text view. When the button is pressed the message should be taken from the edit text field and sent to the server, when the server receives the message it should reply with a message stating that it has received it and then that reply message is to be received by the client and written on the text view. The problem is that the message is sent to the server when I press on button twice and then when I press the third time the server crashes. Any help on what's the problem would really be appreciated. Thanks in advance.
This is the logcat error that I get
02-04 04:18:38.065: I/Error51(32228): android.os.NetworkOnMainThreadException
MainActivity.java
package com.example.testclientandroid;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends Activity {
static Socket socket;
static final int SERVERPORT = 50000;
static final String SERVER_IP = "192.168.0.105";
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new Thread(new ClientThread()).start();
Button button = (Button) findViewById(R.id.button1);
button.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
EditText editText = (EditText) findViewById(R.id.editText1);
TextView textView = (TextView) findViewById(R.id.textView2);
try {
String str = editText.getText().toString();
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
out.println(str);
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
textView.setText(in.readLine());
} catch (UnknownHostException e) {
Log.i("Error47", e.toString());
} catch (IOException e) {
Log.i("Error49", e.toString());
} catch (Exception e) {
Log.i("Error51", e.toString());
}
}
});
}
private static class ClientThread implements Runnable {
public void run() {
try {
InetAddress serverAddr = InetAddress.getByName(SERVER_IP);
socket = new Socket(serverAddr, SERVERPORT);
} catch (UnknownHostException e) {
Log.i("Error64", e.toString());
} catch (IOException e) {
Log.i("Error65", e.toString());
}
}
}
}
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<EditText
android:id="#+id/editText1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:ems="10" >
<requestFocus />
</EditText>
<Button
android:id="#+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/editText1"
android:layout_centerHorizontal="true"
android:layout_marginTop="48dp"
android:text="Send" />
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_below="#+id/button1"
android:layout_marginTop="53dp"
android:text="Response:"
android:textAppearance="?android:attr/textAppearanceLarge" />
<TextView
android:id="#+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/textView1"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_below="#+id/textView1" />
</RelativeLayout>
Android Manifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.testclientandroid"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="10"
android:targetSdkVersion="19" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.INTERNET"/>
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.testclientandroid.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>
</application>
</manifest>
ServerClass.java
package mainPackage;
//Server
import java.net.*;
import java.io.*;
public class ServerClass
{
static final int PORTNUMBER = 50000;
public static void main(String[] args) throws IOException
{
new Thread(new ServerThread()).start();
}
public static class ServerThread implements Runnable {
ServerSocket serverSocket;
Socket clientSocket;
public void run() {
try {
serverSocket = new ServerSocket(PORTNUMBER);
clientSocket = serverSocket.accept();
new Thread(new CommunicationThread(clientSocket)).start();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
public static class CommunicationThread implements Runnable {
Socket socket;
BufferedReader in;
PrintWriter out;
public CommunicationThread(Socket clientSocket) {
socket = clientSocket;
try {
in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
//out = new PrintWriter(clientSocket.getOutputStream(), true);
} catch (IOException e) {
System.out.println(e.toString());
}
}
public void run() {
try {
while(in.readLine() != null)
{
System.out.println(in.readLine());
out.println(in.readLine() + " Received");
}
} catch (IOException e) {
System.out.println(e.toString());
}
}
}
}
Update
I tried using asyncTask, I don't get a Logcat error anymore but now the server doesn't receive the message at all,
Here's the modified code:
package com.example.testclientandroid;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends Activity {
static Socket socket;
static final int SERVERPORT = 50000;
static final String SERVER_IP = "192.168.0.105";
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new Thread(new ClientThread()).start();
Button button = (Button) findViewById(R.id.button1);
button.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
new CommunicationTask().execute();
}
});
}
private static class ClientThread implements Runnable {
public void run() {
try {
InetAddress serverAddr = InetAddress.getByName(SERVER_IP);
socket = new Socket(serverAddr, SERVERPORT);
} catch (UnknownHostException e) {
Log.i("Error64", e.toString());
} catch (IOException e) {
Log.i("Error65", e.toString());
}
}
}
private class CommunicationTask extends AsyncTask<Void, Void, String> {
#Override
protected String doInBackground(Void... params) {
// TODO Auto-generated method stub
EditText editText = (EditText) findViewById(R.id.editText1);
String result;
try {
String str = editText.getText().toString();
PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
out.println(str);
BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
result = in.readLine();
return result;
} catch (UnknownHostException e) {
Log.i("Error47", e.toString());
} catch (IOException e) {
Log.i("Error49", e.toString());
} catch (Exception e) {
Log.i("Error51", e.toString());
}
return "Error";
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
TextView textView = (TextView) findViewById(R.id.textView2);
textView.setText(result);
}
}
}
Any operation that needs internet should be done on background. Try to read Asynctask to remove this error.
Try to use asynctask , its simple and easier.AsyncTask enables proper and easy use of the UI thread. This class allows to perform background operations and publish results on the UI thread without having to manipulate threads and/or handlers.
Here is an example
private class DownloadFilesTask extends AsyncTask {
protected Long doInBackground(URL... urls) {
int count = urls.length;
long totalSize = 0;
for (int i = 0; i < count; i++) {
totalSize += Downloader.downloadFile(urls[i]);
publishProgress((int) ((i / (float) count) * 100));
// Escape early if cancel() is called
if (isCancelled()) break;
}
return totalSize;
}
protected void onProgressUpdate(Integer... progress) {
setProgressPercent(progress[0]);
}
protected void onPostExecute(Long result) {
showDialog("Downloaded " + result + " bytes");
}
}
I am able to properly send my data through UDP socket , but when I receive data it keeps on waiting at receive command I don't know what is causing this.
Please have a look at my code below.
I am able to properly receive data at server side from android device, but when I send data from server side to android device it doesn't receive. but when I send data from server to any other client e.g PC application it receive and displays data properly.
class Task implements Runnable {
#Override
public void run() {
try {
String messageStr = "feed";
int server_port = 8888;
InetAddress local = InetAddress.getByName("10.0.2.2");
int msg_length = messageStr.length();
byte[] message = messageStr.getBytes();
DatagramSocket s = new DatagramSocket();
//
DatagramPacket p = new DatagramPacket(message, msg_length, local, server_port);
s.send(p);//properly able to send data. i receive data to server
for (int i = 0; i <= 20; i++) {
final int value = i;
message = new byte[30000];
p = new DatagramPacket(message,message.length );
s.receive(p); //keeps on waiting here but i am sending data back from server, but it never receives
final byte[] data = p.getData();;
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
handler.post(new Runnable() {
#Override
public void run() {
progressBar.setProgress(value);
imageView.setImageBitmap(BitmapFactory.decodeByteArray(data,0,data.length));
}
});
}
}
catch(Exception ex)
{
}
}
}
Documentation in Eclipse:
Receives a packet from this socket and stores it in the argument pack.
All fields of pack must be set according to the data received. If the
received data is longer than the packet buffer size it is truncated.
This method blocks until a packet is received or a timeout has
expired.
The "s.receive(p);" command blocks the thread until it receices data or the timeout set with setSoTimeout(timeout) is over.
I have made 2 classes to make my communication happen.
First UDP-Server:
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Build;
public class UDP_Server
{
private AsyncTask<Void, Void, Void> async;
private boolean Server_aktiv = true;
#SuppressLint("NewApi")
public void runUdpServer()
{
async = new AsyncTask<Void, Void, Void>()
{
#Override
protected Void doInBackground(Void... params)
{
byte[] lMsg = new byte[4096];
DatagramPacket dp = new DatagramPacket(lMsg, lMsg.length);
DatagramSocket ds = null;
try
{
ds = new DatagramSocket(Main.SERVER_PORT);
while(Server_aktiv)
{
ds.receive(dp);
Intent i = new Intent();
i.setAction(Main.MESSAGE_RECEIVED);
i.putExtra(Main.MESSAGE_STRING, new String(lMsg, 0, dp.getLength()));
Main.MainContext.getApplicationContext().sendBroadcast(i);
}
}
catch (Exception e)
{
e.printStackTrace();
}
finally
{
if (ds != null)
{
ds.close();
}
}
return null;
}
};
if (Build.VERSION.SDK_INT >= 11) async.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
else async.execute();
}
public void stop_UDP_Server()
{
Server_aktiv = false;
}
}
I send the received data to an BroadcastReceiver and there you can do what ever you want to with the data.
And now my client to send the data. In this code I send a broadcast, but I think it will be no problem to change the code for sending to a direct IP or something.
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import android.annotation.SuppressLint;
import android.os.AsyncTask;
import android.os.Build;
public class UDP_Client
{
private AsyncTask<Void, Void, Void> async_cient;
public String Message;
#SuppressLint("NewApi")
public void NachrichtSenden()
{
async_cient = new AsyncTask<Void, Void, Void>()
{
#Override
protected Void doInBackground(Void... params)
{
DatagramSocket ds = null;
try
{
ds = new DatagramSocket();
DatagramPacket dp;
dp = new DatagramPacket(Message.getBytes(), Message.length(), Main.BroadcastAddress, Main.SERVER_PORT);
ds.setBroadcast(true);
ds.send(dp);
}
catch (Exception e)
{
e.printStackTrace();
}
finally
{
if (ds != null)
{
ds.close();
}
}
return null;
}
protected void onPostExecute(Void result)
{
super.onPostExecute(result);
}
};
if (Build.VERSION.SDK_INT >= 11) async_cient.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
else async_cient.execute();
}
And here is how you instantiate the classes from your main class.
//start UDP server
Server = new UDP_Server();
Server.runUdpServer();
//UDP Client erstellen
Client = new UDP_Client();
And here how to send a message with the client.
//Set message
Client.Message = "Your message";
//Send message
Client.NachrichtSenden();
To stop the UDP_Server, just set Server.Server_aktiv to false.
To set the message above u can also write a "setMessage(String message)" methode or something like that.
Here, in this post you will find the detailed code for establishing socket between devices or between two application in the same mobile.
You have to create two application to test below code.
In both application's manifest file, add below permission
<uses-permission android:name="android.permission.INTERNET" />
1st App code: UDP Client Socket
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TableRow
android:id="#+id/tr_send_message"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_alignParentTop="true"
android:layout_marginTop="11dp">
<EditText
android:id="#+id/edt_send_message"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:layout_marginRight="10dp"
android:layout_marginLeft="10dp"
android:hint="Enter message"
android:inputType="text" />
<Button
android:id="#+id/btn_send"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="10dp"
android:text="Send" />
</TableRow>
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_below="#+id/tr_send_message"
android:layout_marginTop="25dp"
android:id="#+id/scrollView2">
<TextView
android:id="#+id/tv_reply_from_server"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" />
</ScrollView>
</RelativeLayout>
UDPClientSocketActivity.java
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
/**
* Created by Girish Bhalerao on 5/4/2017.
*/
public class UDPClientSocketActivity extends AppCompatActivity implements View.OnClickListener {
private TextView mTextViewReplyFromServer;
private EditText mEditTextSendMessage;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button buttonSend = (Button) findViewById(R.id.btn_send);
mEditTextSendMessage = (EditText) findViewById(R.id.edt_send_message);
mTextViewReplyFromServer = (TextView) findViewById(R.id.tv_reply_from_server);
buttonSend.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_send:
sendMessage(mEditTextSendMessage.getText().toString());
break;
}
}
private void sendMessage(final String message) {
final Handler handler = new Handler();
Thread thread = new Thread(new Runnable() {
String stringData;
#Override
public void run() {
DatagramSocket ds = null;
try {
ds = new DatagramSocket();
// IP Address below is the IP address of that Device where server socket is opened.
InetAddress serverAddr = InetAddress.getByName("xxx.xxx.xxx.xxx");
DatagramPacket dp;
dp = new DatagramPacket(message.getBytes(), message.length(), serverAddr, 9001);
ds.send(dp);
byte[] lMsg = new byte[1000];
dp = new DatagramPacket(lMsg, lMsg.length);
ds.receive(dp);
stringData = new String(lMsg, 0, dp.getLength());
} catch (IOException e) {
e.printStackTrace();
} finally {
if (ds != null) {
ds.close();
}
}
handler.post(new Runnable() {
#Override
public void run() {
String s = mTextViewReplyFromServer.getText().toString();
if (stringData.trim().length() != 0)
mTextViewReplyFromServer.setText(s + "\nFrom Server : " + stringData);
}
});
}
});
thread.start();
}
}
2nd App Code - UDP Server Socket
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="#+id/btn_stop_receiving"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="STOP Receiving data"
android:layout_alignParentTop="true"
android:enabled="false"
android:layout_centerHorizontal="true"
android:layout_marginTop="89dp" />
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/btn_stop_receiving"
android:layout_marginTop="35dp"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true">
<TextView
android:id="#+id/tv_data_from_client"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" />
</ScrollView>
<Button
android:id="#+id/btn_start_receiving"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="START Receiving data"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="14dp" />
</RelativeLayout>
UDPServerSocketActivity.java
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
/**
* Created by Girish Bhalerao on 5/4/2017.
*/
public class UDPServerSocketActivity extends AppCompatActivity implements View.OnClickListener {
final Handler handler = new Handler();
private Button buttonStartReceiving;
private Button buttonStopReceiving;
private TextView textViewDataFromClient;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buttonStartReceiving = (Button) findViewById(R.id.btn_start_receiving);
buttonStopReceiving = (Button) findViewById(R.id.btn_stop_receiving);
textViewDataFromClient = (TextView) findViewById(R.id.tv_data_from_client);
buttonStartReceiving.setOnClickListener(this);
buttonStopReceiving.setOnClickListener(this);
}
private void startServerSocket() {
Thread thread = new Thread(new Runnable() {
private String stringData = null;
#Override
public void run() {
byte[] msg = new byte[1000];
DatagramPacket dp = new DatagramPacket(msg, msg.length);
DatagramSocket ds = null;
try {
ds = new DatagramSocket(9001);
//ds.setSoTimeout(50000);
ds.receive(dp);
stringData = new String(msg, 0, dp.getLength());
updateUI(stringData);
String msgToSender = "Bye Bye ";
dp = new DatagramPacket(msgToSender.getBytes(), msgToSender.length(), dp.getAddress(), dp.getPort());
ds.send(dp);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (ds != null) {
ds.close();
}
}
}
});
thread.start();
}
private void updateUI(final String stringData) {
handler.post(new Runnable() {
#Override
public void run() {
String s = textViewDataFromClient.getText().toString();
if (stringData.trim().length() != 0)
textViewDataFromClient.setText(s + "\n" + "From Client : " + stringData);
}
});
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_start_receiving:
startServerSocket();
buttonStartReceiving.setEnabled(false);
buttonStopReceiving.setEnabled(true);
break;
case R.id.btn_stop_receiving:
//Add logic to stop server socket yourself
buttonStartReceiving.setEnabled(true);
buttonStopReceiving.setEnabled(false);
break;
}
}
}
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>();