ANDROID :Retrieving image from parse to an android activity - java

I have a ListView created . and when I click a single item of the ListView, I'm calling an activity to show the single item View. TextView data is parsing. but when I'm trying to call an image from parse its not loading (the image is hosted in a separate location online). if any one can please tell how to load image here ??
my file url
url = new URL("file location " + statusObject.getString("image"));
edited code
URL url = null;
try {
url = new URL("https://www.gravatar.com/avatar/db5bfe41c9d21d3a5b4e5b5f6a2d776d?s=32&d=identicon&r=PG&f=1");
} catch (MalformedURLException e1) {
e1.printStackTrace();
}
Bitmap bmp = null;
try {
bmp = BitmapFactory.decodeStream(url.openConnection().getInputStream());
} catch (IOException e1) {
e1.printStackTrace();
}
txtv2.setImageBitmap(bmp);
////////////////
single item view
import android.content.*;
import android.net.*;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.*;
import android.view.View;
import android.widget.*;
import com.parse.*;
import com.parse.ParseException;
public class SingleItemView extends AppCompatActivity {
String objectId;
protected TextView txtv;
protected TextView txtv1;
protected ImageView txtv2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_single_item_view);
txtv =(TextView)findViewById(R.id.txt123);
txtv1 =(TextView)findViewById(R.id.txt1234);
txtv2 =(ImageView)findViewById(R.id.txt12345);
Intent i =getIntent();
objectId = i.getStringExtra("objectId");
ParseQuery<ParseObject> query = ParseQuery.getQuery("_User");
query.getInBackground(objectId, new GetCallback<ParseObject>() {
public void done(ParseObject object, ParseException e) {
if (e == null) {
String username = object.getString("firstname");
txtv.setText(username);
String position = object.getString("position");
txtv1.setText(position);
String img_ = object.getString("image");
txtv2.setImageURI(Uri.parse(img_));
} else {
// something went wrong
}
}
});
}
}
fragment file
import android.content.*;
import android.os.Bundle;
import android.support.v4.app.*;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.*;
import com.parse.FindCallback;
import com.parse.ParseException;
import com.parse.ParseObject;
import com.parse.ParseQuery;
import java.util.ArrayList;
import java.util.List;
public class Individuals extends android.support.v4.app.ListFragment
implements FindCallback<ParseObject> {
private List<ParseObject> mOrganization = new ArrayList<ParseObject>();
SearchView sv;
IndividualsAdaptor adaptor;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.individuals, container, false);
}
#Override
public void onViewCreated(View view, Bundle b) {
super.onViewCreated(view, b);
sv = (SearchView) view.findViewById(R.id.ser1);
adaptor = new IndividualsAdaptor(getActivity(), mOrganization);
setListAdapter(adaptor);
ParseQuery.getQuery("_User").findInBackground(this);
sv.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String text) {
return false;
}
#Override
public boolean onQueryTextChange(String text) {
adaptor.getFilter().filter(text);
return true;
}
});
}
#Override
public void done(List<ParseObject> scoreList, ParseException e) {
if (e == null) {
Log.d("score", "Retrieved " + scoreList.size() + " _User");
mOrganization.clear();
mOrganization.addAll(scoreList);
((IndividualsAdaptor) getListAdapter()).updateBackupList(mOrganization);
((IndividualsAdaptor) getListAdapter()).notifyDataSetChanged();
} else {
Log.d("score", "Error: " + e.getMessage());
}
}
#Override
public void onListItemClick(android.widget.ListView l, android.view.View v, int position, long id) {
super.onListItemClick(l, v, position, id);
ParseObject prs = mOrganization.get(position);
String objectId = prs.getObjectId();
Intent i = new Intent(getActivity(), SingleItemView.class);
i.putExtra("objectId", objectId);
startActivity(i);
}
}

Define <uses-permission android:name="android.permission.INTERNET" /> in Manifest.xml.
Then use Picasso or Gilde and parse images from their respective instances and pass image URL that you are querying from parsing. These libraries will parse URL and return image in the ImageView.
Other similar questions:
Load image from url
How to load an ImageView by URL in Android?

finally this code is working after editing some codes form the link in the answer . by this code you can
call images dynamically for each of the Object id.
URL url = null;
try {
url = new URL("image url" + object.getString("image"));
} catch (MalformedURLException e1) {
e1.printStackTrace();
}
Bitmap bmp = null;
try {
bmp = BitmapFactory.decodeStream(url.openConnection().getInputStream());
} catch (IOException e1) {
e1.printStackTrace();
}
txtv2.setImageBitmap(bmp);
// something went wrong

Related

Android Can't change imageview [duplicate]

