ENETUNREACH (Network is unreachable) error? What am I doing wroung? - java

I am attempting to establish a connection with android and my server. My server sends HTML5 responses.
My main activity
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
//atempting connection to sever
Thread thread = new Thread(new Runnable(){
#Override
public void run() {
try {
SimpleHTTPRequest connect=new SimpleHTTPRequest();
connect.attemptConnect();
} catch (Exception e) {
e.printStackTrace();
}
}
});
thread.start();
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
My network class
public class SimpleHTTPRequest {
HttpURLConnection connection = null;
BufferedReader rd = null;
StringBuilder sb = null;
String line = null;
public void attemptConnect() {
try {
URL serverAddress = new URL("myUrl");
//set up out communications stuff
connection = null;
//Set up the initial connection
connection = (HttpURLConnection) serverAddress.openConnection();
connection.setRequestMethod("GET");
connection.connect();
//get the output stream writer and write the output to the server
//not needed in this example
//wr = new OutputStreamWriter(connection.getOutputStream());
//wr.write("");
//wr.flush();
//read the result from the server
rd = new BufferedReader(new InputStreamReader(connection.getInputStream()));
sb = new StringBuilder();
while ((line = rd.readLine()) != null) {
sb.append(line + '\n');
System.out.println(sb.toString());
//This will return the String Server Sent event from the server
//Need to parse the data as JSON Now
//attempt to parse string from sb=StringBuilder into a JSon object
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (ProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
//close the connection, set all objects to null
connection.disconnect();
rd = null;
sb = null;
connection = null;
}
}
}
I did this in eclipse and it worked, so what am I doing wroung?

Related

Endless RecyclerView with ProgressBar in Search activity

I am new at android. I have a search activity which searches for a query using async task, i want to implement endless/infinite scrolling when user reaches bottom. I want to add a parameter startrow to async task which will then be passed on to the server telling which row to begin.
// CONNECTION_TIMEOUT and READ_TIMEOUT are in milliseconds
public static final int CONNECTION_TIMEOUT = 10000;
public static final int READ_TIMEOUT = 15000;
private RecyclerView mRVFish;
private AdapterFish mAdapter;
private LinearLayoutManager mLayoutManager;
private String searchQuery;
SearchView searchView = null;
private String query;
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// adds item to action bar
getMenuInflater().inflate(R.menu.search_main, menu);
// Get Search item from action bar and Get Search service
MenuItem searchItem = menu.findItem(R.id.action_search);
SearchManager searchManager = (SearchManager) MainActivity.this.getSystemService(Context.SEARCH_SERVICE);
if (searchItem != null) {
searchView = (SearchView) searchItem.getActionView();
}
if (searchView != null) {
searchView.setSearchableInfo(searchManager.getSearchableInfo(MainActivity.this.getComponentName()));
searchView.setIconified(false);
}
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
return super.onOptionsItemSelected(item);
}
Every time when you press search button on keypad an Activity is recreated which in turn calls this function
#Override
protected void onNewIntent(Intent intent) {
// Get search query and create object of class AsyncFetch
if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
query = intent.getStringExtra(SearchManager.QUERY);
if (searchView != null) {
searchView.clearFocus();
}
new AsyncFetch(query).execute();
}
}
class AsyncFetch which will fetch data from the server
private class AsyncFetch extends AsyncTask<String, String, String> {
ProgressDialog pdLoading = new ProgressDialog(MainActivity.this);
HttpURLConnection conn;
URL url = null;
String searchQuery;
public AsyncFetch(String searchQuery){
this.searchQuery=searchQuery;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
//this method will be running on UI thread
pdLoading.setMessage("\tLoading...");
pdLoading.setCancelable(false);
pdLoading.show();
}
#Override
protected String doInBackground(String... params) {
try {
// URL address wherephp file resides
url = new URL("http://someurl/json/search.php");
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return e.toString();
}
try {
// Setup HttpURLConnection class to send and receive data from php and mysql
conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(READ_TIMEOUT);
conn.setConnectTimeout(CONNECTION_TIMEOUT);
conn.setRequestMethod("POST");
// setDoInput and setDoOutput to true as we send and recieve data
conn.setDoInput(true);
conn.setDoOutput(true);
// add parameter to our above url
Uri.Builder builder = new Uri.Builder().appendQueryParameter("searchQuery", searchQuery);
String query = builder.build().getEncodedQuery();
OutputStream os = conn.getOutputStream();
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, "UTF-8"));
writer.write(query);
writer.flush();
writer.close();
os.close();
conn.connect();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
return e1.toString();
}
try {
int response_code = conn.getResponseCode();
// Check if successful connection made
if (response_code == HttpURLConnection.HTTP_OK) {
// Read data sent from server
InputStream input = conn.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
StringBuilder result = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
result.append(line);
}
// Pass data to onPostExecute method
return (result.toString());
} else {
return("Connection error");
}
} catch (IOException e) {
e.printStackTrace();
return e.toString();
} finally {
conn.disconnect();
}
}
#Override
protected void onPostExecute(String result) {
//this method will be running on UI thread
pdLoading.dismiss();
List<DataFish> data=new ArrayList<>();
pdLoading.dismiss();
if(result.equals("no rows")) {
Toast.makeText(MainActivity.this, "No Results found for entered query", Toast.LENGTH_LONG).show();
}else{
try {
JSONArray jArray = new JSONArray(result);
// Extract data from json and store into ArrayList as class objects
for (int i = 0; i < jArray.length(); i++) {
JSONObject json_data = jArray.getJSONObject(i);
DataFish fishData = new DataFish();
try {
fishData.fileName = URLDecoder.decode(json_data.getString("file"), "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
fishData.linkName = json_data.getString("link");
fishData.reg_date = json_data.getString("reg_date");
fishData.fileSize = json_data.getString("filesize");
data.add(fishData);
}
// Setup and Handover data to recyclerview
mRVFish = (RecyclerView) findViewById(R.id.fishPriceList);
mAdapter = new AdapterFish(MainActivity.this, data);
// mRVFish.setLayoutManager(new LinearLayoutManager(MainActivity.this));
mLayoutManager = new LinearLayoutManager(MainActivity.this);
mRVFish.setLayoutManager(mLayoutManager);
mRVFish.setAdapter(mAdapter);
} catch (JSONException e) {
// You to understand what actually error is and handle it appropriately
Toast.makeText(MainActivity.this, e.toString(), Toast.LENGTH_LONG).show();
Toast.makeText(MainActivity.this, result.toString(), Toast.LENGTH_LONG).show();
}
}
}
}
Add EndlessScrollListener to recyclerView from link:
https://gist.github.com/zfdang/38ae655a4fc401c99789#file-endlessrecycleronscrolllistener-java
override onLoadMore method and call your AsyncFetch Task.

I want another class like main activity to receive data from bluetooth, am unable to switch to another activity

I want same activity as Main activity and i just want that the another activity should also receive the same data coming from bluetooth after switching to another activity but while switching to another activity the connection failure occurs and shows:
> W/BluetoothAdapter: getBluetoothService() called with no
> BluetoothManagerCallback I/Choreographer: Skipped 52 frames! The
> application may be doing too much work on its main thread.
Please help.
DeviceListActivity
public class DeviceListActivity extends Activity {
// Debugging for LOGCAT
private static final String TAG = "DeviceListActivity";
private static final boolean D = true;
// declare button for launching website and textview for connection status
//Button tlbutton;
TextView textView1;
// EXTRA string to send on to mainactivity
public static String EXTRA_DEVICE_ADDRESS = "device_address";
// Member fields
private BluetoothAdapter mBtAdapter;
private ArrayAdapter<String> mPairedDevicesArrayAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.device_list);
}
#Override
public void onResume()
{
super.onResume();
checkBTState();
textView1 = (TextView) findViewById(R.id.connecting);
textView1.setTextSize(40);
textView1.setText(" ");
// Initialize array adapter for paired devices
mPairedDevicesArrayAdapter = new ArrayAdapter<String>(this, R.layout.device_name);
// Find and set up the ListView for paired devices
ListView pairedListView = (ListView) findViewById(R.id.paired_devices);
pairedListView.setAdapter(mPairedDevicesArrayAdapter);
pairedListView.setOnItemClickListener(mDeviceClickListener);
// Get the local Bluetooth adapter
mBtAdapter = BluetoothAdapter.getDefaultAdapter();
// Get a set of currently paired devices and append to 'pairedDevices'
Set<BluetoothDevice> pairedDevices = mBtAdapter.getBondedDevices();
// Add previosuly paired devices to the array
if (pairedDevices.size() > 0) {
findViewById(R.id.title_paired_devices).setVisibility(View.VISIBLE);//make title viewable
for (BluetoothDevice device : pairedDevices) {
mPairedDevicesArrayAdapter.add(device.getName() + "\n" + device.getAddress());
}
} else {
String noDevices = getResources().getText(R.string.none_paired).toString();
mPairedDevicesArrayAdapter.add(noDevices);
}
}
// Set up on-click listener for the list (nicked this - unsure)
private AdapterView.OnItemClickListener mDeviceClickListener = new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> av, View v, int arg2, long arg3) {
textView1.setText("Connecting...");
// Get the device MAC address, which is the last 17 chars in the View
String info = ((TextView) v).getText().toString();
String address = info.substring(info.length() - 17);
// Make an intent to start next activity while taking an extra which is the MAC address.
Intent i = new Intent(DeviceListActivity.this, MainActivity.class);
i.putExtra(EXTRA_DEVICE_ADDRESS, address);
startActivity(i);
}
};
private void checkBTState() {
// Check device has Bluetooth and that it is turned on
mBtAdapter=BluetoothAdapter.getDefaultAdapter(); // CHECK THIS OUT THAT IT WORKS!!!
if(mBtAdapter==null) {
Toast.makeText(getBaseContext(), "Device does not support Bluetooth", Toast.LENGTH_SHORT).show();
} else {
if (mBtAdapter.isEnabled()) {
Log.d(TAG, "...Bluetooth ON...");
} else {
//Prompt user to turn on Bluetooth
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, 1);
}
}
}
}
MainActivity
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener {
Button btnOn, btnOff;
TextView txtString, txtStringLength, sensorView0, sensorView1, sensorView2, sensorView3;
Handler bluetoothIn;
final int handlerState = 0; //used to identify handler message
private BluetoothAdapter btAdapter = null;
private BluetoothSocket btSocket = null;
private StringBuilder recDataString = new StringBuilder();
public static ConnectedThread mConnectedThread;
// SPP UUID service - this should work for most devices
private static final UUID BTMODULEUUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
// String for MAC address
public static String address;
public static String address2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnOn = (Button) findViewById(R.id.buttonOn);
btnOff = (Button) findViewById(R.id.buttonOff);
txtString = (TextView) findViewById(R.id.txtString);
txtStringLength = (TextView) findViewById(R.id.testView1);
sensorView0 = (TextView) findViewById(R.id.sensorView0);
sensorView1 = (TextView) findViewById(R.id.sensorView1);
sensorView2 = (TextView) findViewById(R.id.sensorView2);
sensorView3 = (TextView) findViewById(R.id.sensorView3);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
// setSupportActionBar(toolbar);
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
navigationView.setNavigationItemSelectedListener(this);
bluetoothIn = new Handler() {
public void handleMessage(android.os.Message msg) {
if (msg.what == handlerState) { //if message is what we want
String readMessage = (String) msg.obj; // msg.arg1 = bytes from connect thread
recDataString.append(readMessage); //keep appending to string until ~
int endOfLineIndex = recDataString.indexOf("~"); // determine the end-of-line
if (endOfLineIndex > 0) { // make sure there data before ~
String dataInPrint = recDataString.substring(0, endOfLineIndex); // extract string
txtString.setText("Data Received = " + dataInPrint);
int dataLength = dataInPrint.length(); //get length of data received
txtStringLength.setText("String Length = " + String.valueOf(dataLength));
if (recDataString.charAt(0) == '#') //if it starts with # we know it is what we are looking for
{
String sensor0 = recDataString.substring(1, 5); //get sensor value from string between indices 1-5
String sensor1 = recDataString.substring(6, 10); //same again...
String sensor2 = recDataString.substring(11, 15);
String sensor3 = recDataString.substring(16, 20);
sensorView0.setText(" Sensor 0 Voltage = " + sensor0 + "V"); //update the textviews with sensor values
sensorView1.setText(" Sensor 1 Voltage = " + sensor1 + "V");
sensorView2.setText(" Sensor 2 Voltage = " + sensor2 + "V");
sensorView3.setText(" Sensor 3 Voltage = " + sensor3 + "V");
}
recDataString.delete(0, recDataString.length()); //clear all string data
// strIncom =" ";
dataInPrint = " ";
}
}
}
};
btAdapter = BluetoothAdapter.getDefaultAdapter(); // get Bluetooth adapter
checkBTState();
// Set up onClick listeners for buttons to send 1 or 0 to turn on/off LED
btnOff.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
mConnectedThread.write("0"); // Send "0" via Bluetooth
Toast.makeText(getBaseContext(), "Turn off LED", Toast.LENGTH_SHORT).show();
}
});
btnOn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
mConnectedThread.write("1"); // Send "1" via Bluetooth
Toast.makeText(getBaseContext(), "Turn on LED", Toast.LENGTH_SHORT).show();
}
});
}
private void checkBTState() {
if(btAdapter==null) {
Toast.makeText(getBaseContext(), "Device does not support bluetooth", Toast.LENGTH_LONG).show();
} else {
if (btAdapter.isEnabled()) {
} else {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, 1);
}
}
}
#Override
public void onBackPressed() {
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
#Override
public void onResume() {
super.onResume();
//Get MAC address from DeviceListActivity via intent
Intent intent = getIntent();
//Get the MAC address from the DeviceListActivty via EXTRA
address = intent.getStringExtra(DeviceListActivity.EXTRA_DEVICE_ADDRESS);
//create device and set the MAC address
BluetoothDevice device = btAdapter.getRemoteDevice(address);
try {
btSocket = createBluetoothSocket(device);
} catch (IOException e) {
Toast.makeText(getApplicationContext(), "Socket creation failed", Toast.LENGTH_LONG).show();
}
// Establish the Bluetooth socket connection.
try
{
btSocket.connect();
} catch (IOException e) {
try
{
btSocket.close();
} catch (IOException e2)
{
//insert code to deal with this
}
}
mConnectedThread = new ConnectedThread(btSocket);
mConnectedThread.start();
//I send a character when resuming.beginning transmission to check device is connected
//If it is not an exception will be thrown in the write method and finish() will be called
mConnectedThread.write("x");
}
public void onPause()
{
super.onPause();
try
{
//Don't leave Bluetooth sockets open when leaving activity
btSocket.close();
} catch (IOException e2) {
//insert code to deal with this
}
runOnUiThread(new Runnable() {
#Override
public void run() {
try {
mConnectedThread.wait();
} catch (Exception e) {
}
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
private BluetoothSocket createBluetoothSocket(BluetoothDevice device) throws IOException {
return device.createRfcommSocketToServiceRecord(BTMODULEUUID);
//creates secure outgoing connecetion with BT device using UUID
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#SuppressWarnings("StatementWithEmptyBody")
#Override
public boolean onNavigationItemSelected(MenuItem item) {
// Handle navigation view item clicks here.
int id = item.getItemId();
if (id == R.id.nav_additem) {
Intent addIntent = new Intent(getApplicationContext(),AddActivity2.class);
address2 = address;
startActivity(addIntent);
try {
}catch (Exception e){}
} else if (id == R.id.nav_viewItems) {
} else if (id == R.id.nav_favourite) {
} else if (id == R.id.nav_sensors) {
} else if (id == R.id.nav_share) {
} else if (id == R.id.nav_send) {
}
DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawer.closeDrawer(GravityCompat.START);
return true;
}
//create new class for connect thread
class ConnectedThread extends Thread {
private final InputStream mmInStream;
private final OutputStream mmOutStream;
//creation of the connect thread
public ConnectedThread(BluetoothSocket socket) {
InputStream tmpIn = null;
OutputStream tmpOut = null;
try {
//Create I/O streams for connection
tmpIn = socket.getInputStream();
tmpOut = socket.getOutputStream();
} catch (IOException e) { }
mmInStream = tmpIn;
mmOutStream = tmpOut;
}
public void run() {
byte[] buffer = new byte[256];
int bytes;
// Keep looping to listen for received messages
while (true) {
try {
bytes = mmInStream.read(buffer); //read bytes from input buffer
String readMessage = new String(buffer, 0, bytes);
// Send the obtained bytes to the UI Activity via handler
bluetoothIn.obtainMessage(handlerState, bytes, -1, readMessage).sendToTarget();
} catch (IOException e) {
break;
}
}
}
//write method
public void write(String input) {
byte[] msgBuffer = input.getBytes(); //converts entered String into bytes
try {
mmOutStream.write(msgBuffer); //write bytes over BT connection via outstream
} catch (IOException e) {
//if you cannot write, close the application
Toast.makeText(getBaseContext(), "Connection Failure", Toast.LENGTH_LONG).show();
finish();
}
}
}
}

How to show alertdialog before asynctask start

I want to show an alertdialog and get some input from user and after that, processing that inputs in an asynctask but the alertdialog become dismissed before get inputs and asynctask start to execute.
What should I do? Please help me. Here is my code;
private String[] newspapers,newspapersUrl,newspapersPath;
private String[] choosed,choosedUrl,choosedPath;
private boolean[] checked;
private int perNewspaper;
private boolean returned = false;
private AlertDialog.Builder builder;
private FetchingNewsByChoice fetchingNewsByChoice;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
returned = AlertDialogCreation();
if(returned)
{
fetchingNewsByChoice = new FetchingNewsByChoice((AppCompatActivity)MainActivity.this,choosed,choosedPath,perNewspaper);
fetchingNewsByChoice.execute();
}
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
//***** Alert Dialog *****//
public boolean AlertDialogCreation()
{
//***** File Control And Creating An Dialog Interface if this is first usage *****//
File file = getApplicationContext().getFileStreamPath("First.txt");
if(!file.exists())
{
writeToFile("First.txt", "0",true);
}
if(readFromFile("First.txt",false)[0].equals("0"))
{
newspapers = readFromFile("Choicable Newspaper.txt",true);
newspapersUrl = readFromFile("Choicable Url.txt",true);
newspapersPath = readFromFile("Choicable Path.txt",true);
checked = new boolean[newspapers.length];
builder = new AlertDialog.Builder(this,R.style.AppCompatAlertDialogStyle);
builder.setTitle("Lütfen Güncel Haberlerini Takip Etmek İstediğiniz Siteleri Seçiniz..");
builder.setItems(newspapers, null);
builder.setPositiveButton("Tamam", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
int count = 0;
for (int a = 0; a < newspapers.length; a++) {
if (checked[a]) {
count++;
writeToFile("Choosed.txt", newspapers[a], false);
writeToFile("ChoosedUrl.txt", newspapersUrl[a], false);
writeToFile("ChoosedPath.txt", newspapersPath[a], false);
}
if (a == (newspapers.length - 1) && count == 0) {
Toast.makeText(getApplicationContext(), "En az bir gazete seçmek zorundasınız..", Toast.LENGTH_LONG).show();
builder.show();
}
}
}
});
builder.setMultiChoiceItems(newspapers, checked, new DialogInterface.OnMultiChoiceClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i, boolean isChecked) {
if (isChecked) {
checked[i] = true;
} else {
checked[i] = false;
}
}
});
try
{
builder.show();
}
catch (Exception ex)
{
ex.printStackTrace();
}
writeToFile("First.txt", "1", true);
choosed = readFromFile("Choosed.txt",false);
choosedUrl = readFromFile("ChoosedUrl.txt",false);
choosedPath = readFromFile("ChoosedPath.txt",false);
if(choosed != null)
{
perNewspaper = (int) Math.ceil(newspapers.length / choosed.length);
if(perNewspaper > 15)
{
perNewspaper = 14;
}
}
return true;
}
else if(readFromFile("First.txt",false)[0].equals("1"))
{
newspapers = readFromFile("Choicable Newspaper.txt",true);
newspapersUrl = readFromFile("Choicable Url.txt",true);
newspapersPath = readFromFile("Choicable Path.txt",true);
choosed = readFromFile("Choosed.txt",false);
choosedUrl = readFromFile("ChoosedUrl.txt",false);
choosedPath = readFromFile("ChoosedPath.txt",false);
perNewspaper = (int) Math.ceil(newspapers.length / choosed.length);
if(perNewspaper > 15)
{
perNewspaper = 14;
}
return true;
}
else
{
return false;
}
//***** File Control And Creating An Dialog Interface if this is first usage *****//
}
//*****Files*****//
private void writeToFile(String fileName,String data,boolean isPrivate)
{
try
{
OutputStreamWriter outputStreamWriter;
if(isPrivate)
{
outputStreamWriter = new OutputStreamWriter(getApplicationContext().openFileOutput(fileName, MODE_PRIVATE));
}
else
{
outputStreamWriter = new OutputStreamWriter(getApplicationContext().openFileOutput(fileName, MODE_APPEND));
}
outputStreamWriter.write(data+"\r\n");
outputStreamWriter.close();
}
catch (IOException e)
{
}
}
public String[] readFromFile(String fileName,boolean isAsset)
{
String[] ret=null;
try
{
InputStream inputStream;
if(isAsset)
{
inputStream = getApplicationContext().getAssets().open(fileName);
}
else
{
inputStream = getApplicationContext().openFileInput(fileName);
}
if (inputStream != null)
{
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String receiveString;
StringBuilder stringBuilder = new StringBuilder();
while ( (receiveString = bufferedReader.readLine()) != null ) {
stringBuilder.append(receiveString).append(",");
}
inputStream.close();
ret = stringBuilder.toString().split(",");
inputStream.close();
}
}
catch (FileNotFoundException e)
{
}
catch (IOException e)
{
}
return ret;
}
I suppose you have a setpositivebutton click listener.
Start your asynktask in that listener with the desired input.
First Write your own function with parameters.
Call async task inside that function.
Now call that function by pass the form values as parameters to that function after you finish dimiss the dialog box.

java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()

I am using the following MainActivity, and I am still getting the following error message:
Caused by: java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
at android.os.Handler.<init>(Handler.java:200)
at android.os.Handler.<init>(Handler.java:114)
at android.widget.Toast$TN.<init>(Toast.java:344)
at android.widget.Toast.<init>(Toast.java:100)
at android.widget.Toast.makeText(Toast.java:258)
at com.example.edtomach.whatstheweather.MainActivity$DownloadTask.doInBackground(MainActivity.java:114)
at com.example.edtomach.whatstheweather.MainActivity$DownloadTask.doInBackground(MainActivity.java:80)
Why am I getting this error? The relevant code is here:
public class MainActivity extends Activity {
EditText cityname;
TextView resulttextview;
public void findWeather(View view) {
Log.i("cityname", cityname.getText().toString());
InputMethodManager mgr = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
mgr.hideSoftInputFromWindow(cityname.getWindowToken(), 0);
try {
String encodedCityName = URLEncoder.encode(cityname.getText().toString(), "UTF-8");
DownloadTask task = new DownloadTask();
task.execute("http://api.openweathermap.org/data/2.5/weather?q=" + encodedCityName);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(), "could not find weather", Toast.LENGTH_LONG).show();
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
cityname = (EditText) findViewById(R.id.cityname);
resulttextview = (TextView) findViewById(R.id.resulttextview);
}
public class DownloadTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... urls) {
String result = "";
URL url;
HttpURLConnection urlConnection = null;
try {
url = new URL(urls[0]);
urlConnection = (HttpURLConnection) url.openConnection();
InputStream in = urlConnection.getInputStream();
InputStreamReader reader = new InputStreamReader(in);
int data = reader.read();
while (data != -1) {
char current = (char) data;
result += current;
data = reader.read();
}
return result;
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "could not find weather", Toast.LENGTH_LONG).show();
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
try {
String message = "";
JSONObject jsonObject = new JSONObject(result);
String weatherInfo = jsonObject.getString("weather");
Log.i("Weather content", weatherInfo);
JSONArray arr = new JSONArray(weatherInfo);
for (int i = 0; i < arr.length(); i++) {
JSONObject jsonPart = arr.getJSONObject(i);
String main = "";
String description = "";
main = jsonPart.getString("main");
description = jsonPart.getString("description");
if (main != "" && description != "") {
message += main + ": " + description + "\r\n";
}
}
if (message != "") {
resulttextview.setText(message);
} else {
Toast.makeText(getApplicationContext(), "could not find weather", Toast.LENGTH_LONG).show();
}
} catch (JSONException e) {
Toast.makeText(getApplicationContext(), "could not find weather", Toast.LENGTH_LONG).show();
}
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
do not put anything can modife the main thread on the doBackground methods which herited from asynctask process , in your case you put toast message when you catch exception :
Toast.makeText(getApplicationContext(), "could not find weather", Toast.LENGTH_LONG).show();
instead that use logger message like e.g: Log.(TAG, "your message");

Android coding with mysql and php

How do I pass the data from this to the next activity passing a particular data? I use PHP+MySQL and Java on Android.
I call this by using onClick on the button:
public class LoginActivity extends Activity {
Handler h = new Handler();
/*
* Login
*/
public void Login(View view) {
EditText usernameField = (EditText)findViewById(R.id.editText_Username_L);
EditText passwordField = (EditText)findViewById(R.id.editText_Password_L);
String username = usernameField.getText().toString();
String password = passwordField.getText().toString();
new SigninActivity(this).execute(username,password);
}
/*
* Login
*/
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.login, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
//int id = item.getItemId();
//if (id == R.id.action_settings) {
// return true;
//}
return super.onOptionsItemSelected(item);
}
}
This is where my code passes and gets data:
public class SigninActivity extends AsyncTask<String,Void,String> {
private TextView roleField;
private Context context;
public SigninActivity(Context context) {
this.context = context;
}
protected void onPreExecute(){
}
#Override
protected String doInBackground(String... arg0) {
try{
String username = (String)arg0[0];
String password = (String)arg0[1];
String link="http://192.168.254.108/Login/login.php";
String data = URLEncoder.encode("username", "UTF-8")
+ "=" + URLEncoder.encode(username, "UTF-8");
data += "&" + URLEncoder.encode("password", "UTF-8")
+ "=" + URLEncoder.encode(password, "UTF-8");
URL url = new URL(link);
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter
(conn.getOutputStream());
wr.write( data );
wr.flush();
BufferedReader reader = new BufferedReader
(new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
// Read Server Response
while((line = reader.readLine()) != null)
{
sb.append(line);
break;
}
return sb.toString();
}catch(Exception e){
return new String("Exception: " + e.getMessage());
}
}
#Override
protected void onPostExecute(String result){
this.roleField.setText(result);
if(result.equals("")){
Intent i = new Intent(SigninActivity.this, DashboardActivity.class);
i.putExtra("user_id", result);
startActivity(i)
} else {
}
}
}
My PHP code:
<?php
$con=mysqli_connect("localhost","root","","d_database");
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$username = $_POST['username'];
$password = $_POST['password'];
$result = mysqli_query($con,"SELECT id FROM user where
username='$username' and password='$password'");
$row = mysqli_fetch_array($result);
$data = $row[0];
if($data){
echo $data;
}
mysqli_close($con);
?>
So I answered it, I guess I didn't do enough research.
Here's my code:
public class LoginActivity extends Activity {
Handler h = new Handler();
/*
* Login
*/
public void DishcoverLogin(View view) {
EditText usernameField = (EditText)findViewById(R.id.editText_Username_L);
EditText passwordField = (EditText)findViewById(R.id.editText_Password_L);
String username = usernameField.getText().toString();
String password = passwordField.getText().toString();
new SigninActivity(this).execute(username,password);
}
/*
* Login
*/
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.login, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
//int id = item.getItemId();
//if (id == R.id.action_settings) {
// return true;
//}
return super.onOptionsItemSelected(item);
}
private class SigninActivity extends AsyncTask<String,Void,String> {
private TextView roleField;
private Context context;
public SigninActivity(Context context) {
this.context = context;
}
protected void onPreExecute(){
}
#Override
protected String doInBackground(String... arg0) {
try{
String username = (String)arg0[0];
String password = (String)arg0[1];
String link="http://192.168.254.108/Login/d_login.php";
String data = URLEncoder.encode("username", "UTF-8")
+ "=" + URLEncoder.encode(username, "UTF-8");
data += "&" + URLEncoder.encode("password", "UTF-8")
+ "=" + URLEncoder.encode(password, "UTF-8");
URL url = new URL(link);
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter
(conn.getOutputStream());
wr.write( data );
wr.flush();
BufferedReader reader = new BufferedReader
(new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
// Read Server Response
while((line = reader.readLine()) != null)
{
sb.append(line);
break;
}
return sb.toString();
}catch(Exception e){
return new String("Exception: " + e.getMessage());
}
}
#Override
protected void onPostExecute(String result){
String vl=result.toString();
if(vl.equals("registered")){
AlertDialog.Builder alt_bld = new AlertDialog.Builder(LoginActivity.this);
alt_bld.setMessage("D Login Successfull !")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// Action for 'Yes' Button
EditText username = (EditText) findViewById(R.id.editText_Username_L);
EditText password = (EditText) findViewById(R.id.editText_Password_L);
Intent in = new Intent(getApplicationContext(), DashboardActivity.class);
in.putExtra("username", username.toString());
in.putExtra("password", password.toString());
startActivity(in);
finish();
}
});
AlertDialog alert = alt_bld.create();
// Title for AlertDialog
alert.setTitle("D Login");
// Icon for AlertDialog
alert.setIcon(R.drawable.topbar);
alert.show();
} else {
AlertDialog.Builder alt_bld = new AlertDialog.Builder(LoginActivity.this);
alt_bld.setMessage("D Login Unsuccessfull !")
.setCancelable(false)
.setNegativeButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// Action for 'NO' Button
dialog.cancel();
}
});
AlertDialog alert = alt_bld.create();
// Title for AlertDialog
alert.setTitle("D Login");
// Icon for AlertDialog
alert.setIcon(R.drawable.topbar);
alert.show();
}
}
}
}

Categories

Resources