Picasso loading image error-Android - java

MainActivity.java
class LoadProfile extends AsyncTask<String, String, String>{
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(EventHome.this);
pDialog.setMessage("Loading...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting Profile JSON
* */
protected String doInBackground(String... args) {
// Building Parameters
String json = null;
try {
List<NameValuePair> params = new ArrayList<NameValuePair>();
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(PROFILE_URL);
httppost.setEntity(new UrlEncodedFormEntity(params));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
HttpEntity resEntity = response.getEntity();
json = EntityUtils.toString(resEntity);
Log.i("All Events: ", json.toString());
} catch (Exception e) {
e.printStackTrace();
}
return json;
}
#Override
protected void onPostExecute(String json) {
super.onPostExecute(json);
// dismiss the dialog after getting all products
pDialog.dismiss();
try{
event_all = new JSONObject(json);
JSONArray user = event_all.getJSONArray("events");
JSONObject jb= user.getJSONObject(0);
String name = jb.getString("name");
String venue=jb.getString("location");
String date=jb.getString("date_d");
String descr=jb.getString("descr");
image1=jb.getString("images1");
// displaying all data in textview
tv3.setText(name);
tv4.setText(venue+", "+date);
tv5.setText(descr);
Picasso.with(this).load(image1).into(iv7);
}catch(Exception e)
{
e.printStackTrace();
}
}
}
while executing the above code I got some error on line Picasso.with(this).load(image1).into(iv7);
And the error is the method with(context) in the type Picasso is not applicable for the arguments(MainActivity.LoadProfile).
What's the problem in my coding.

You may change
Picasso.with(this).load(image1).into(iv7);
to
Picasso.with(MainActivity.this).load(image1).into(iv7);
give it a try.

You have placed Picasso.with(this).load(image1).into(iv7); this line in AsyncTask's onPostExecute. So, here this refers that AsyncTask not the context of that Activity. You have to do like this
Picasso.with(MainActivity.this).load(image1).into(iv7);

Related

Connecting Php to MySQLi in Android

I am trying to connect my Android Application with mySQL. I am getting error in LogCat.
You can find my complete code here https://github.com/rraj56801/php-connection
I am concerning only on getting all product here.
class LoadAllProducts extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(AllProductsActivity.this);
pDialog.setMessage("Loading products. Please wait...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
/**
* getting All products from url
* */
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
// getting JSON string from URL
JSONObject json = jParser.makeHttpRequest(url_all_products, "GET", params);
// Check your log cat for JSON reponse
// Log.d("All Products: ", json.toString());
try {
// Checking for SUCCESS TAG
int success = json.getInt(TAG_SUCCESS);
if (success == 1) {
// products found
// Getting Array of Products
products = json.getJSONArray(TAG_PRODUCTS);
// looping through All Products
for (int i = 0; i < products.length(); i++) {
JSONObject c = products.getJSONObject(i);
// Storing each json item in variable
String id = c.getString(TAG_PID);
String name = c.getString(TAG_NAME);
// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();
// adding each child node to HashMap key => value
map.put(TAG_PID, id);
map.put(TAG_NAME, name);
// adding HashList to ArrayList
productsList.add(map);
}
} else {
// no products found
// Launch Add New product Activity
Intent i = new Intent(getApplicationContext(),
NewProductActivity.class);
// Closing all previous activities
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog after getting all products
pDialog.dismiss();
// updating UI from Background Thread
runOnUiThread(new Runnable() {
public void run() {
/**
* Updating parsed JSON data into ListView
* */
ListAdapter adapter = new SimpleAdapter(
AllProductsActivity.this, productsList,
R.layout.list_item, new String[] { TAG_PID,
TAG_NAME},
new int[] { R.id.pid, R.id.name });
// updating listview
setListAdapter(adapter);
}
});
}
}
JSONParser code here:
public JSONObject makeHttpRequest(String url, String method,
List<NameValuePair> params) {
// Making HTTP request
try {
// check for request method
if(method == "POST"){
// request method is POST
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
if (params!=null)
httpPost.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}else if(method == "GET"){
// request method is GET
DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams());
// Setup the get request
HttpGet httpGetRequest = new HttpGet("http://127.0.0.1");
try{
// Execute the request in the client
HttpResponse httpResponse = httpclient.execute(httpGetRequest);
// Grab the response
BufferedReader reader = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent(), "UTF-8"));
json = reader.readLine();
}catch(Exception e){
Log.d("Error",e.toString());
}
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
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();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
LogCat here:
Caused by: java.lang.NullPointerException: Attempt to invoke virtual
method 'int org.json.JSONObject.getInt(java.lang.String)' on a null
object reference
at
com.example.errahulraj.phpconnection.AllProductsActivity$LoadAllProducts.doInBackground(AllProductsActivity.java:134)
at
com.example.errahulraj.phpconnection.AllProductsActivity$LoadAllProducts.doInBackground(AllProductsActivity.java:105)
at android.os.AsyncTask$2.call(AsyncTask.java:304)
you are having problem in this line.
JSONObject json = jParser.makeHttpRequest(url_all_products, "GET", params);
your json object is not getting value hence remains null. and letter you are trying to access a method of null object so the error occurs. check you url
or else check value before using
if(json != null)
{
try
{
int success = json.getInt(TAG_SUCCESS);
...
...
...
}
}

How i can println the statuscode in display with a toast when the request is fail?

Need to println HttpResponse response if the conexion is fail
private class HttpAsyncTask extends AsyncTask<String, Void, String> {
private ProgressDialog pDialog;
#Override
protected String doInBackground(String... params) {
return GET();
}
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Iniciando sesiĆ³n...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
#Override
protected void onPostExecute(String result) {
pDialog.dismiss();
}
public String GET() {
String url = "http://"+ippref+":8080/Activo/webresources/activo.entities.coreusuario/usuarios/" + usuario_ws + "/" +contrasenia_ws+ "";
String result = "";
BufferedReader inStream = null;
try {
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpRequest = new HttpGet(url);
HttpResponse response = httpClient.execute(httpRequest);
response.getStatusLine().getStatusCode();
inStream = new BufferedReader(
new InputStreamReader(
response.getEntity().getContent()));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = inStream.readLine()) != null) {
buffer.append(line);
}
inStream.close();
result = buffer.toString();
respuesta_ws = Integer.valueOf(result);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
Need printl the statuscode
Check for return status. If its value is not 200 then its a failure and toast it.
if(response.getStatusLine().getStatusCode()!=200){
Toast.makeText(getApplicationContext(),
"Request failure!",
Toast.LENGTH_LONG).show();
}
Use this :
Toast.makeText(getApplicationContext(),
response.getStatusLine().getStatusCode(),
Toast.LENGTH_LONG).show();
import android.widget.Toast
And you can change time of toast by changing Toast.LENGTH_LONG
Of course if you want to only show toast when http response is bad,then add the logic for checking the error cases and make toast there.
Hope this helps. :)

App crashes when getting data from JSON

I'm trying to retrieve data from JSON but it crashes whenever I try to retrieve data from my Android app.
// Intent i = new Intent(this,MainMenu.class);
// startActivity(i);
new AsyncTask<Void, Void, Void>()
{
ProgressDialog progressDialog;
#Override
protected void onPreExecute()
{
super.onPreExecute();
progressDialog = new ProgressDialog(JobScreen.this);
progressDialog.setMessage("Getting Items..");
progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progressDialog.setIndeterminate(true);
progressDialog.setCancelable(false);
progressDialog.show();
}
#Override
protected Void doInBackground(Void... voids)
{
try
{
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet post = new HttpGet("http://users.abdullahadhaim.com/users/WebServiceResturant.asmx/login?userName=abood&Password=123");
HttpResponse response = httpClient.execute(post);
String responseString = EntityUtils.toString(response.getEntity());
JSONArray jsonArray = new JSONArray(responseString);
JSONObject jsonObject = jsonArray.getJSONObject(0);
ed1.setText(jsonObject.getString("UserName"));
Log.e("Done", "Done");
}
catch (Exception e)
{
e.printStackTrace();
Toast.makeText(JobScreen.this, "Faild", Toast.LENGTH_SHORT).show();
}
return null;
}
#Override
protected void onPostExecute(Void aVoid)
{
super.onPostExecute(aVoid);
progressDialog.dismiss();
}
}.execute();
It looks like the problem is that you're calling ed1.setText() in the background thread.
Just move that call to onPostExecute(), and return the String value that you need from doInBackground().
Also remove the Toast from doInBackground(), and move it to onPostExecute() to be displayed if the return value of doInBackground() is null;
I just ran this, and it worked fine, and set the text to abood:
//use String for last parameter here:
new AsyncTask<Void, Void, String>() {
ProgressDialog progressDialog;
protected void onPreExecute() {
super.onPreExecute();
progressDialog = new ProgressDialog(JobScreen.this);
progressDialog.setMessage("Getting Items..");
progressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progressDialog.setIndeterminate(true);
progressDialog.setCancelable(false);
progressDialog.show();
}
//String return value:
protected String doInBackground(Void... unused) {
try
{
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet post = new HttpGet("http://users.abdullahadhaim.com/users/WebServiceResturant.asmx/login?userName=abood&Password=123");
HttpResponse response = httpClient.execute(post);
String responseString = EntityUtils.toString(response.getEntity());
JSONArray jsonArray = new JSONArray(responseString);
JSONObject jsonObject = jsonArray.getJSONObject(0);
Log.e("Done", "Done");
//return the String you need:
return jsonObject.getString("UserName");
}
catch (Exception e)
{
e.printStackTrace();
//remove this Toast:
//Toast.makeText(MainActivity.this, "Faild", Toast.LENGTH_SHORT).show();
}
return null;
}
//String parameter
protected void onPostExecute(String username) {
super.onPostExecute(username);
if (username == null){
//Toast if username is null
Toast.makeText(MainActivity.this, "Failed", Toast.LENGTH_SHORT).show();
}
else{
//Set the text here with the String received:
ed1.setText(username);
}
progressDialog.dismiss();
}
}.execute();

Attempt to invoke virtual method 'int org.json.JSONObject.getInt(java.lang.String)' on a null object reference

I'm trying to check the username/psw on my phpmyadmin database
but I can't figure out the problem.
The logcat gives me this error:
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'int org.json.JSONObject.getInt(java.lang.String)' on a null object reference
Java code:
public class MainActivity extends ActionBarActivity {
// Progress Dialog
private ProgressDialog pDialog;
private String password="";
private String userName="";
JSONParser jsonParser = new JSONParser();
// url to create new product
private static String url_login = "http://localhost/android_connect/get_login.php";
// JSON Node names
private static final String TAG_SUCCESS = "success";
Button btnSignIn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnSignIn=(Button)findViewById(R.id.buttonSignIN);
}
public void signIn(View V)
{
final Dialog dialog = new Dialog(MainActivity.this);
dialog.setContentView(R.layout.login);
dialog.setTitle("Login");
// get the Refferences of views
final EditText editTextUserName=(EditText)dialog.findViewById(R.id.editTextUserNameToLogin);
final EditText editTextPassword=(EditText)dialog.findViewById(R.id.editTextPasswordToLogin);
Button btnSignIn=(Button)dialog.findViewById(R.id.buttonSignIn);
// Set On ClickListener
btnSignIn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// get The User name and Password
userName=editTextUserName.getText().toString();
password=editTextPassword.getText().toString();
new LoginUser().execute();
}
});
dialog.show();
}
class LoginUser extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Verificoo NomeUtente & Password ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
/**
* Checking login
* */
protected String doInBackground(String... args) {
// Building Parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("use_username", userName));
params.add(new BasicNameValuePair("use_psw", password));
// getting JSON Object
// Note that create product url accepts POST method
JSONObject json = jsonParser.makeHttpRequest(url_login,
"POST", params);
// check for success tag
try {
int success = json.getInt(TAG_SUCCESS)
if (success == 1) {
//blablabla
} else {
Intent intent = getIntent();
finish();
Toast.makeText(MainActivity.this, "User Name or Password does not match", Toast.LENGTH_LONG).show();
startActivity(intent);
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String file_url) {
// dismiss the dialog once done
pDialog.dismiss();
}
}
}
#miselking
here the class JsonParser
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
// constructor
public JSONParser() {
}
// function get json from url
// by making HTTP POST or GET mehtod
public JSONObject makeHttpRequest(String url, String method,
List<NameValuePair> params) {
// Making HTTP request
try {
// check for request method
if (method == "POST") {
// request method is POST
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
httpPost.setEntity(new UrlEncodedFormEntity(params));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} else if (method == "GET") {
// request method is GET
DefaultHttpClient httpClient = new DefaultHttpClient();
String paramString = URLEncodedUtils.format(params, "utf-8");
url += "?" + paramString;
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
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();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
// return JSON String
return jObj;
}
}
check json is not null
if(json!=null){do something}
Error at this line
httpPost.setEntity(new UrlEncodedFormEntity(params));
Use this line
if (params!=null)
httpPost.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
and also in GET method use HTTP.UTF_8 instead of "utf-8"

"BasicNameValuePair" Parameters not passing into PHP from Android

I get the "No Items found" toast on the ListActivity.
Note: When I change the PHP code to "Select * from items", the entire table shows up. But when I try to filter it with the param/cat_id value in Android/Java, I get a blank
Here is code, first: php
<?php
$sql=mysql_query("SELECT * FROM items WHERE cat_id = ' ".$_REQUEST['cat_id']." '");
while($row=mysql_fetch_assoc($sql))
$output[]=$row;
print(json_encode($output));
mysql_close();
?>
(I have confirmed that "cat_id", the value I am passing into the below activity through a bundle is what it needs to be.)
Android/Java:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
cat_id = getIntent().getExtras().getString("category_id");
items = new ArrayList<String>();
new task().execute();
}
class task extends AsyncTask<String, String, Void> {
#Override
protected Void doInBackground(String... params) {
String url_select = "http://www.---.com/---/items.php";
param = new ArrayList<NameValuePair>();
param.add(new BasicNameValuePair("category_id", cat_id));
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url_select);
try {
httpPost.setEntity(new UrlEncodedFormEntity(param));
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
// read content
is = httpEntity.getContent();
} catch (Exception e) {
//
}
and farther below
protected void onPostExecute(Void v) {
String item;
try {
jArray = new JSONArray(result);
JSONObject json_data = null;
for (int i = 0; i < jArray.length(); i++) {
json_data = jArray.getJSONObject(i);
item = json_data.getString("item");
items.add(item);
}
} catch (JSONException e1) {
Toast.makeText(getBaseContext(), "No Items Found",
Toast.LENGTH_LONG).show();
} catch (ParseException e1) {
e1.printStackTrace();
}
I get the "No Items found" toast on the ListActivity.
Note: When I change the PHP code to "Select * from items", the entire table shows up. But when I try to filter it with the param/cat_id value in Android/Java, I get a blank.
On the Java code you write
param.add(new BasicNameValuePair("category_id", cat_id));
but on the PHP code you write
$_REQUEST['cat_id']
you should change it to
$_REQUEST['category_id']

Categories