I had a problem here.
I have a login_activity that execute asynctask to get some result from a php file which it connects to mysql database.
public class login_main extends AppCompatActivity implements OnDataSendToActivity{
ViewPager viewPager;
CustomAdapter adapter;
ArrayList<String> image = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
//setSupportActionBar(toolbar);
String type = "getProfileImages";
RetrieveData retrieveData = new RetrieveData(this);
retrieveData.execute(type);
//After Asycntask, get the result and put back into image array
viewPager = (ViewPager) findViewById(R.id.view_pager);
adapter = new CustomAdapter(login_main.this,image);
viewPager.setAdapter(adapter);
}
public void sendData(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray result = jsonObject.getJSONArray("result");
for (int i = 0 ; i < result.length(); i++) {
JSONObject obj = result.getJSONObject(i);
String id = obj.getString("image"+i);
image.add("http://192.168.12.252/"+id+"/profile.png");
}
} catch (JSONException e) {
e.printStackTrace();
}
}
When i get the result i try to process the result by using interface from the asynctask
protected void onPostExecute(String result) {
super.onPostExecute(result);
dataSendToActivity.sendData(result);
}
Everything is working fine except that the image array always empty when i pass it to the PageAdapter. How can i pass the data back to activity from asycntask and push into the array image, by using interface, it cant work.
Or anyway i can directly process it in Asyntask and update the ViewPager.
Here is my Asynctask
public class RetrieveData extends AsyncTask<String,Void,String>{
Context context;
RetrieveData(Context ctx) {
context = ctx;
}
private OnDataSendToActivity dataSendToActivity;
public RetrieveData(Activity activity){
dataSendToActivity = (OnDataSendToActivity)activity;
}
#Override
protected String doInBackground(String... params) {
String profile_url = "http://192.168.12.252/getprofile.php";
String image_url = "http://192.168.12.252/imagelist.php";
String type = params[0];
if(type.equals("getProfile")){
try {
String user_name = params[1];
URL url = new URL(profile_url);
HttpURLConnection httpURLConnection = null;
httpURLConnection = (HttpURLConnection)url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
OutputStream outputStream = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
String post_data = URLEncoder.encode("user_name", "UTF-8")+"="+URLEncoder.encode(user_name, "UTF-8");
bufferedWriter.write(post_data);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream,"iso-8859-1"));
String result = null;
result = bufferedReader.readLine();
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
return result;
} catch (IOException e) {
e.printStackTrace();
}
}else if(type.equals("getProfileImages")){
try {
URL url = new URL(image_url);
HttpURLConnection httpURLConnection = null;
httpURLConnection = (HttpURLConnection)url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
OutputStream outputStream = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
String post_data = URLEncoder.encode("Image", "UTF-8")+"="+URLEncoder.encode("Image", "UTF-8");
bufferedWriter.write(post_data);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream,"iso-8859-1"));
String result = null;
result = bufferedReader.readLine();
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
return result;
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
dataSendToActivity.sendData(result);
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
}
The execution sequence is all messed up. by the time ur adding data to ur image array the,the empty image array has already been passed to the view pager adapter,therfore ur image array is empty.
u continue to do the same thing but instead of setting view pager adapter in onCreate() set the adapter after u call the method sendData();
modify the sendData() method like this.
public void sendData(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray result = jsonObject.getJSONArray("result");
for (int i = 0 ; i < result.length(); i++) {
JSONObject obj = result.getJSONObject(i);
String id = obj.getString("image"+i);
image.add("http://192.168.12.252/"+id+"/profile.png");
}
} catch (JSONException e) {
e.printStackTrace();
}
adapter = new CustomAdapter(login_main.this,image);//set ur image array here
viewPager.setAdapter(adapter);
}
Related
I am trying to download content of some random web content to my Logcat. I already did this many time but now I am getting only 2020-05-17 13:24:20.850 24632-24632/com.example.jsondownload I/RezultatĀ URLa:: { and nothing else.Content is some random JSON small sample and I want to show it in my logcat, and nothing else.
I added internet permission.
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String string = "https://api.openweathermap.org/data/2.5/weather?q=London,uk&appid=6...3";
DownloadAsync downloadAsync = new DownloadAsync();
downloadAsync.execute(string);
}
public static class DownloadAsync extends AsyncTask<String,Void,String> {
#Override
protected String doInBackground(String... strings) {
StringBuilder rezultat = new StringBuilder();
URL url;
HttpURLConnection httpURLConnection;
try {
url = new URL(strings[0]);
httpURLConnection = (HttpURLConnection) url.openConnection();
InputStream inputStream = httpURLConnection.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
int podaci = inputStreamReader.read();
while (podaci!=-1){
char trenutnoSlovoKojeSeCita = (char) podaci;
rezultat.append(trenutnoSlovoKojeSeCita);
podaci = inputStream.read();
}
return rezultat.toString();
}
catch (Exception e){
e.printStackTrace();
return "Neuspesno";
}
}
#Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
Log.i("Rezultat URLa: ",s);
}
}
}
I find a solution: I added BufferReader:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String string = "https://api.openweathermap.org/data/2.5/weather?q=Belgrade&appid=6c5022949de1b8e8448bc7232238dcf3";
DownloadAsync downloadAsync = new DownloadAsync();
downloadAsync.execute(string);
}
public static class DownloadAsync extends AsyncTask<String,Void,String> {
#Override
protected String doInBackground(String... strings) {
StringBuilder rezultat = new StringBuilder();
URL url;
HttpURLConnection httpURLConnection;
try {
url = new URL(strings[0]);
httpURLConnection = (HttpURLConnection) url.openConnection();
InputStream inputStream = httpURLConnection.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, Charset.forName("UTF-8"));
BufferedReader reader = new BufferedReader(inputStreamReader);
String line = reader.readLine();
while (line!=null){
rezultat.append(line);
line = reader.readLine();
}
return rezultat.toString();
}
catch (Exception e){
e.printStackTrace();
return "Neuspesno " ;
}
}
#Override
protected void onPostExecute(String rezultat) {
super.onPostExecute(rezultat);
try {
JSONObject jsonObject = new JSONObject(rezultat);
String weatherInfo = jsonObject.getString("weather");
JSONArray arr = new JSONArray(weatherInfo);
for (int i = 0; i < arr.length();i++){
JSONObject jsonObject1 = arr.getJSONObject(i);
String main = jsonObject1.getString("main");
String desc = jsonObject1.getString("description");
Log.i("main: ",main);
Log.i("description: ",desc);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
Basically, I want to start a new activity after login using the database. How can I do that?
This is my login class
public class login extends AppCompatActivity {
EditText username;
EditText password;
Button btn_login;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
username = (EditText) findViewById(R.id.username);
password = (EditText) findViewById(R.id.password);
btn_login = (Button) findViewById(R.id.btn_login);
btn_login.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String user = username.getText().toString();
String pass = password.getText().toString();
String type = "login";
System.out.println("IN Onclick login");
BackgroundTask backgroundTask = new BackgroundTask(getApplicationContext());
backgroundTask.execute(type,user,pass);
if(backgroundTask.statusOK.equals("true")) {
Intent loginIntent = new Intent(login.this,loggedIn.class);
startActivity(loginIntent);
}
}
});
}
}
You can see in the code above that I am using this code to start my new activity after successful login, but this is not starting a new activity. I don't know why?
if(backgroundTask.statusOK.equals("true")) {
Intent loginIntent = new Intent(login.this,loggedIn.class);
startActivity(loginIntent);
}
This is BackgroundTask class
public class BackgroundTask extends AsyncTask<String, String, String> {
Context context;
public String statusOK="false";
BackgroundTask(Context ctx){
this.context = ctx;
}
#Override
protected String doInBackground(String... strings) {
System.out.println("In doin");
String type = strings[0];
String loginURL = "http://192.168.10.119/log/login.php";
String regURL = "http://192.168.10.119/log/log.php";
if(type.equals("reg")){
String name = strings[1];
String pass = strings[2];
try{
URL url = new URL(regURL);
try {
HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
OutputStream outputStream = httpURLConnection.getOutputStream();
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(outputStream,"UTF-8");
BufferedWriter bufferedWriter = new BufferedWriter(outputStreamWriter);
String insert_data = URLEncoder.encode("Username","UTF-8")+"="+URLEncoder.encode(name,"UTF-8")+
"&"+URLEncoder.encode("Password","UTF-8")+ "=" +URLEncoder.encode(pass,"UTF-8");
bufferedWriter.write(insert_data);
bufferedWriter.flush();
bufferedWriter.close();
InputStream inputStream = httpURLConnection.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream,"ISO-8859-1");
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String result="";
String line="";
StringBuilder stringBuilder = new StringBuilder();
while((bufferedReader.readLine())!= null){
stringBuilder.append(line).append("\n");
}
result = stringBuilder.toString();
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
return result;
} catch (IOException e) {
e.printStackTrace();
}
} catch (MalformedURLException e) {
e.printStackTrace();
}
}
else if(type.equals("login")){
System.out.println("In type = login");
String name1 = strings[1];
String pass1 = strings[2];
try{
URL url = new URL(loginURL);
try {
System.out.println("In type = login try");
HttpURLConnection httpURLConnection = (HttpURLConnection)url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
OutputStream outputStream = httpURLConnection.getOutputStream();
OutputStreamWriter outputStreamWriter = new OutputStreamWriter(outputStream,"UTF-8");
BufferedWriter bufferedWriter = new BufferedWriter(outputStreamWriter);
String login_data = URLEncoder.encode("Username","UTF-8")+"="+URLEncoder.encode(name1,"UTF-8")+
"&"+URLEncoder.encode("Password","UTF-8")+ "=" +URLEncoder.encode(pass1,"UTF-8");
bufferedWriter.write(login_data);
bufferedWriter.flush();
bufferedWriter.close();
InputStream inputStream = httpURLConnection.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream,"ISO-8859-1");
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String result="";
String line="";
StringBuilder stringBuilder = new StringBuilder();
while((bufferedReader.readLine())!= null){
stringBuilder.append(line).append("\n");
}
result = stringBuilder.toString();
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
return result;
} catch (IOException e) {
e.printStackTrace();
}
} catch (MalformedURLException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onPostExecute(String s) {
statusOk="true";
Toast.makeText(context, "Successful", Toast.LENGTH_LONG).show();
//super.onPostExecute(s);
}
}
I have checked the connection between the database and my app is established and the app is running without any error.
You can see in the code above that I have created a public variable statusOk and initialize it with "false". This variable is telling the login class that the user have entered his correct login credentials.
You can see that I have changed the value of statusOk to "true" onPostExexute method.
Now the problem is my new activity is not opening from the login class after successful login. Please give me a solution how can I open a new activity after Login with correct login credentials.
Asynctask is used to execute task in the background thread, (not the main thread from where you have called the execute() ).
Therefore in your code, if statement is executed just after you called the execute(), which still store the variable statusOK as false. Hence the condition is false.
The postExecute() method of asynctask is used to execute code in the main thread,
My suggestion: remove the if condition from the Login class, and check for the if condition in the postExecute(),
I can do only add jsonobj and json obj like in the left hand side in this picture
but if i want to add data like right hand side what code should i add to my code
(i want to know how to specific the header of json array which i want to add)
(credit code from ThinkTwiceCodeOnce)
my code is ...
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
new PostDataTask().execute("http://<myip4:port>/api/status");
}
class PostDataTask extends AsyncTask<String, Void, String> {
ProgressDialog progressDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = new ProgressDialog(MainActivity.this);
progressDialog.setMessage("Inserting data...");
progressDialog.show();
}
#Override
protected String doInBackground(String... params) {
try {
return postData(params[0]);
} catch (IOException ex) {
return "Network error !";
} catch (JSONException ex) {
return "Data Invalid !";
}
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
mResult.setText(result);
if (progressDialog != null) {
progressDialog.dismiss();
}
}
private String postData(String urlPath) throws IOException, JSONException {
StringBuilder result = new StringBuilder();
BufferedWriter bufferedWriter = null;
BufferedReader bufferedReader = null;
try {
//Create data to send to server
JSONObject dataToSend = new JSONObject();
dataToSend.put("name", "puggy");
dataToSend.put("like", "dog");
dataToSend.put("eat", "meat");
dataToSend.put("fav", "red balloon");
//Initialize and config request, then connect to server.
URL url = new URL(urlPath);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setReadTimeout(10000 /* milliseconds */);
urlConnection.setConnectTimeout(10000 /* milliseconds */);
urlConnection.setRequestMethod("POST");
urlConnection.setDoOutput(true); //enable output (body data)
urlConnection.setRequestProperty("Content-Type", "application/json");// set header
urlConnection.connect();
//Write data into server
OutputStream outputStream = urlConnection.getOutputStream();
bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream));
bufferedWriter.write(dataToSend.toString());
bufferedWriter.flush();
//Read data response from server
InputStream inputStream = urlConnection.getInputStream();
bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
String line;
while ((line = bufferedReader.readLine()) != null) {
result.append(line).append("\n");
}
} finally {
if (bufferedReader != null) {
bufferedReader.close();
}
if (bufferedWriter != null) {
bufferedWriter.close();
}
}
return result.toString();
}
}
Use dataToSend.put("profile", JSONArrayProfile) to add profile JSONArray to JSONObject.
Here is the working code. Try this:
try {
JSONObject dataToSend = new JSONObject();
// Profile
JSONArray jsonArrayProfile = new JSONArray();
// Post 1
JSONObject jsonObjectPost1 = new JSONObject();
jsonObjectPost1.put("fbname", "Think Twice Code Once");
jsonObjectPost1.put("content", "felling full");
jsonObjectPost1.put("likes", 1);
jsonObjectPost1.put("comments", 3);
// Post 2
JSONObject jsonObjectPost2 = new JSONObject();
jsonObjectPost2.put("fbname", "Think Twice Code Once");
jsonObjectPost2.put("content", "felling full");
jsonObjectPost2.put("likes", 1);
jsonObjectPost2.put("comments", 3);
// Add post1, post2 jsonObject to profile jsonArray
jsonArrayProfile.put(jsonObjectPost1);
jsonArrayProfile.put(jsonObjectPost2);
// Add profile jsonArray to jsonObject
dataToSend.put("profile", jsonArrayProfile);
Log.d("SUCCESS", "JSON: " + dataToSend.toString());
} catch (final JSONException e) {
Log.e("FAILED", "Json build error: " + e.getMessage());
}
OUTPUT:
{
"profile":[
{
"fbname":"Think Twice Code Once",
"content":"felling full",
"likes":1,
"comments":3
},
{
"fbname":"Think Twice Code Once",
"content":"felling full",
"likes":1,
"comments":3
}
]
}
You can use following code to try it.
JSONArray ja = new JSONArray();
ja.put(dataToSend);
You have to create JSON objects of this way
JSONObject dataToSend = new JSONObject();
JSONArray arrayData = new JSONArray();
dataToSend.put("profile",arrayData);
And if you want to add JSON object to your JSONArray use this
arrayData.put(JSONObject1);
arrayData.put(JSONObject2);
First of all, i am quite a newbie to android and java as i come from a web developer background.
Recently, i had try to develop and app for learning purposes, but i am facing one headache problem during the development process.
i had a main activity that triggers Asynctask to get the list of id's from my wamp database through a php file.
Part of my main activity file - login_main.java
public class login_main extends AppCompatActivity implements OnDataSendToActivity{
ViewPager viewPager;
CustomAdapter adapter;
ArrayList<String> images = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
//setSupportActionBar(toolbar);
SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", 0); // 0 - for private mode
SharedPreferences.Editor editor = pref.edit();
String username = pref.getString("username", null);
String type = "getProfileImages";
RetrieveData retrieveData = new RetrieveData(this);
retrieveData.execute(type,username);
viewPager = (ViewPager) findViewById(R.id.view_pager);
}
public void sendData(String response) {
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray result = jsonObject.getJSONArray("result");
for (int i = 0 ; i < result.length(); i++) {
JSONObject obj = result.getJSONObject(i);
String id = obj.getString("image"+i);
String url = "http://192.168.12.252/"+id+"/profile.png";
images.add(url);
}
} catch (JSONException e) {
e.printStackTrace();
}
adapter = new CustomAdapter(login_main.this,images);//set ur image array here
viewPager.setAdapter(adapter);
}
AsyncTask file
public class RetrieveData extends AsyncTask<String,Void,String>{
Context context;
RetrieveData(Context ctx) {
context = ctx;
}
private OnDataSendToActivity dataSendToActivity;
public RetrieveData(Activity activity){
dataSendToActivity = (OnDataSendToActivity)activity;
}
#Override
protected String doInBackground(String... params) {
String profile_url = "http://192.168.12.252/getprofile.php";
String image_url = "http://192.168.12.252/imagelist.php";
String type = params[0];
if(type.equals("getProfile")){
try {
String user_name = params[1];
URL url = new URL(profile_url);
HttpURLConnection httpURLConnection = null;
httpURLConnection = (HttpURLConnection)url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
OutputStream outputStream = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
String post_data = URLEncoder.encode("user_name", "UTF-8")+"="+URLEncoder.encode(user_name, "UTF-8");
bufferedWriter.write(post_data);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream,"iso-8859-1"));
String result = null;
result = bufferedReader.readLine();
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
return result;
} catch (IOException e) {
e.printStackTrace();
}
}else if(type.equals("getProfileImages")){
try {
String user_name = params[1];
URL url = new URL(image_url);
HttpURLConnection httpURLConnection = null;
httpURLConnection = (HttpURLConnection)url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
OutputStream outputStream = httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
String post_data = URLEncoder.encode("Image", "UTF-8")+"="+URLEncoder.encode("Image", "UTF-8")+"&"+URLEncoder.encode("user_name", "UTF-8")+"="+URLEncoder.encode(user_name, "UTF-8");
bufferedWriter.write(post_data);
bufferedWriter.flush();
bufferedWriter.close();
outputStream.close();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream,"iso-8859-1"));
String result = null;
result = bufferedReader.readLine();
bufferedReader.close();
inputStream.close();
httpURLConnection.disconnect();
return result;
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
dataSendToActivity.sendData(result);
}
Page Adapter file
public class CustomAdapter extends PagerAdapter{
Activity activity;
ArrayList<String> images = new ArrayList<>();
LayoutInflater inflater;
public CustomAdapter(Activity activity, ArrayList<String> images){
this.activity = activity;
this.images = images;
}
#Override
public int getCount() {
return images.size();
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view==object;
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
inflater = (LayoutInflater)activity.getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View itemView = inflater.inflate(R.layout.swipe,container,false);
ImageView image;
image = (ImageView)itemView.findViewById(R.id.imageView);
DisplayMetrics dis = new DisplayMetrics();
activity.getWindowManager().getDefaultDisplay().getMetrics(dis);
int height = dis.heightPixels;
int width = dis.widthPixels;
image.setMinimumHeight(height);
image.setMinimumWidth(width);
try{
Picasso.with(activity.getApplicationContext())
.load(images.get(position))
.placeholder(R.mipmap.ic_launcher)
.error(R.mipmap.ic_launcher)
.into(image);
}catch (Exception ex){
}
container.addView(itemView);
return itemView;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
((ViewPager) container).removeView((View)object);
}
}
So let me explain a little bit here, whats going on here. What my app does is it will get array of ids from my phpmysql, after it get from asynctask, it send the data back to main activity using Interface which is the sendData function in main from that sendData function you can see there is a loop to loop through each id and generate a url image link and store it into a string array which the variable name is images and the page adapter will put the image into imageView in the page adapter with Picasso pluggin.
try {
JSONObject jsonObject = new JSONObject(response);
JSONArray result = jsonObject.getJSONArray("result");
for (int i = 0 ; i < result.length(); i++) {
JSONObject obj = result.getJSONObject(i);
String id = obj.getString("image"+i);
String url = "http://192.168.12.252/"+id+"/profile.png";
images.add(url);
}
} catch (JSONException e) {
e.printStackTrace();
}
adapter = new CustomAdapter(login_main.this,images);//set ur image array here
viewPager.setAdapter(adapter);
The problem is i want to make those image clickable and when it click, it will display the information for that particular id, how do map the id with those image and make them clickable and when it clicks , it do another asynctask to retrieve more detail information of that id
You can alter your Adapter class to take in an ArrayList of Ids as well:
public class CustomAdapter extends PagerAdapter{
ArrayList<String> mIds = new ArrayList<>();
public CustomAdapter(Activity activity, ArrayList<String> images, ArrayList<String> ids){
mIds = ids;
}
Then, inside your instantiateItem():
image.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view){
String clickedId = mIds.get(position);
// Do something with the selected image Id
}
});
Don't forget to change your call to new CustomAdapter(activity, images, ids) though.
I suggest that you create your own Object (Class) that have item (id, filename, ...). Pass your ArrayList<YourObjectName> into CustomAdapter.
This question already has answers here:
FileNotFoundException while getting the InputStream object from HttpURLConnection
(8 answers)
Closed 6 years ago.
My code to that sends JSON over the network works until OutputStream is invoked, but when I try actually sending the data, I get the following exception. Can anyone help me figure it out?
java.io.FileNotFoundException: http://hmkcode.appspot.com/jsonservlet
at
com.android.okhttp.internal.huc.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:238)
at app.test.testapp2.MainActivity$HttpAsyncTask.doInBackground(MainActivity.java:84)
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button) findViewById(R.id.accept);
textView = (TextView) findViewById(R.id.textView);
editName = (EditText) findViewById(R.id.editName);
editCountry = (EditText) findViewById(R.id.editCountry);
editTwitter = (EditText) findViewById(R.id.editTwitter);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
HttpAsyncTask httpAsyncTask = new HttpAsyncTask(MainActivity.this);
httpAsyncTask.execute("http://hmkcode.appspot.com/jsonservlet", editName.getText().toString(), editCountry.getText().toString(), editTwitter.getText().toString());
}
});
}
private class HttpAsyncTask extends AsyncTask<String, Void, String> {
private MainActivity mainActivity;
String result = "";
HttpAsyncTask(MainActivity mainActivity) {
this.mainActivity = mainActivity;
}
#Override
protected String doInBackground(String... strings) {
Person person = new Person();
person.setName(strings[1]);
person.setCountry(strings[2]);
person.setTwitter(strings[3]);
try {
URL url = new URL(strings[0]);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
String json = "";
JSONObject jsonObject = new JSONObject();
jsonObject.accumulate("name", "!!!");
jsonObject.accumulate("country", "###");
jsonObject.accumulate("twitter", "####");
json = jsonObject.toString();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
httpURLConnection.setDoInput(true);
httpURLConnection.setRequestProperty("Accept", "application/json");
httpURLConnection.setRequestProperty("content-type", "application/json");
InputStream is = httpURLConnection.getInputStream();
OutputStream os = httpURLConnection.getOutputStream();
os.write(json.getBytes("utf-8"));
os.flush();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(is));
String line = "";
while ((line = bufferedReader.readLine()) != null) {
result += line;
}
is.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
#Override
protected void onPostExecute(String result) {
str = result;
mainActivity.runOnUiThread(new Runnable() {
#Override
public void run() {
try {
JSONArray jsonArray = new JSONArray(str);
mainActivity.textView.setText(jsonArray.toString());
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
}
}
W/System.err: java.io.FileNotFoundException: http://hmkcode.appspot.com/jsonservlet
W/System.err: at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:238)
W/System.err: at app.test.testapp2.MainActivity$HttpAsyncTask.doInBackground(MainActivity.java:84)
.....
This is equivalent to HTTP status 404 - Not Found.