This question already has answers here:
CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch views
(6 answers)
Closed 5 years ago.
I have code that gets an image by its name from drawables, but for some reason it can't update it.
package com.infonuascape.osrshelper.fragments;
import android.content.Context;
import android.content.SharedPreferences;
import android.graphics.drawable.Drawable;
import android.media.Image;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
import com.android.volley.toolbox.ImageLoader;
import com.infonuascape.osrshelper.R;
import com.infonuascape.osrshelper.activities.MainActivity;
import com.infonuascape.osrshelper.models.Account;
import org.json.JSONException;
import org.json.JSONObject;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
public class BankViewFragment extends OSRSFragment {
private static final String TAG = "BankViewFragment";
private static Account account;
private ListView lv;
private ImageView iv;
Handler handler;
ArrayList<HashMap<String, String>> ItemList;
public static BankViewFragment newInstance(final Account account) {
BankViewFragment fragment = new BankViewFragment();
Bundle b = new Bundle();
fragment.setArguments(b);
return fragment;
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
super.onCreateView(inflater, container, savedInstanceState);
View view = inflater.inflate(R.layout.bank_view, null);
ItemList = new ArrayList<>();
new GetItems().execute();
lv = (ListView) view.findViewById(R.id.list);
handler = new Handler(Looper.getMainLooper());
SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
String nikas = sharedPref.getString("bankname", "null");
return view;
}
public static int getResId(String resourceName, Class<?> c) {
try {
Field idField = c.getDeclaredField(resourceName);
return idField.getInt(idField);
} catch (Exception e) {
throw new RuntimeException("No resource ID found for: "
+ resourceName + " / " + c, e);
}
}
private class GetItems extends AsyncTask<Void, Void, Void> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... arg0) {
HttpHandler sh = new HttpHandler();
SharedPreferences sharedpreferences = getContext().getSharedPreferences("minescape", Context.MODE_PRIVATE);
String nikas = sharedpreferences.getString("bankname", "null");
String url = "https://api.minesca.pe/game/classic/stats?username=" + nikas;
String jsonStr = sh.makeServiceCall(url);
Log.e(TAG, "NIKAS: " + nikas);
Log.e(TAG, "ACCOUNT: " + account);
Log.e(TAG, "Response from url: " + jsonStr);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
JSONObject items = jsonObj.getJSONObject("bank");
Iterator keys = items.keys();
while(keys.hasNext()) {
String dynamicKey = (String)keys.next();
JSONObject line = items.getJSONObject(dynamicKey);
String item = line.getString("item");
//Integer image = getResId(item, Drawable.class);
final Integer image = getResources().getIdentifier(item, "drawable", getActivity().getPackageName());
String amount = line.getString("amount");
Log.e(TAG, "DAIKTAS: " + item);
Log.e(TAG, "KIEKIS: " + amount);
HashMap<String, String> contact = new HashMap<>();
String itembank = item.replaceAll("i_", "");
String itembanks = itembank.replaceAll("_", " ");
contact.put("name", itembanks);
contact.put("email", amount);
LayoutInflater inflater = LayoutInflater.from(getContext());
View view = inflater.inflate(R.layout.bank_view, null);
lv = (ListView) view.findViewById(R.id.list);
// iv = (ImageView) view.findViewById(R.id.logo);
final ImageView ims = (ImageView) lv.findViewById(R.id.logo);
handler.post(new Runnable() {
public void run() {
if(image != null) {
Log.e(TAG, "kas cia jam netinka?: " + image);
if(image == 0) {
ims.setImageResource(R.drawable.i_noted);
Log.e(TAG, "kas cia jam netinka?: " + image);
} else {
Log.e(TAG, "kas cia jam netinka?: " + image);
ims.setImageResource(image);
}
} else {
Log.e(TAG, "null?: " + image);
}
}
});
ItemList.add(contact);
}
} catch (final JSONException e) {
Log.e(TAG, "Json parsing error: " + e.getMessage());
new Runnable() {
#Override
public void run() {
Toast.makeText(getContext(),
"Json parsing error: " + e.getMessage(),
Toast.LENGTH_LONG).show();
}
};
}
} else {
Log.e(TAG, "Couldn't get json from server.");
new Runnable() {
#Override
public void run() {
Toast.makeText(getContext(),
"Couldn't get json from server!",
Toast.LENGTH_LONG).show();
}
};
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
ListAdapter adapter = new SimpleAdapter(getContext(), ItemList,
R.layout.list_item, new String[]{ "email","name"},
new int[]{R.id.email, R.id.name});
lv.setAdapter(adapter);
}
}
}
Error:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.infonuascape.osrshelper, PID: 31024
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ImageView.setImageResource(int)' on a null object reference
at com.infonuascape.osrshelper.fragments.BankViewFragment$GetItems$1.run(BankViewFragment.java:128)
at android.os.Handler.handleCallback(Handler.java:815)
at android.os.Handler.dispatchMessage(Handler.java:104)
at android.os.Looper.loop(Looper.java:194)
at android.app.ActivityThread.main(ActivityThread.java:5637)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:959)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:754)
The problem is that there's a lot of items, and most of them have the resources, but some don't and i would like to just skip those who don't have, but the main problem is that the app crashes while trying to see the bank.
You can't change Views in a non UI thread.
So in order to fix your problem just access UI related stuff in the UI thread, e.g. in onPostExecute()
Do not do this : View should not be touched in another thread except UI thread.
#Override
protected void onPostExecute(Void result) {
-->>>>> DONOT DO THIS --->>>>>lv.setAdapter(adapter);
}

