Photos from a website to android app - java

Im using ListView and Jsoup to create simple app that shows photos from a website, anyone can tell me why does the emulator crushes everytime? what's the problem with the code?
public class MainActivity extends Activity{
private ListView listView;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.listview);
listView = (ListView) findViewById( R.id.listview);
final ArrayList list = new ArrayList();
Document doc = null;
try {
doc = (Document) Jsoup.connect("http://mongol.co.il/").get();
Elements divs = ((Elements) doc).select("img[src$=.jpg]");
for (org.jsoup.nodes.Element div : divs)
{
list.add(div);
}
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
ArrayAdapter adapter = new ArrayAdapter(this,
android.R.layout.simple_list_item_1, list);
listView.setAdapter(adapter);
}
}

Hello I had this also in my application.
The solution is fairly simple:
All Networking actions have to be done in an Asyntask or Thread
I personally use an Asynctask like this:
private class LoadImages extends AsyncTask<Void, Void, Void> {
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
// Here you can do any UI operations like textview.setText("test");
}
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
Document doc = null;
try {
doc = (Document) Jsoup.connect("http://mongol.co.il/").get();
Elements divs = ((Elements) doc).select("img[src$=.jpg]");
for (org.jsoup.nodes.Element div : divs)
{
list.add(div);
}
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
return null;
}

Don't make http requests in your onCreate, this will throw an exception in ICS and above, I think, because you are blocking the UI thread.

Related

Android native ANSYNC task method not working

I am working on an android app development and I am stuck in an issue. I have used ANSYNC TASK method but now it has stopped working.
It was working fine from last many years but now it is creating problem.
Also, doinbackground() and postExecute() methods are not working (they are not called) only preExecute() method is working for me.
I am attaching code here for the reference:
class MyAsyncTask extends AsyncTask<Void, ConversationModel, Void> {
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
runOnUiThread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
heading.setText("myheading");
}
});
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
for (ConversationModel model : dataList) {
if (flagStop)
break;
publishProgress(model);
long_time = Long.parseLong(model.sound_time) * 1000 + 500;
try {
Thread.sleep(long_time);
Thread.sleep(long_extraTime);
long_extraTime = 0;
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
i++;
Log.d("i", i + " -----------------");
}
return null;
}
protected void onProgressUpdate(ConversationModel... model) {
if (i % 2 == 0) {
View v = View.inflate(Conversation1.this, arrInt_resource[0], null);
v.setAnimation(null);
TextView txtV_spn = (TextView) v.findViewById(R.id.textView_spn);
TextView txtV_eng = (TextView) v.findViewById(R.id.textView_eng);
ImageView img_sound = (ImageView) v.findViewById(R.id.imgsound_conv_spn2eng);
RelativeLayout speak_layout = (RelativeLayout) v.findViewById(R.id.speaking_layout);
heading.setText(dataList.get(0).heading);
if (flag != 1) {
txtV_spn.setText(model[0].eng_txt);
txtV_eng.setText(model[0].spn_txt);
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
if (i >= dataList.size()) {
Log.d("i", i + " ------------------");
makingcontinueImageView();
}
}
}
i think you are using .execute() method of asynctask to start execute of asynctask, change that line of code with this one
asynctask.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);

my app getting crashed when i use this threads codes

