In my activity i have an AsyncTask, in which i had overridden doInBackGround.
In the same activity i have a camera intent to open the camera and allow user to take a pic
The problem is when i call the camera intent it is triggering the doInBackGround method i overrode. Which eventually gives me a SingleClientConnManager exception which asks me to release the client before allocating it again.
Here is my activity code:
public class UserProfileActivity extends Activity {
//many instance fiels here
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.user_profile);
new LongOperation().execute("");
userImage = (ImageView) findViewById(R.id.profileImage);
userName = (TextView) findViewById(R.id.userName_profile);
userLocation = (TextView) findViewById(R.id.userLocation_profile);
editInfo = (TextView) findViewById(R.id.edit_profile);
changeImage = (TextView) findViewById(R.id.changeImage_profile);
userScore = (TextView) findViewById(R.id.userScore_profile);
friendsLabel = (TextView) findViewById(R.id.userFriends_profile);
changeImage.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
Intent cameraIntent = new Intent(
android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
//Point 1
}
});
//Point 2
}
private class LongOperation extends AsyncTask<String, Void, String> {
private InputStream is;
private StringBuilder sb;
private String result;
private ProgressDialog dialog = new ProgressDialog(context);
#Override
protected String doInBackground(String... params) {
//Point 3
try {
HttpResponse response;
HttpPost httppost = new HttpPost(
"http://www.xxxxx.com/yyyy/zzzz");
//httpclient is global to maintain sessions
response = SignUpActivity.httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
try {
BufferedReader reader = new BufferedReader(
new InputStreamReader(is, "iso-8859-1"), 8);
sb = new StringBuilder();
sb.append(reader.readLine() + "\n");
String line = "0";
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
} catch (Exception e) {
Log.e("error in reading input stream", e.toString());
}
try {
JSONObject jObj = new JSONObject(result);
String status = jObj.getString("status");
score = jObj.getInt("credits");
level = jObj.getInt("level");
image = jObj.getString("image");
fname = jObj.getString("fname");
lname = jObj.getString("lname");
city = jObj.getString("city");
email = jObj.getString("email");
clickedUserId = jObj.getInt("user_id");
JSONArray friendsJsonArray = jObj.getJSONArray("friends");
size = friendsJsonArray.length();
ArrayList<String> friendsNames = new ArrayList<String>();
friendsIds = new int[size];
for (int i = 0; i < size; i++) {
friendsNames.add(friendsJsonArray.getJSONObject(i)
.getString("name"));
friendsIds[i] = friendsJsonArray.getJSONObject(i)
.getInt("user_id");
}
adapter = new ArrayAdapter<String>(context,
R.layout.simple_listview_item, friendsNames);
} catch (Exception e) {
Log.d("error in creating json object", e.toString());
}
} catch (Exception e) {
//Point 5
Log.e("error main try", "Error in http connection" + e.toString());
}
return "Executed";
}
#Override
protected void onPostExecute(String result) {
friendsList.setAdapter(adapter);
userScore.setText(score + " points" + " level " + level);
userName.setText(fname + " " + lname);
userLocation.setText(city);
changeImage.setText("Change image");
editInfo.setText("Edit");
friendsLabel.setText("Friends");
Bitmap bitmap = null;
try {
bitmap = BitmapFactory
.decodeStream((InputStream) new URL(image).getContent());
userImage.setImageBitmap(bitmap);
} catch (MalformedURLException e1) {
e1.printStackTrace();
userImage.setImageResource(R.drawable.xxx);
} catch (IOException e2) {
e2.printStackTrace();
userImage.setImageResource(R.drawable.xxx);
}
if (dialog.isShowing()) {
dialog.dismiss();
}
}
#Override
protected void onPreExecute() {
this.dialog.setMessage("Please wait");
this.dialog.show();
}
#Override
protected void onProgressUpdate(Void... values) {
}
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
//Point 4
if (resultCode == RESULT_OK) {
if (data != null) {
photo = (Bitmap) data.getExtras().get("data");
userImage.setImageBitmap(photo);
}else{
Intent intent = new Intent(UserProfileActivity.this,
UserProfileActivity.class);
startActivity(intent);
}
} else {
Intent intent = new Intent(UserProfileActivity.this,
UserProfileActivity.class);
startActivity(intent);
}
}
}
here in the code Point 1, 2, 3, 4, 5 gives the sequence of code flow once i click the changeImage TextView.
Please help me in solving this scenario.
Thank You.
If I am correct the problem is because of your device orientation get changed when you open camera.That calls your activity's onCreate() method again
please insert this line to your activity in menifest that is causing problem
<activity
android:name="your activity" android:configChanges="keyboardHidden|orientation"
/>
Related
I want to make a voice-text bot using DialogFlow to return an Activity.
The bot works well in terms of voice-text mode .. but I want the bot to answer the user by an Activity as the user ask him !
Like an example : I want "Messi goals in world cup 2018".
Result will be the activity that i will add in Android Studio and that will include Messi pictures with his goals and so on ..
my code :
public class MainActivity extends AppCompatActivity {
private final int REQ_CODE_SPEECH_INPUT = 100;
ImageButton btnSpeak;
TextView txtSpeechInput, outputText;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnSpeak = findViewById(R.id.btnSpeak);
txtSpeechInput = findViewById(R.id.txtSpeechInput);
outputText = findViewById(R.id.outputTex);
btnSpeak.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
promptSpeechInput();
}
});
}
/**
* Showing google speech input dialog
*/
private void promptSpeechInput() {
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
// intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.getDefault());
intent.putExtra(RecognizerIntent.EXTRA_PROMPT,
"Say Something");
try {
startActivityForResult(intent, REQ_CODE_SPEECH_INPUT);
} catch (ActivityNotFoundException a) {
Toast.makeText(getApplicationContext(),
"orry! Your device doesn\\'t support speech input",
Toast.LENGTH_SHORT).show();
}
}
/**
* Receiving speech input
*/
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case REQ_CODE_SPEECH_INPUT: {
if (resultCode == RESULT_OK && null != data) {
ArrayList<String> result = data
.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
String userQuery = result.get(0);
txtSpeechInput.setText(userQuery);
RetrieveFeedTask task=new RetrieveFeedTask();
task.execute(userQuery);
}
break;
}
}
}
// Create GetText Metod
public String GetText(String query) throws UnsupportedEncodingException {
String text = "";
BufferedReader reader = null;
// Send data
try {
// Defined URL where to send data
URL url = new URL("my url");
// Send POST data request
URLConnection conn = url.openConnection();
conn.setDoOutput(true);
conn.setDoInput(true);
conn.setRequestProperty("Authorization", "Bearer client access token code");
conn.setRequestProperty("Content-Type", "application/json");
//Create JSONObject here
JSONObject jsonParam = new JSONObject();
JSONArray queryArray = new JSONArray();
queryArray.put(query);
jsonParam.put("query", queryArray);
//jsonParam.put("name", "order a medium pizza");
jsonParam.put("lang", "en");
jsonParam.put("sessionId", "1234567890");
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
Log.d("karma", "after conversion is " + jsonParam.toString());
wr.write(jsonParam.toString());
wr.flush();
Log.d("karma", "json is " + jsonParam);
// Get the server response
reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
StringBuilder sb = new StringBuilder();
String line = null;
// Read Server Response
while ((line = reader.readLine()) != null) {
// Append server response in string
sb.append(line + "\n");
}
text = sb.toString();
JSONObject object1 = new JSONObject(text);
JSONObject object = object1.getJSONObject("result");
JSONObject fulfillment = null;
String speech = null;
//if (object.has("fulfillment")) {
fulfillment = object.getJSONObject("fulfillment");
//if (fulfillment.has("speech")) {
speech = fulfillment.optString("speech");
// }
// }
Log.d("karma ", "response is " + text);
return speech;
} catch (Exception ex) {
Log.d("karma", "exception at last " + ex);
} finally {
try {
reader.close();
} catch (Exception ex) {
}
}
return null;}
class RetrieveFeedTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... voids) {
String s = null;
try {
s = GetText(voids[0]);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
Log.d("karma", "Exception occurred " + e);
}
return s;
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
outputText.setText(s);
}
}
}
You may use the Android library for Dialogflow and based on the response coming switch between different Activities or Fragments. It would be better to have one central activity for Dialogflow communication and switch between fragments or views.
I have a listview populated by the data from mysql database. It works fine but when I select an item then press back , the previous listview fecth again data from database that duplicates the items in my listview.
Here's is my code :
public class CityPage extends Activity{
Activity context;
HttpPost httppost;
StringBuffer buffer;
HttpResponse response;
HttpClient httpclient;
ProgressDialog pd;
CityAdapter cityAdapter;
ListView listCity;
ArrayList<City> records;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_city_page);
context = this;
records = new ArrayList<City>();
listCity = (ListView) findViewById(R.id.cities);
cityAdapter = new CityAdapter(context, R.layout.city_layout, R.id.city_name, records);
listCity.setAdapter(cityAdapter);
listCity.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent myIntent = new Intent(view.getContext(),City_attractions.class);
Toast.makeText(CityPage.this, "Opening", Toast.LENGTH_LONG).show();
String info1 = records.get(position).getCityName();
String info2 = records.get(position).getDescription();
myIntent.putExtra("info1", info1);
myIntent.putExtra("info2", info2);
startActivity(myIntent);
}
});
}
#Override
protected void onStart() {
super.onStart();
fetchCity fetch = new fetchCity();
fetch.execute();
}
private class fetchCity extends AsyncTask<Void, Void, Void> {
protected void onPreExecute() {
super.onPreExecute();
}
protected Void doInBackground(Void... params) {
InputStream is = null;
String result = "";
try {
httpclient = new DefaultHttpClient();
httppost = new HttpPost("http://iguideph-001-site1.btempurl.com/getcity.php");
response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
// Get our response as a String.
is = entity.getContent();
} catch (Exception e) {
if (pd != null)
pd.dismiss(); //close the dialog if error occurs
Log.e("ERROR", e.getMessage());
}
//convert response to string
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "utf-8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
} catch (Exception e) {
Log.e("ERROR", "Error converting result " + e.toString());
}
//parse json data
try {
// Remove unexpected characters that might be added to beginning of the string
result = result.substring(result.indexOf(""));
JSONArray jArray = new JSONArray(result);
for (int i = 0; i < jArray.length(); i++) {
JSONObject json_data = jArray.getJSONObject(i);
City p = new City();
p.setCityName(json_data.getString("place_name"));
p.setDescription(json_data.getString("description"));
records.add(p);
}
} catch (Exception e) {
Log.e("ERROR", "Error pasting data " + e.toString());
}
return null;
}
protected void onPostExecute(Void result) {
if (pd != null) pd.dismiss(); //close dialog
Log.e("size", records.size() + "");
cityAdapter.notifyDataSetChanged(); //notify the ListView to get new records
}
}
}
try remove those lines from onstart() and put them inside oncreate() function
fetchCity fetch = new fetchCity();
fetch.execute();
Good luck !
I've been having a lot of problems making this code work.
My main activity uses ZXing to scan a barcode, and then I want to take the result of that scan and query my API with it. I know I have to use an AsyncTask to do this, but I've never used one before and I'm having a lot of trouble with it. My goal is to query the API within the AsyncTask, and then update my upcTxt TextView element with the resulting JSON String. What am I supposed to do next in my ReadJSON code?
Here's my main activity code:
public class Barcode extends Activity implements OnClickListener {
private Button scanBtn;
private TextView formatTxt, contentTxt, upcTxt;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_barcode);
scanBtn = (Button)findViewById(R.id.scan_button);
formatTxt = (TextView)findViewById(R.id.scan_format);
contentTxt = (TextView)findViewById(R.id.scan_content);
upcTxt = (TextView)findViewById(R.id.upc);
scanBtn.setOnClickListener(this);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.barcode, menu);
return true;
}
public void onClick(View v){
//respond to clicks
if(v.getId()==R.id.scan_button){
//scan
IntentIntegrator scanIntegrator = new IntentIntegrator(this);
scanIntegrator.initiateScan();
}
}
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
//retrieve scan result
IntentResult scanningResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, intent);
if (scanningResult != null) {
//we have a result
String scanResult = scanningResult.getContents();
String scanFormat = scanningResult.getFormatName();
formatTxt.setText("FORMAT: " + scanFormat);
contentTxt.setText("CONTENT: " + scanResult);
new ReadJSON().execute(new String[] {scanResult});
} else {
Toast toast = Toast.makeText(getApplicationContext(), "No scan data received!", Toast.LENGTH_LONG);
toast.show();
}
}}
And here is my ReadJSON code:
public class ReadJSON extends AsyncTask<String, Void, Void> {
private String content;
private TextView upcTxt;
private String url;
#Override
protected Void doInBackground(String... scanResult) {
url = "REDACTED";
content = "";
HttpClient Client = new DefaultHttpClient();
HttpGet httpget = new HttpGet(url + scanResult[0]);
ResponseHandler<String> responseHandler = new BasicResponseHandler();
try {
content = Client.execute(httpget, responseHandler);
// Update upcTxt here
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
Thank you in advance.
Update: Whenever I try to run the code on my phone, I can scan the barcode just fine but then the program crashes once it tries to access the URL.
LogCat:
01-18 17:26:44.731: E/AndroidRuntime(24876): at com.peter.barcodetest.ReadJSON.doInBackground(ReadJSON.java:30)
01-18 17:26:44.731: E/AndroidRuntime(24876): at com.peter.barcodetest.ReadJSON.doInBackground(ReadJSON.java:1)
01-18 17:26:46.473: D/CrashAnrDetector(376): processName: com.peter.barcodetest
01-18 17:26:46.473: D/CrashAnrDetector(376): broadcastEvent : com.peter.barcodetest data_app_crash
01-18 17:26:46.913: D/PackageBroadcastService(26662): Received broadcast action=android.intent.action.PACKAGE_REPLACED and uri=com.peter.barcodetest
01-18 17:26:55.122: I/ActivityManager(376): Process com.peter.barcodetest (pid 24876) (adj 13) has died.
I changed your code to this:
Edited ReadJSON only
AsyncTask (edited)
public class ReadJSON extends AsyncTask<String, Integer, String> {
private String content;
private TextView upcTxt;
private String url;
private static final String TAG = "ReadJSON";
String s = "";
Context context;
ReadJSONCallBack callback;
public ReadJSONTask (Context context, ReadJSONCallBack cb) {
super();
this.callback = cb;
this.context = context;
}
#Override
protected String doInBackground(String... scanResult) {
url = "REDACTED";
HttpClient Client = new DefaultHttpClient();
HttpGet httpget = new HttpGet(url + scanResult[0]);
try {
HttpResponse response = Client.execute(httpget);
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
InputStream in = response.getEntity().getContent();
Log.d(TAG, "Got response");
InputStreamReader inputStreamReader = new InputStreamReader(in);
BufferedReader bufferedReader = new BufferedReader(
inputStreamReader);
StringBuilder stringBuilder = new StringBuilder();
String bufferedStrChunk = null;
while ((bufferedStrChunk = bufferedReader.readLine()) != null) {
stringBuilder.append(bufferedStrChunk);
}
Log.d(TAG, "Content: " + stringBuilder.toString());
return stringBuilder.toString();
// Update upcTxt here
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
protected void onPostExecute(String result) {
callback.setString(s);
}
// method for parsing JSON object
public String parseJSONObject(String output) {
try {
JSONArray jArray = new JSONArray(output);
for (int i = 0; i < jArray.length(); i++) {
JSONObject jObject = jArray.getJSONObject(i);
String id = jObject.getString("id");
String customer = jObject.getString("name");
String description = jObject.getString("description");
Long time = (Long) jObject.get("timeAsDate");
// do something
}
} catch (JSONException e) {
}
return description;
}
}
I have some data on the internet for each specific longitude and latitude. If a user inputs a particular latitude and longitude, the data is downloaded from the web and then used in further calculation. I want to save that data so that the next time the user inputs the same latitude and longitude, It bypasses the web connectivity and proceeds with the existing data.
My Input Class:
public class OpTilt extends Activity implements OnClickListener {
EditText latitude, longitude;
Button go;
String data1, data2, link, link1;
double dat1, dat2;
TextView gps;
SharedPreferences dataurl;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.optilt);
initialize();
go.setOnClickListener(this);
}
private void initialize() {
// TODO Auto-generated method stub
go = (Button) findViewById(R.id.loaddata);
latitude = (EditText) findViewById(R.id.lat);
longitude = (EditText) findViewById(R.id.lon);
dataurl = getSharedPreferences("url", 0);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
data1 = longitude.getText().toString();
data2 = latitude.getText().toString();
dat1 = Double.parseDouble(data1);
dat2 = Double.parseDouble(data2);
link = ("http://www.otilt.com/api.php?lat=" + dat2 + "&lon=" + dat1);
SharedPreferences.Editor editor = dataurl.edit();
editor.putString("key", link);
editor.commit();
Intent i = new Intent(OpTilt.this, DataRetrieve.class);
startActivity(i);
}
}
My Parsing Class:
public class DataRetrieve extends Activity {
HttpClient client;
String URL, re, element;
JSONObject json, getjson;
int i, j, statusCode;
HttpGet httpget;
HttpResponse response;
HttpEntity entity;
InputStream is;
BufferedReader reader;
StringBuilder sb, sb1;
WakeLock w;
SharedPreferences getinput, passjson;
ProgressDialog pd;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
w = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK, "tag");
super.onCreate(savedInstanceState);
w.acquire();
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.dataretrieve);
// Bundle gotBasket = getIntent().getExtras();
// URL = gotBasket.getString("key");
getinput = getSharedPreferences("url", 0);
URL = getinput.getString("key", null);
Read r = new Read();
r.execute();
}
public class Read extends AsyncTask<String, Integer, String> {
#Override
protected void onPreExecute() {
pd = new ProgressDialog(DataRetrieve.this);
pd.setTitle("Processing...");
pd.setMessage("Please wait.");
pd.setCancelable(false);
pd.setIndeterminate(true);
pd.show();
}
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
re = null;
is = null;
json = null;
try {
client = new DefaultHttpClient();
httpget = new HttpGet(URL);
response = client.execute(httpget);
entity = response.getEntity();
is = entity.getContent();
statusCode = response.getStatusLine().getStatusCode();
} catch (Exception e) {
statusCode = -1;
Log.e("log_tag", "Erro http " + e.toString());
}
if (statusCode == 200) {
try {
reader = new BufferedReader(new InputStreamReader(is,
"UTF-8"), 8);
sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
re = sb.toString();
} catch (Exception e) {
Log.e("log_tag", "Erro conversão " + e.toString());
}
}
return re;
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
pd.dismiss();
try {
json = new JSONObject(result);
getjson = json.getJSONObject("Solar");
String H[] = new String[getjson.length()];
for (i = 0, j = 1; i < getjson.length(); i++, j++) {
H[i] = getjson.getString("" + j);
}
Bundle bundle = new Bundle();
bundle.putStringArray("key1", H);
Intent f = new Intent(DataRetrieve.this, Calculator.class);
f.putExtras(bundle);
startActivity(f);
}
catch (JSONException e) {
Log.e("log_tag", "Erro dados " + e.toString());
}
}
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
w.release();
finish();
}
}
So, how can I achieve my goal?
package com.Itattooz.Gallery;
#SuppressWarnings("unused")
public class grid_layout extends Activity {
private GridView list;
private String id_folder;
private LazyAdapter1 adapter;
private Intent intent;
private String main_folder;
private JSONArray jArray;
private String result = null;
private InputStream is = null;
private StringBuilder sb = null;
private String[] r;
boolean flag1 = false, flag2 = false, flag3 = false;
private String[] sub_folder_id;
private String[] path;
private String[] sub_folder_name;
private String[] flag;
private String previouse_folder;
private String[] url;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.grid_layout);
intent = getIntent();
main_folder = intent.getStringExtra("selected_item");
new Thread(new Runnable() {
public void run() {
databaseConnectivity();
}
}).start();
list = (GridView) findViewById(R.id.list);
adapter = new LazyAdapter1(this, url, sub_folder_name);
list.setAdapter(adapter);
list.setOnItemClickListener(grid_listener);
}
#Override
public void onDestroy() {
list.setAdapter(null);
super.onDestroy();
}
// djhwawd
OnItemClickListener grid_listener = new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, int position,
long id) {
id_folder = sub_folder_id[position];
flag1 = true;
TextView text = (TextView) v.findViewById(R.id.text);
String str = (String) text.getText();
if (flag[position].equals("X")) {
//main_folder = main_folder + "/" + str.replace(" ", "%20");
// int flags = Intent.FLAG_ACTIVITY_SINGLE_TOP;
intent = new Intent(v.getContext(), grid_layout_main.class);
intent.putExtra("folder_name", main_folder.replace(" ", "%20") + "/" + str.replace(" ", "%20"));
intent.putExtra("id", sub_folder_id[position]);
startActivity(intent);
} else {
flag2=true;
main_folder = main_folder + "/" + str.replace(" ", "%20");
int flags = Intent.FLAG_ACTIVITY_SINGLE_TOP;
intent = new Intent(v.getContext(), grid_layout.class);
intent.setFlags(flags);
intent.putExtra("selected_item", main_folder);
startActivity(intent);
}
}
};
#Override
protected void onNewIntent(Intent intent) {
setIntent(intent);
new Thread(new Runnable() {
public void run() {
databaseConnectivity();
}
}).start();
adapter = new LazyAdapter1(this, url, sub_folder_name);
list.setAdapter(adapter);
adapter.imageLoader.clearCache();
adapter.notifyDataSetChanged();
list.setOnItemClickListener(grid_listener);
}
public void databaseConnectivity() {
HttpPost httppost = null;
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
try {
HttpClient httpclient = new DefaultHttpClient();
if (flag1 == false) {
nameValuePairs
.add(new BasicNameValuePair("folder", main_folder));
httppost = new HttpPost(
"http://www.itattooz.com/android/index.php");
} else if (flag1 == true) {
nameValuePairs.add(new BasicNameValuePair("sub_folder_id",
id_folder));
httppost = new HttpPost(
"http://www.itattooz.com/android/index2.php");
}
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
} catch (Exception e) {
Log.e("log_tag", "Error in http connection" + e.toString());
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
} catch (Exception e) {
Log.e("log_tag", "Error converting result " + e.toString());
}
String rt;
try {
jArray = new JSONArray(result);
path = new String[jArray.length()];
sub_folder_id = new String[jArray.length()];
sub_folder_name = new String[jArray.length()];
flag = new String[jArray.length()];
url = new String[jArray.length()];
JSONObject json_data = null;
for (int i = 0; i < jArray.length(); i++) {
json_data = jArray.getJSONObject(i);
sub_folder_id[i] = json_data.getString("id");
sub_folder_name[i] = json_data.getString("folder");
flag[i] = json_data.getString("flag");
path[i] = json_data.getString("path");
rt = "http://www.itattooz.com/itattooz/"
+ main_folder.replace(" ", "%20") + "/"
+ sub_folder_name[i].replace(" ", "%20")
+ "/cover_image/" + path[i].replace(" ", "%20");
url[i] = rt;
}
} catch (JSONException e1) {
Toast.makeText(getBaseContext(), "No Image Found",
Toast.LENGTH_LONG).show();
} catch (ParseException e1) {
e1.printStackTrace();
}
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK)) {
onResume();
Log.d(this.getClass().getName(), "back button pressed");
}
return super.onKeyDown(keyCode, event);
}
#Override
public void onResume() { // After a pause OR at startup
super.onResume();
// Refresh your stuff here
}
#Override
protected void onPause() {
super.onPause();
}
}
Hello Above is my code for a Gallery view as a grid layout ..
I researched a lot on net and got to know I should use AsyncTask for what I am trying to achieve .. Here Are few problems i am facing
I am doing something on Main thread
I want to change it to AsyncTask..
Don't know what should I do exactly to get rid of this issue.. Please Help...
use the asyncTask to handle this exception.
Please see the android developer Link
or you can see the stackoverflow Accepted answer related to this Link HERE
For exmp
class YourTask extends AsyncTask<URL, Integer, String> {
protected String doInBackground(URL... urls) {
// Fetch Data (Task A)
return "Result";
}
protected void onProgressUpdate(Integer... progress) {
// Show progress
}
protected void onPostExecute(String result) {
// Show UI after complete (Task B)
}
}
Use Async Task
or
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
use AsyncTask
or
add below code in your onCreate() method before thread starts to disable the strict mode using following code:
this is not the solution but avoids network IO on main thread so i recommend AsyncTask
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
}
also check internet permission in AndroidManifest.xml file
<uses-permission android:name="android.permission.INTERNET"/>