Accessing the searchview query text from mainactivity

I am planning to make a news app. I have created a simple search view inside the action bar of my app.
This is the Main activity
package com.example.hp.simplenews;
import android.app.Activity;
import android.app.LoaderManager;
import android.app.SearchManager;
import android.content.Context;
import android.content.Intent;
import android.content.Loader;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.View;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SearchView;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.List;
public class MainActivity extends AppCompatActivity implements LoaderManager.LoaderCallbacks<List<News>> {
private int Newsloaderid = 1;
private Newsadapter newslistadapter;
private String search_query_input = "";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ListView newslistview = findViewById(R.id.list);
newslistadapter = new Newsadapter(this, new ArrayList<News>());
newslistview.setAdapter(newslistadapter);
LoaderManager loaderManager = getLoaderManager();
loaderManager.initLoader(Newsloaderid, null, MainActivity.this);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the options menu from XML
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.options_menu, menu);
// Get the SearchView and set the searchable configuration
SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
SearchView searchView = (SearchView) menu.findItem(R.id.search).getActionView();
// Assumes current activity is the searchable activity
searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
searchView.setIconifiedByDefault(false); // Do not iconify the widget; expand it by default
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String newtext) {
search_query_input = newtext;
return true;
}
#Override
public boolean onQueryTextChange(String query) {
return true;
}
});
return true;
}
#Override
public Loader<List<News>> onCreateLoader(int i, Bundle bundle) {
return new NewsLoader(this, search_query_input);
}
#Override
public void onLoadFinished(Loader<List<News>> loader, List<News> news) {
newslistadapter.clear();
if (news != null && !news.isEmpty()) {
newslistadapter.addAll(news);
}
}
#Override
public void onLoaderReset(Loader loader) {
newslistadapter.clear();
}
}
The SearchResultsActivity handles the HTTP request and JSON parsing.
This is the SearchResultsActivity
package com.example.hp.simplenews;
import android.app.Activity;
import android.app.LoaderManager;
import android.app.SearchManager;
import android.content.Context;
import android.content.Intent;
import android.content.Loader;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.NavUtils;
import android.text.TextUtils;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.widget.SearchView;
import android.widget.TextView;
import android.widget.Toast;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
public class SearchResultsActivity extends Activity{
String query_string = "";
private static final String LOG_TAG = SearchResultsActivity.class.getName();
public static URL createUrl(String query_url) throws MalformedURLException {
URL url = null;
String APIKey = "apiKey";
String query = "q";
try {
final String base_url = "https://newsapi.org/v2/everything?";
Uri final_url = Uri.parse(base_url).buildUpon()
.appendQueryParameter(query, query_url)
.appendQueryParameter(APIKey, "48f67c1e66994aa8a92f92a48b5f6581")
.build();
url = new URL(final_url.toString());
Log.i(LOG_TAG, "THE FINAL URL IS" + final_url);
} catch (MalformedURLException e) {
e.printStackTrace();
Log.e(LOG_TAG, "the url couldn't be made");
}
return url;
}
private static final String HTTPREQUEST(URL url) throws IOException {
String jsonresponse = "";
if (jsonresponse == null) {
return null;
}
HttpURLConnection httpURLConnection = null;
InputStream inputStream = null;
try {
httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("GET");
httpURLConnection.setReadTimeout(10000);
httpURLConnection.setConnectTimeout(150000);
httpURLConnection.connect();
if (httpURLConnection.getResponseCode() == 200) {
inputStream = httpURLConnection.getInputStream();
jsonresponse = readfromstream(inputStream);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (inputStream != null) {
inputStream.close();
}
if (httpURLConnection != null) {
httpURLConnection.disconnect();
}
}
return jsonresponse;
}
private static final String readfromstream(InputStream inputStream) throws IOException {
StringBuilder output = new StringBuilder();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, Charset.forName("UTF-8"));
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String urlline = bufferedReader.readLine();
while (urlline != null) {
output.append(urlline);
urlline = bufferedReader.readLine();
}
return output.toString();
}
private static List<News> JSONParser(String NewsJSON) throws JSONException {
if (TextUtils.isEmpty(NewsJSON)) {
return null;
}
List<News> news = new ArrayList<>();
try {
JSONObject basejson = new JSONObject(NewsJSON);
JSONArray articles = basejson.getJSONArray("articles");
for (int i = 0; i < articles.length(); i++) {
News newss = new News();
JSONObject c = articles.getJSONObject(i);
JSONObject source = c.getJSONObject("source");
newss.setMsource(source.getString("name"));
newss.setMtitle(c.getString("title"));
newss.setMdescription(c.getString("description"));
newss.setMtime(c.getString("publishedAt"));
String image = c.getString("urlToImage");
if (image != null) {
newss.setmImage(c.getString("urlToImage"));
}
newss.setNewsURL(c.getString("url"));
news.add(newss);
}
} catch (JSONException j) {
Log.e(LOG_TAG, "couldn't parse jSON");
}
return news;
}
public static List<News> fetchnews(String search_query) throws IOException, JSONException {
URL url = createUrl(search_query);
String JSONRESPONSE = null;
try {
JSONRESPONSE = HTTPREQUEST(url);
} catch (IOException j) {
j.printStackTrace();
}
List<News> news = JSONParser(JSONRESPONSE);
return news;
}
#Override
protected void onNewIntent(Intent intent) {
setIntent(intent);
try {
handleIntent(intent);
} catch (MalformedURLException e) {
e.printStackTrace();
}
}
private void handleIntent(Intent intent) throws MalformedURLException {
if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
query_string = intent.getStringExtra(SearchManager.QUERY);
Log.i(LOG_TAG, "The querytext is" + query_string);
}
}
}
This whole process of refreshing the list view is done by a AsyncTaskLoader
The custom Asyntaskloader class is copied below:
public class NewsLoader extends AsyncTaskLoader<List<News>> {
private String mUrl;
private static String LOG_TAG = NewsLoader.class.getName();
public NewsLoader(Context context, String url) {
super(context);
mUrl = url;
}
#Override
protected void onStartLoading() {
forceLoad();
}
#Override
public List<News> loadInBackground() {
if (mUrl == null) {
return null;
}
List<News> news = null;
try {
news = SearchResultsActivity.fetchnews(mUrl);
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return news;
}
}
Now I have the search query entered by the user stored in the search_query_input variable in the MainActivity.
But the app just gets stuck when I press the submit button. The override methods for the asynctaskloader are not getting executed at all.
What is happening? Any help will be much appreciated.
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener(){
onQueryTextChange(String newText){
//when user type in searchview get string as newText parameter
asynTaskMethod(newText);
}
onQueryTextSubmit(String query){
//when user press submit button in searchview get string as query parameter
asynTaskMethod(query);
}
});