My purpose is simple,I want to creat a countdown that count from 10 to 1.I have tried using countdown given by google but I can't make it as a thread,so I use this way to creat the same function but I had a problem with this code.My app getting crashed when I use this threads code.Please help me man.
public class MainActivity extends Activity {
TextView textView;
Handler handler = new Handler(){
#Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
super.handleMessage(msg);
String string = textView.getText().toString();
int num = Integer.parseInt(string);
num = num-1;
string = Integer.toString(num);
textView.setText(string);
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.textView);
}
#Override
protected void onStart() {
// TODO Auto-generated method stub
super.onStart();
Thread myThread = new Thread(new Runnable(){
#Override
public void run() {
// TODO Auto-generated method stub
for(int i = 10; i>0;i--){
try {
Thread.sleep(1000);
//handler.sendMessage(handler.obtainMessage());
handler.sendMessage(handler.obtainMessage());
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
});
myThread.start();
}
}
Your problem isnt with the thread, its with these lines
String string = textView.getText().toString();
int num = Integer.parseInt(string);
You probably have that textView starting out with some text in the XML("Large Text"). Remove it. "Large Text" isn't a number, so when you call parseInt() on that original string its trying to convert "Large Text" to a number.
Try this code:
try {
String string = textView.getText().toString();
int num = Integer.parseInt(string);
textView.setText(String.valueOf(--num));
catch(NumberFormatException ignored){
}
with a try/catch block

Return a value from one activity to another

I want to display a message if the user types wrong password or username.
This is the class which takes the values
public class Login extends Activity {
Button submit_login;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
submit_login = (Button) findViewById(R.id.submit_login);
submit_login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub.
EditText usr_number = (EditText) findViewById(R.id.username);
EditText password_main = (EditText) findViewById(R.id.password);
String username = usr_number.getText().toString();
String password = password_main.getText().toString();
String[] Loginvalues = {username,password};
new CheckUsername().execute(Loginvalues);
}
});
}
}
Now After new CheckUsername().execute(Loginvalues); this call i want to show a message in textview( id = loginStatus)
public class CheckUsername extends AsyncTask<String, Integer, String[]> {
HttpClient Client;
JSONObject json;
final static String URL = "someurl";
#Override
protected String[] doInBackground(String... params) {
// TODO Auto-generated method stub
String username = params[0].toString();
String password = params[1].toString();
Client = new DefaultHttpClient();
try {
json = ValidateUsername(username, password);
String status = json.getString("status");
if (status.equals("ok")) {
System.out.println(json.getString("response"));
JSONObject user_values = new JSONObject(json.getString("user"));
GlobalVariables newObj = new GlobalVariables();
newObj.setUserId(user_values.getString("id"));
newObj.setUserName(user_values.getString("name"));
System.out.println(newObj.getUserId());
System.out.println(newObj.getUserName());
} else {
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
public JSONObject ValidateUsername(String username, String password)
throws ClientProtocolException, IOException, JSONException {
StringBuilder url = new StringBuilder(URL);
HttpPost post = new HttpPost(url.toString());
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("token", "ABCD"));
nameValuePairs.add(new BasicNameValuePair("func_name",
"validate_user"));
nameValuePairs.add(new BasicNameValuePair("username", username));
nameValuePairs.add(new BasicNameValuePair("password", password));
post.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = Client.execute(post);
int status = response.getStatusLine().getStatusCode();
if (status == 200) {
HttpEntity e = response.getEntity();
String data = EntityUtils.toString(e);
JSONObject statusValue = new JSONObject(data);
return statusValue;
} else {
System.out.println(status);
return null;
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}
status.equals("ok") this is the identifier which lets us know if logged or not
Thanks
It appears you might be misunderstanding the functionality of an AsyncTask, or just haven't read up on it too much. A big piece of clarification is that an AsyncTask is not an Activity. It is important to understand what an Activity is and how it is used to interact with the UI (it is one of a handful of classes that will let you do that).
Helping with your question, instead of having a separate class, just put your AsyncTask as a inner class of your main class.
public class Login extends Activity {
// Your code like onCreate and stuff
public class CheckUsername extends AsyncTask<String[], Void, String> {
// do your async task stuff
}
}
Extending on your AsyncTask, after you are done with do in background, you can return data to your class via onPostExecute()
public class CheckUsername extends AsyncTask<String[], Void, String> {
#Override
protected String doInBackground(String[]... params) {
//... do your stuff
return statusValue;
}
#Override
protected void onPostExecute(String statusValue) {
setText(statusValue);
}
}
In your main class, have a method like setText that will allow you to work with your return value as needed
public void setText(String return) {
if (return.equals("ok") { // or whatever it is supposed to equal if it's ok
// set your text to whatever, you are ok
}
else {
// set your text to whatever, bad password
}
}
In short, the design idea behind an AsyncTask is
public class AsyncTaskName extends AsyncTask<IN_PARAMETER, PROGRESS_PARAMETER, RETURN_PARAMETER> {
#Override
protected RETURN_PARAMETER doInBackground(IN_PARAMETER... params) {
// do your stuff
return (variable of type RETURN_PARAMETER);
}
#Override
protected void onProgressUpdate(PROGRESS_PARAMETER... progress) {
// do your stuff
}
#Override
protected void onPostExecute(RETURN_PARAMETER returnParam) {
// interact with your UI, like calling a method from your activity
}
}
It is worth noting that onProgressUpdate is often not needed for a task, unless you want to notify the user of the update progress of your AsyncTask directly.
AsyncTasks are meant to do operations off of the UI, but still be able to easily interact with it. The method doInBackground tells the AsyncTask that we want that done off of the UI thread, but onPostExecute tells us that we are done, close up our thread and return our data. Without onPostExecute you are floating dead in the water as far as UI interaction is concerned. You don't have to call a method from onPostExecute and can work with the UI directly (like textView.setText(returnValue);) but using a method makes it clearer that the work is being done by the Activity and not the AsyncTask itself.
you can use
protected void onPostExecute(Void unused) {
// NOTE: You can call UI Element here.
}
It might solve your problem.

NullPointerExcepction for TextView.setText() when called inside onPreExecute()

It is stated in d.android.com for onPreExecute() that it runs on the UI thread before doInBackground(Params...) so it should easily access the TextView and perform setText() method from the Activity from which it was executed().
But here in the below codes the loading TextView is privately declared inside the class SplashScreen that extends Activity. Inside the onCreate() it is linked with the TextView widget of the UI. But when AsyncTask extended class Atom the function onPreExecute() is executed which throws a NullPointerExcepction for the statement loading.setText("Loading..."); executed inside it.
Here the code
public class SplashScreen extends Activity implements AnimationListener{
...
TextView loading=null;
...
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash_screen);
try {
a = (Atom) new Atom().execute(null,null,null);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
finish();
}
...
loading = (TextView) findViewById(R.id.textView2);
....
}
public class Atom extends AsyncTask<RSSFeed, Void, RSSFeed>{
private RSSReader reader;
private RSSFeed feed = null;
private String uri = "http://website.com/feed/";
#Override
protected void onPreExecute() {
super.onPreExecute();
//------------problem----area-------------------
loading.setText("Loading...");
//------------problem----area-------------------
}
#Override
protected RSSFeed doInBackground(RSSFeed... arg0) {
reader = new RSSReader();
try {
feed = reader.load(uri);
Log.d("rss", feed.getTitle());
} catch (RSSReaderException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return feed;
}
#Override
protected void onPostExecute(RSSFeed result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
prg.cancel();
t(result.getTitle().toString());
}
}
}
The stack:
03-09 10:50:12.793: W/System.err(14214): java.lang.NullPointerException
03-09 10:50:12.813: W/System.err(14214): at in.edu.ss.er.splash.SplashScreen$Atom.onPreExecute(SplashScreen.java:158)
03-09 10:50:12.827: W/System.err(14214): at android.os.AsyncTask.executeOnExecutor(AsyncTask.java:586)
03-09 10:50:12.833: W/System.err(14214): at android.os.AsyncTask.execute(AsyncTask.java:534)
03-09 10:50:12.833: W/System.err(14214): at in.edu.ss.er.splash.SplashScreen.onCreate(SplashScreen.java:45)
Try to initialize TextView before executing asyntask. Like following.
try {
loading = (TextView) findViewById(R.id.textView2);
a = (Atom) new Atom().execute(null,null,null);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
finish();
}
I don't know this is correct or not, This my guessing, So, Please let me know what happened.
Thanks
just initialize your text view before calling AsyncTask. do something like this
loading = (TextView) findViewById(R.id.textView2);
try {
a = (Atom) new Atom().execute(null,null,null);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
finish();
}
You have to initialize your textview before then call asynctask. Change your code into following-
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash_screen);
loading = (TextView) findViewById(R.id.textView2);
try {
a = (Atom) new Atom().execute(null,null,null);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
finish();
}
}

Reading from textbox when button is pushed in android

I'm trying to retrieve the TextBox value when I press the button, but it does not work. Here is my code. Any idea?
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.httpxml);
httpstuff = (TextView) findViewById(R.id.http);
client = new DefaultHttpClient();
button = (Button)findViewById(R.id.shoppingprice);
button.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
//shoppingapi price = new shoppingapi();
et=(EditText)findViewById(R.id.text);
txt=et.getText().toString();
}
});
new Read().execute("displayprice");
}
#SuppressLint("ShowToast")
public JSONObject productprice(String productname) throws ClientProtocolException,IOException,JSONException
{
StringBuilder url = new StringBuilder(URL);
url.append(productname);
url.append("&searchType=keyword&contentType=json");
HttpGet get = new HttpGet(url.toString());
HttpResponse r = client.execute(get);
int status = r.getStatusLine().getStatusCode();
Log.d("Price", "asdasd");
if(status == 200){
HttpEntity e = r.getEntity();
String data = EntityUtils.toString(e);
jObj = new JSONObject(data);
JSONObject jsonData = jObj.getJSONObject("mercadoresult");
JSONObject jsonProducts = jsonData.getJSONObject("products");
JSONArray jsonArray = jsonProducts.getJSONArray("product");
jsonArray = (JSONArray) jsonArray.get(1);
jObj = (JSONObject)jsonArray.get(0);
return jObj;
}
else
{
Toast.makeText(MainActivity.this,"error",Toast.LENGTH_LONG).show();
return null;
}
}
public class Read extends AsyncTask<String,Integer,String>
{
#Override
protected String doInBackground(String... params) {
try {
json = productprice(txt);
return json.getString("displayprice");
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
//e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
//e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
//e.printStackTrace();
}
// TODO Auto-generated method stub
return null;
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
//super.onPostExecute(result);
//httpstuff.setText("The price of the Product is ");
httpstuff.setText(result);
httpstuff.setText(txt);
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
It shows no error but it shows txt value as blank
Because you are calling this line
new Read().execute("displayprice");
in onCreate
Where as txt value is changing when you click on button.
So you are accessing txt value before assigning it. if you want to use the value change like this and try like this
public void onClick(View arg0) {
et=(EditText)findViewById(R.id.text);
txt=et.getText().toString();
new Read().execute("displayprice");
}
});
Reference it outside Button click.
et=(EditText)findViewById(R.id.text);
Access directly inside AsynTask shown below
public class Read extends AsyncTask<String,Integer,String>
{
String txt = et.getText().toString();
#Override
protected String doInBackground(String... params) {
try {
json = productprice(txt);
return json.getString("displayprice");
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
//e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
//e.printStackTrace();
} catch (JSONException e) {
// TODO Auto-generated catch block
//e.printStackTrace();
}
// TODO Auto-generated method stub
return null;
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
//super.onPostExecute(result);
//httpstuff.setText("The price of the Product is ");
httpstuff.setText(result);
httpstuff.setText(txt);
}
}

Categories