Raj Raj - 19 days ago 11
Android Question

OutputStreamWriter is not working in android higher version, How to solve?

This code working in android lower version not higher version. Because

OutputStreamWriter
not working in higher version.How to solve. This code tested with Android emulator 2.2(working) and 4.4(not working).

public class Main extends Activity {
String names,numbers,areas,citys;
ArrayList<GSdemovote> contact_data = new ArrayList<GSdemovote>();
DatabaseHandler db;
GSdemovote contact;
String n,nn,a,c;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.home);
contact_data.clear();
db = new DatabaseHandler(this);
ArrayList<GSdemovote> contact_array_from_db = db.getAllGSdemovotes();
for (int i = 0; i < contact_array_from_db.size(); i++) {

//int tidno = contact_array_from_db.get(i).getID();
names = contact_array_from_db.get(i).getName();
numbers = contact_array_from_db.get(i).getPhoneNumber();
areas = contact_array_from_db.get(i).getArea();
citys = contact_array_from_db.get(i).getCity();
execute( names,numbers,areas,citys);
Toast.makeText(getApplicationContext(), names+numbers+areas+citys, Toast.LENGTH_SHORT).show();
}


}

public void execute(String names,String numbers,String areas,String citys){

try {
n = URLEncoder.encode(names, "utf-8");
nn = URLEncoder.encode(numbers, "utf-8");
a = URLEncoder.encode(areas, "utf-8");
c = URLEncoder.encode(citys, "utf-8");

} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

BufferedReader reader=null;
String text = "";

String urlParameters = "?name="+n+"&number="+nn+"&area="+a+"&city="+c;

try {

URL url = new URL("http://10.0.2.2:8080/android/tsubba/demovotes.php");

URLConnection conn = url.openConnection();
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(urlParameters);
wr.flush();

// Get the response


reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;


while((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
text = sb.toString();
}
catch(Exception ex)
{

}
finally
{
try
{

reader.close();
}
catch(Exception ex) {}
}
}

}

Raj Raj
Answer

Get current version of device.

int currentapiVersion = android.os.Build.VERSION.SDK_INT;

Run StrictMode only Android 2.3 and 2.3 above.

if (currentapiVersion >= android.os.Build.VERSION_CODES.GINGERBREAD){
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}

Credit goes to anonymous

Comments