Direct to android-mail client when clicking a button

hi,
this is a single Item View of a ListView. I wan't to go to email
client when clicking a Button in below fragment. there is a email
column in parse database . when clicking the button it should lead to
email client with that particular email id of this single item view .
I tried some code its not working anyone please help ??
import android.content.*;
import android.graphics.*;
import android.net.*;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.*;
import android.view.View;
import android.widget.*;
import com.parse.*;
import com.parse.ParseException;
import com.squareup.picasso.*;
import java.io.*;
import java.net.*;
public class SingleItemView extends AppCompatActivity {
String objectId;
protected TextView txtv;
protected TextView txtv1;
protected ImageView txtv2;
protected ImageView txtv3;
Button sendEmail;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_single_item_view);
txtv =(TextView)findViewById(R.id.txt123);
txtv1 =(TextView)findViewById(R.id.txt1234);
txtv2 =(ImageView)findViewById(R.id.txt12345);
txtv3 =(ImageView)findViewById(R.id.txt123456);
Intent i =getIntent();
objectId = i.getStringExtra("objectId");
ParseQuery<ParseObject> query = ParseQuery.getQuery("_User");
query.getInBackground(objectId, new GetCallback<ParseObject>() {
public void done(ParseObject object, ParseException e) {
if (e == null) {
String username = object.getString("firstname");
txtv.setText(username);
String position = object.getString("position");
txtv1.setText(position);
URL url = null;
try {
url = new URL("http://izi-dev.fr/fbc/assets/uploads/" + object.getString("image"));
} catch (MalformedURLException e1) {
e1.printStackTrace();
}
Bitmap bmp = null;
try {
bmp = BitmapFactory.decodeStream(url.openConnection().getInputStream());
} catch (IOException e1) {
e1.printStackTrace();
}
txtv2.setImageBitmap(bmp);
URL url1 = null;
try {
url = new URL("http://izi-dev.fr/fbc/assets/uploads/" + object.getString("image"));
} catch (MalformedURLException e1) {
e1.printStackTrace();
}
Bitmap bmp1 = null;
try {
bmp = BitmapFactory.decodeStream(url.openConnection().getInputStream());
} catch (IOException e1) {
e1.printStackTrace();
}
txtv3.setImageBitmap(bmp);
} else {
// something went wrong
}
}
});
sendEmail = (Button) findViewById(R.id.button5);
sendEmail.setOnClickListener((View.OnClickListener) this);
}
public void onClick(View v) {
try{
Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND);
emailIntent.putExtra(Intent.EXTRA_EMAIL , "email");
emailIntent.setType("text/plain"); // <-- HERE
startActivity(emailIntent); // <-- AND HERE
}finally {
}
}
}
Try this:
sendEmail.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(view.getId()==R.id.button5){
Intent i = new Intent(Intent.ACTION_SEND);
i.putExtra(android.content.Intent.EXTRA_EMAIL, new String[]{ emailAddress });
i.putExtra(android.content.Intent.EXTRA_SUBJECT, subject);
i.putExtra(android.content.Intent.EXTRA_TEXT, text);
startActivity(Intent.createChooser(i, "Send email"));
}
}
});
You have set the click listener in wrong way.
Implement the ClickListener
public class SingleItemView extends AppCompatActivity implements View.OnClickListener
Set the listener
sendEmail.setOnClickListener(this);
Use annotations
#Override
public void onClick(View v)
Please try that.
As i may understood correctly your problem, I suggest you to use the following plugin https://github.com/katzer/cordova-plugin-email-composer#examples. Basically with this plugin you can send HTML embodeed body with the click of a button.
cordova.plugins.email.open({
to: 'max#mustermann.de',
subject: 'Greetings',
body: '<h1>Nice greetings from Leipzig</h1>',
isHtml: true
});
Please check the documentation for further info. I hope i helped you.

Getting json response in log.d but not inside app (code included)

I am trying to use the ProductHunt API to display a list of new posts in a ListView and further expand the list item on click.
On opening the app, the Progress bar appears but after that the app screen stays blank. I think there might be some error in my OnPostExecute method, because when I added a textview to display a string, its getting displayed but my listView is not getting displayed.
I used the standard Apache HttpClient for handling api requests.
I have 4 classes,
MainActivity.java
package com.emoji.apisoup;
/**
* Created by mdhalim on 16/05/16.
*/
import java.io.IOException;
import java.util.ArrayList;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import org.apache.http.HttpClientConnection;
import org.apache.http.HttpResponse;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicHttpResponse;
import org.apache.http.protocol.HTTP;
public class MainActivity extends Activity {
private ListView lvPosts;
private ProductHuntAdapter adapterPosts;
public static final String POST_DETAIL_KEY = "posts";
private ProgressDialog pDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.phunt_main);
String serverURL = "https://api.producthunt.com/v1/posts/";
ArrayList<ProductHuntList> aPosts = new ArrayList<ProductHuntList>();
adapterPosts = new ProductHuntAdapter(MainActivity.this, aPosts);
lvPosts = (ListView) findViewById(R.id.lvPosts);
lvPosts.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
{
Intent i = new Intent(MainActivity.this, ProductHuntDetail.class);
i.putExtra(POST_DETAIL_KEY, adapterPosts.getItem(position));
startActivity(i);
}
}
});
new LongOperation().execute(serverURL);
}
private class LongOperation extends AsyncTask<String, Void, Void> {
private final HttpClient Content = new DefaultHttpClient();
private String Error = null;
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Please wait...");
pDialog.setCancelable(false);
pDialog.show();
}
protected Void doInBackground(String... urls){
JSONArray items = null;
try {
HttpGet httpget = new HttpGet(urls[0]);
httpget.setHeader("Accept","application/json");
httpget.setHeader("Content-Type","application/json");
httpget.setHeader("Authorization","Bearer 2587aa878d7334e3c89794a6b73ebffb59a06c23b82cd0f789d2ab72d2417739");
ResponseHandler<String> responseHandler = new BasicResponseHandler();
String jsonStr = Content.execute(httpget, responseHandler);
Log.d("Response: ", "> " + jsonStr);
JSONObject jsonObj = new JSONObject(jsonStr);
items = jsonObj.getJSONArray("posts");
// Parse json array into array of model objects
ArrayList<ProductHuntList> posts = ProductHuntList.fromJson(items);
// Load model objects into the adapter
for (ProductHuntList post : posts) {
adapterPosts.add(post);
}
} catch (JSONException e) {
e.printStackTrace();
} catch (IOException e) {
Error = e.getMessage();
cancel(true);
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
ArrayList<ProductHuntList> aPosts = new ArrayList<ProductHuntList>();
adapterPosts = new ProductHuntAdapter(MainActivity.this, aPosts);
lvPosts.setAdapter(adapterPosts);
}
}
}
ProductHuntList.java containing the JSON Data model and deserializer and a static method for parsing an array of JSON
package com.emoji.apisoup;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
import java.io.Serializable;
/**
* Created by mdhalim on 18/05/16.
*/
public class ProductHuntList implements Serializable {
private static final long serialVersionUID = -8959832007991513854L;
private String name;
private String tagline;
private String screenshot_url;
private String largePosterUrl;
private String discussion_Url;
private String created_at;
private int votes_count;
public String getNames() {
return name;
}
public String getCreated_at() {
return created_at;
}
public String getScreenshot_url() {
return screenshot_url;
}
public String getDiscussion_Url() {
return discussion_Url;
}
public int getVotes_count() {
return votes_count;
}
public String getLargePosterUrl() {
return largePosterUrl;
}
public String getTagline(){
return tagline;
}
public static ProductHuntList fromJson(JSONObject jsonObject) {
ProductHuntList b = new ProductHuntList();
try {
// Deserialize json into object fields
b.name = jsonObject.getString("name");
b.created_at = jsonObject.getString("created_at");
b.tagline = jsonObject.getString("tagline");
b.screenshot_url = jsonObject.getJSONObject("screenshot_url").getString("300px");
b.largePosterUrl = jsonObject.getJSONObject("screenshot_url").getString("850px");
b.votes_count = jsonObject.getInt("votes_count");
b.discussion_Url = jsonObject.getString("discussion_url");
} catch (JSONException e) {
e.printStackTrace();
return null;
}
// Return new object
return b;
}
public static ArrayList<ProductHuntList> fromJson(JSONArray jsonArray) {
ArrayList<ProductHuntList> posts = new ArrayList<ProductHuntList>(jsonArray.length());
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject productJson = null;
try {
productJson = jsonArray.getJSONObject(i);
} catch (Exception e) {
e.printStackTrace();
continue;
}
ProductHuntList post = ProductHuntList.fromJson(productJson);
if (post != null)
{
posts.add(post);
}
}
return posts;
}
}
ProductHuntAdapter.java this implements the ArrayAdapter
package com.emoji.apisoup;
/**
* Created by mdhalim on 18/05/16.
*/
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import com.squareup.picasso.Picasso;
import java.util.ArrayList;
/**
* Created by mdhalim on 18/05/16.
*/
public class ProductHuntAdapter extends ArrayAdapter<ProductHuntList> {
public ProductHuntAdapter(Context context, ArrayList<ProductHuntList> aPosts) {
super(context, 0, aPosts);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// Get the data item for this position
ProductHuntList posts = getItem(position);
// Check if an existing view is being reused, otherwise inflate the view
if (convertView == null) {
LayoutInflater inflater = LayoutInflater.from(getContext());
convertView = inflater.inflate(R.layout.item_product_hunt, null);
}
// Lookup view for data population
TextView name = (TextView) convertView.findViewById(R.id.name);
TextView created = (TextView) convertView.findViewById(R.id.created);
TextView tagline = (TextView) convertView.findViewById(R.id.tagline);
ImageView ivPosterImage = (ImageView) convertView.findViewById(R.id.ivPosterImage);
// Populate the data into the template view using the data object
name.setText(posts.getNames());
created.setText("Created On: " + posts.getCreated_at() + "%");
tagline.setText(posts.getTagline());
Picasso.with(getContext()).load(posts.getScreenshot_url()).into(ivPosterImage);
// Return the completed view to render on screen
return convertView;
}
}
and finally, a class implementing the activity for Item Details when a user clicks on any item on the list.
ProductHuntDetail
package com.emoji.apisoup;
/**
* Created by mdhalim on 18/05/16.
*/
import android.annotation.SuppressLint;
import android.app.Activity;
import android.os.Bundle;
import android.text.Html;
import android.widget.ImageView;
import android.widget.TextView;
import com.squareup.picasso.Picasso;
public class ProductHuntDetail extends Activity {
private ImageView ivPosterImage;
private TextView name;
private TextView discusUrl;
private TextView upvotes;
private TextView tagline;
private TextView created;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.product_hunt_detail);
// Fetch views
ivPosterImage = (ImageView) findViewById(R.id.ivPosterImage);
name = (TextView) findViewById(R.id.name);
discusUrl = (TextView) findViewById(R.id.discusUrl);
created = (TextView) findViewById(R.id.created);
upvotes = (TextView) findViewById(R.id.upvotes);
tagline = (TextView) findViewById(R.id.tagline);
// Load movie data
ProductHuntList posts = (ProductHuntList) getIntent().getSerializableExtra(MainActivity.POST_DETAIL_KEY);
loadMovie(posts);
}
// Populate the data for the movie
#SuppressLint("NewApi")
public void loadMovie(ProductHuntList posts) {
// Populate data
name.setText(posts.getNames());
upvotes.setText(Html.fromHtml("<b>Upvotes:</b> " + posts.getVotes_count() + "%"));
created.setText(posts.getCreated_at());
tagline.setText(posts.getTagline());
discusUrl.setText(Html.fromHtml("<b>Discussion Url:</b> " + posts.getDiscussion_Url()));
// R.drawable.large_movie_poster from
// http://content8.flixster.com/movie/11/15/86/11158674_pro.jpg -->
Picasso.with(this).load(posts.getLargePosterUrl()).
placeholder(R.drawable.large_movie_poster).
into(ivPosterImage);
}
}
I have been trying to debug this for hours :/
Your Async task is returning a void.
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
ArrayList<ProductHuntList> aPosts = new ArrayList<ProductHuntList>();
adapterPosts = new ProductHuntAdapter(MainActivity.this, aPosts);
lvPosts.setAdapter(adapterPosts);
}
As far as I can tell from the code, aPosts is empty.
I think your Async task should be -
AsyncTask<String, Void, ProductHuntAdapter>
and remove -
adapterPosts = new ProductHuntAdapter(MainActivity.this, aPosts);
You are creating and updating this in your doInBackground() method already.
I got it!
I didnt need to declare these lines again in my onPostExecute() method
ArrayList<ProductHuntList> aPosts = new ArrayList<ProductHuntList>();
adapterPosts = new ProductHuntAdapter(MainActivity.this, aPosts);
So bascially, my new onPostExecute() method goes like this
protected void onPostExecute(Void result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
lvPosts.setAdapter(adapterPosts);
}
I had been trying to find this error for last 2 hours, it was harder since, I wasn't even getting any errors. As soon as I posted it on StackOverFlow, seems like I had a divine intervention.

POST not occuring on Android?

Hey so I am not getting an error, but all my logs get initiated except for the one after HttpResponse not sure why, and on the server end I do not see any activity of a POST coming in...
here is my code:
package com.sfsfdsfds;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HTTP;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Editable;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
public class wardrobe extends Activity{
//set variable for the fields
private EditText nameField;
private Spinner typeField;
private EditText colorField;
private Spinner seasonField;
private EditText sizeField;
private EditText quantityField;
private ImageView imageField;
private ProgressBar progressBarField;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.wardrobe);
ImageView user_photo = (ImageView) findViewById(R.id.user_photo);
//button for upload image
Button uploadImageButton = (Button) findViewById(R.id.uploadImageButton);
//button for posting details
Button postWardrobe = (Button) findViewById(R.id.postButton);
//Value of fields
nameField = (EditText) findViewById(R.id.nameFieldWardrobeScreen);
typeField = (Spinner) findViewById(R.id.typeFieldWardrobeScreen);
colorField = (EditText) findViewById(R.id.colorFieldWardrobeScreen);
seasonField = (Spinner) findViewById(R.id.seasonFieldWardrobeScreen);
sizeField = (EditText) findViewById(R.id.sizeFieldWardrobeScreen);
quantityField = (EditText) findViewById(R.id.quantityFieldWardrobeScreen);
imageField = (ImageView) findViewById(R.id.user_photo);
progressBarField = (ProgressBar) findViewById(R.id.progressBarWardrobe);
progressBarField.setVisibility(View.GONE);
//Creating spinner for select/options for type field
Spinner spinnerType = (Spinner) findViewById(R.id.typeFieldWardrobeScreen);
ArrayAdapter<CharSequence> adapterTypeArray = ArrayAdapter.createFromResource(this, R.array.type_array, android.R.layout.simple_spinner_item);
adapterTypeArray.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerType.setAdapter(adapterTypeArray);
//Creating spinner for select/options for season field
Spinner spinnerSeason = (Spinner) findViewById(R.id.seasonFieldWardrobeScreen);
ArrayAdapter<CharSequence> adapterSeasonArray = ArrayAdapter.createFromResource(this, R.array.season_array, android.R.layout.simple_spinner_item);
adapterSeasonArray.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinnerSeason.setAdapter(adapterSeasonArray);
uploadImageButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
//below allows you to open the phones gallery
Image_Picker_Dialog();
}
});
postWardrobe.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
//validate input and that something was entered
if(nameField.getText().toString().length()<1 || colorField.getText().toString().length()<1 || sizeField.getText().toString().length()<1 || quantityField.getText().toString().length()<1) {
//missing required info (null was this but lets see)
Toast.makeText(getApplicationContext(), "Please complete all sections!", Toast.LENGTH_LONG).show();
} else {
JSONObject dataWardrobe = new JSONObject();
try {
dataWardrobe.put("type", typeField.getSelectedItem().toString());
dataWardrobe.put("color", colorField.getText().toString());
dataWardrobe.put("season", seasonField.getSelectedItem().toString());
dataWardrobe.put("size", sizeField.getText().toString());
dataWardrobe.put("quantity", quantityField.getText().toString());
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//make progress bar visible
progressBarField.setVisibility(View.VISIBLE);
//execute the post request
new dataSend().postData(dataWardrobe);
}
//below should send data over
}
});
}
// After the selection of image you will retun on the main activity with bitmap image
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == Utility.GALLERY_PICTURE)
{
// data contains result
// Do some task
Image_Selecting_Task(data);
} else if (requestCode == Utility.CAMERA_PICTURE)
{
// Do some task
Image_Selecting_Task(data);
}
}
public void Image_Picker_Dialog()
{
AlertDialog.Builder myAlertDialog = new AlertDialog.Builder(this);
myAlertDialog.setTitle("Pictures Option");
myAlertDialog.setMessage("Select Picture Mode");
myAlertDialog.setPositiveButton("Gallery", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface arg0, int arg1)
{
Utility.pictureActionIntent = new Intent(Intent.ACTION_GET_CONTENT, null);
Utility.pictureActionIntent.setType("image/*");
Utility.pictureActionIntent.putExtra("return-data", true);
startActivityForResult(Utility.pictureActionIntent, Utility.GALLERY_PICTURE);
}
});
myAlertDialog.setNegativeButton("Camera", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface arg0, int arg1)
{
Utility.pictureActionIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(Utility.pictureActionIntent, Utility.CAMERA_PICTURE);
}
});
myAlertDialog.show();
}
public void Image_Selecting_Task(Intent data)
{
ImageView user_photo = (ImageView) findViewById(R.id.user_photo);
try
{
Utility.uri = data.getData();
if (Utility.uri != null)
{
// User had pick an image.
Cursor cursor = getContentResolver().query(Utility.uri, new String[]
{ android.provider.MediaStore.Images.ImageColumns.DATA }, null, null, null);
cursor.moveToFirst();
// Link to the image
final String imageFilePath = cursor.getString(0);
//Assign string path to File
Utility.Default_DIR = new File(imageFilePath);
// Create new dir MY_IMAGES_DIR if not created and copy image into that dir and store that image path in valid_photo
Utility.Create_MY_IMAGES_DIR();
// Copy your image
Utility.copyFile(Utility.Default_DIR, Utility.MY_IMG_DIR);
// Get new image path and decode it
Bitmap b = Utility.decodeFile(Utility.Paste_Target_Location);
// use new copied path and use anywhere
String valid_photo = Utility.Paste_Target_Location.toString();
b = Bitmap.createScaledBitmap(b, 150, 150, true);
//set your selected image in image view
user_photo.setImageBitmap(b);
cursor.close();
} else
{
Toast toast = Toast.makeText(this, "Sorry!!! You haven't selecet any image.", Toast.LENGTH_LONG);
toast.show();
}
} catch (Exception e)
{
// you get this when you will not select any single image
Log.e("onActivityResult", "" + 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;
}
//Calling code for different selected menu options
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()) {
//show settings activity screen (main preference activity file)
case R.id.wardrobe:
Intent intent = new Intent(wardrobe.this, wardrobe.class);
startActivity(intent);
//if index button clicked in menu sub-menu options
case R.id.matches:
Toast.makeText(this, "matches was clicked!", 5).show();
//if index button clicked in menu sub-menu options
case R.id.worn:
Toast.makeText(this, "worn was clicked!", 5).show();
default:
}
return super.onOptionsItemSelected(item);
}
private class dataSend extends AsyncTask<JSONObject, Integer, Double> {
protected Double doInBackground(JSONObject... params) {
// TODO Auto-generated method stub
postData(params[0]);
return null;
}
protected void onPostExecute(Double result) {
progressBarField.setVisibility(View.GONE);
Toast.makeText(wardrobe.this, "info sent", Toast.LENGTH_LONG).show();
}
protected void onProgressUpdate(Integer... progress) {
progressBarField.setProgress(progress[0]);
}
public void postData(JSONObject dataWardrobe) {
Log.v("posting data", "poooooost");
// Create a new HttpClient and Post Header
//int TIMEOUT_MILLISEC = 10000; // = 10 seconds
HttpParams httpParams = new BasicHttpParams();
//HttpConnectionParams.setConnectionTimeout(httpParams, TIMEOUT_MILLISEC);
//HttpConnectionParams.setSoTimeout(httpParams, TIMEOUT_MILLISEC);
HttpClient httpclient = new DefaultHttpClient(httpParams);
HttpPost httppost = new HttpPost("http://127.0.0.1:3000/wardrobe");
Log.v("posteed", "posteed url");
try {
Log.v("trying data", "prep");
//add data
StringEntity se = new StringEntity( dataWardrobe.toString());
se.setContentType(new BasicHeader(HTTP.CONTENT_TYPE, "application/json"));
httppost.setEntity(se);
Log.v("posteed", "posteed 11");
// execute http post request
HttpResponse response = httpclient.execute(httppost);
Log.v("posteed", "posteed 22");
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
}
}
}
Not sure what I am doing wrong, I tried various things and trying to look up different ways to go about doing this and none of them have worked... maybe it is something more simple than I see... the problem I think lies in the private class within this class.
I haven't read your code in great detail, but I suspect a strong contributor is this:
HttpPost httppost = new HttpPost("http://127.0.0.1:3000/wardrobe");
If you're using the emulator it's probably more likely you want to connect to "10.0.2.2". which is:
Special alias to your host loopback interface (i.e., 127.0.0.1 on your
development machine)
See here for more details on the emulator networking:
http://developer.android.com/tools/devices/emulator.html#emulatornetworking

Categories

Resources