Loading Json data won't show - java

I am trying to make an app that takes data from google sheet in JSON format.
I have tried a couple of different codes to make the data simply apeare on the screen, but could not make this happen.
would be glad for ideas.
tried with a several codes using AsyncTask and saw it is not working. so tried a
different approach..
the following app is a blank page with a button, that when you click it , it suppose to make name list apear on the screen.
the JSON url:
https://myjson.dit.upm.es/api/bins/1anx
the XML:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<Button
android:id="#+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="10dp"
android:text="click me!"
android:layout_centerHorizontal="true"
android:layout_margin="50dp"/>
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_centerHorizontal="true"
>
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginHorizontal="150dp"
android:padding="5dp"
android:textSize="24dp"
android:id="#+id/data"
android:text="list"/>
</ScrollView>
<ListView
android:layout_width="match_parent"
android:layout_height="0dp"
android:id="#+id/userList"
/>
</RelativeLayout>
The ActivityMain.Java :
package com.example.webdownload;
import androidx.appcompat.app.AppCompatActivity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.example.webdownload.databinding.ActivityMainBinding;
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.util.ArrayList;
import java.util.concurrent.ExecutionException;
public class MainActivity extends AppCompatActivity {
ActivityMainBinding binding;
ArrayList<String> userList;
ArrayAdapter<String> listAdapter;
Handler mainHandler= new Handler();
ProgressDialog progressDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = ActivityMainBinding.inflate(getLayoutInflater());
setContentView(binding.getRoot());
initializeUserList();
binding.data.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new fetchData().start();
}
});
}
private void initializeUserList() {
userList = new ArrayList<>();
listAdapter=new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,userList);
binding.userList.setAdapter(listAdapter);
}
class fetchData extends Thread{
String data = "";
#Override
public void run() {
mainHandler.post(new Runnable() {
#Override
public void run() {
progressDialog =new ProgressDialog(MainActivity.this);
progressDialog.setMessage("Fetching Data");
progressDialog.setCancelable(false);
progressDialog.show();
}
});
try {
URL url =new URL("http://myjson.dit.upm.es/api/bins/1anx");
HttpURLConnection httpURLConnection=(HttpURLConnection) url.openConnection();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(inputStream));
String line;
while ((line= bufferedReader.readLine())!= null){
data = data + line;
}
if(!data.isEmpty()){
JSONObject jsonObject = new JSONObject(data);
JSONArray users = jsonObject.getJSONArray("Users");
userList.clear();
for(int i =0;i<users.length();i++){
JSONObject names = users.getJSONObject(i);
String name = names.getString("name");
userList.add(name);
}
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
mainHandler.post(new Runnable() {
#Override
public void run() {
if(progressDialog.isShowing())
progressDialog.dismiss();
listAdapter.notifyDataSetChanged();
}
});
}
}
}

I Think This is happening because your JSON URL have some spelling mistake
The spelling of name (namr) is wrong
You can check your json url - Your wrong json url

Related

Unable to start activity ComponentInfo{com.example.myapplication/com.example.myapplication.MainActivity}

Main activity.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#color/colorPrimary"
android:orientation="vertical"
tools:context=".MainActivity">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="5dp"
android:orientation="horizontal">
<EditText
android:id="#+id/editText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="4"
android:background="#android:color/white"
android:ems="10"
android:hint="Add a Note"
android:textColor="#android:color/black"
android:inputType="textPersonName" />
<Button
android:id="#+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="Button" />
</LinearLayout>
<ListView
android:id="#+id/list"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>
MainActivity.java
package com.example.myapplication;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListAdapter;
import android.widget.ListView;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
EditText item;
Button add;
ListView listView;
ArrayList<String> itemList = new ArrayList<>();
ArrayAdapter<String> arrayAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
item = findViewById(R.id.editText);
add = findViewById(R.id.button);
listView = findViewById(R.id.list);
itemList = FileHelper.readData(this);
arrayAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1,android.R.id.text1,itemList);
listView.setAdapter(arrayAdapter);
add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String itemName = item.getText().toString();
itemList.add(itemName);
item.setText("");
FileHelper.writeData(itemList,getApplicationContext());
arrayAdapter.notifyDataSetChanged();
}
});
}
}
FileHelper.java
package com.example.myapplication;
import android.content.Context;
import android.os.Build;
import androidx.annotation.RequiresApi;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
public class FileHelper {
public static final String FILENAME = "listinfo.dat";
public static void writeData(ArrayList<String> item, Context context)
{
try {
FileOutputStream fos = context.openFileOutput(FILENAME, Context.MODE_PRIVATE);
ObjectOutputStream oas = new ObjectOutputStream(fos);
oas.writeObject(item);
oas.close();
} catch (FileNotFoundException e){
e.printStackTrace();
}catch (IOException e){
e.printStackTrace();
}
}
public static ArrayList<String> readData(Context context){
ArrayList<String> itemList = null;
try {
FileInputStream fis = context.openFileInput(FILENAME);
ObjectInputStream ois = new ObjectInputStream(fis);
try {
itemList = (ArrayList<String>) ois.readObject();
} catch (ClassNotFoundException e) {
itemList = new ArrayList<>();
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return itemList;
}
}
This gives me an error and the app crashes before it starts
I get the following error message:
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.myapplication, PID: 7111
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.myapplication/com.example.myapplication.MainActivity}: java.lang.NullPointerException: Attempt to invoke interface method 'int java.util.List.size()' on a null object reference
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2778)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2856)
at android.app.ActivityThread.-wrap11(Unknown Source:0)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1589)
ObjectInputStream ois = new ObjectInputStream(fis);
is returning null. this is not caught in try/catch as well so its crashing

I have made an application to fetch JSON data from a link. But whenever i click on the button , i don't get any data

I have made a button, on which, when i click the data is supposed to show up. But it's not. I don't know what's the problem. I don't get any errors and the app also works fine.
I have already given the internet permission so there no issue for that.
Here are the code files
MainActivity.java
package com.example.apiactivity;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
Button click;
public static TextView data;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
click=(Button) findViewById(R.id.button);
data=(TextView) findViewById(R.id.fetcheddata);
click.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
fetchData process= new fetchData();
process.execute();
}
});
}
}
fetchData.java
package com.example.apiactivity;
import android.os.AsyncTask;
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;
public class fetchData extends AsyncTask<Void,Void,Void> {
String data="";
String dataParsed="";
String singleParsed="";
#Override
protected Void doInBackground(Void... voids) {
try {
URL url=new URL("https://oneglobal.in/api/UserApi/Login");
HttpURLConnection httpURLConnection=(HttpURLConnection) url.openConnection();
InputStream inputStream = httpURLConnection.getInputStream();
BufferedReader bufferedReader= new BufferedReader(new InputStreamReader(inputStream));
String line="";
while (line!=null){
line=bufferedReader.readLine();
data= data + line;
}
JSONArray JA=new JSONArray(data);
for (int i=0;i<JA.length();i++){
JSONObject JO= (JSONObject) JA.get(i);
singleParsed= "Email:" + JO.get("Email") + "\n" + "Password:" + JO.get("Password") + "\n";
dataParsed = dataParsed+ singleParsed + "\n";
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
MainActivity.data.setText(this.data);
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="CLick me!"
android:id="#+id/button"
android:layout_marginBottom="10dp"
/>
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="#+id/button">
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="5dp"
android:textSize="24sp"
android:id="#+id/fetcheddata"
android:hint="Fetched data here"
/>
</ScrollView>
</RelativeLayout>
Whenever i click on the button, I want the json data on my screen in table view.
you have to send the user name and the password to the login api
and it is better to use retrofit or even volley to integrate with the remote api

android app crashes while trying to register a user

I'm trying to insert data user to MySQL from the app, as registering a user, but every time it will crash
I changed the code and used one from an instructor in Udemy, but it still.. crashes
I was thinking it's an internet connection problem, but it wasn't.. the internet works just fine.
what I am doing wrong here?
Layout, pRegister
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".pRegister"
android:background="#color/Background">
<EditText
android:id="#+id/pID"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginStart="20dp"
android:layout_marginTop="30dp"
android:ems="10"
android:inputType="number"
android:hint="#string/regID"
android:backgroundTint="#color/white"
android:textColorHint="#color/white" />
<EditText
android:id="#+id/pPhoneNo"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/pID"
android:layout_centerHorizontal="true"
android:layout_marginStart="20dp"
android:layout_marginTop="10dp"
android:ems="10"
android:inputType="number"
android:importantForAutofill="auto"
android:hint="#string/phoneNo"
android:backgroundTint="#color/white"
android:textColorHint="#color/white" />
<Button
android:id="#+id/login"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/pPhoneNo"
android:layout_centerHorizontal="true"
android:layout_marginStart="20dp"
android:layout_marginTop="20dp"
android:backgroundTint="#color/white"
android:textColor="#color/textButton"
android:textAllCaps="false"
android:text="#string/regbutton"
android:onClick="register"
/>
</RelativeLayout>
java activity,
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
public class pRegister extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_p_register);
}
// register function
public void register (View view) {
Intent intent = new Intent(this, Insert.class);
startActivity(intent);
}
}
Insert.java
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.EditText;
public class Insert extends AppCompatActivity {
EditText eID, ePhoneNo;
String id, phoneNo;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_p_register);
eID = (EditText) findViewById(R.id.pID);
ePhoneNo = (EditText) findViewById(R.id.pPhoneNo);
}
public void register (View view) {
id = eID.getText().toString();
phoneNo = ePhoneNo.getText().toString();
// for java class background task
String method= "register";
backgroundTask backgroundTask= new backgroundTask(this);
backgroundTask.execute(method,id, phoneNo);
finish();
}
}
background Task.java
import android.content.Context;
import android.os.AsyncTask;
import android.widget.Toast;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
public class backgroundTask extends AsyncTask<String,Void,String> {
Context ctx;
backgroundTask(Context ctx){this.ctx=ctx;}
protected String doInBackground(String... params) {
// background pRegister
String reg_url = "/insert.php";
String method = params[0];
if(method.equals("register")){
String id = params[1];
String phoneNo = params[2];
try {
URL url= new URL(reg_url);
HttpURLConnection httpURLConnection= (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestMethod("POST");
httpURLConnection.setDoOutput(true);
OutputStream os= httpURLConnection.getOutputStream();
BufferedWriter bufferedWriter= new BufferedWriter(new OutputStreamWriter(os,"UTF-8"));
String data= URLEncoder.encode("name", "UTF-8")+"="+URLEncoder.encode(id,"UTF-8")+"&"+
URLEncoder.encode("email","UTF-8")+"="+URLEncoder.encode(phoneNo,"UTF-8");
bufferedWriter.write(data);
bufferedWriter.flush();
bufferedWriter.close();
os.close();
InputStream IS= httpURLConnection.getInputStream();
IS.close();
return "Registration success";
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(String result) {
Toast.makeText(ctx, result, Toast.LENGTH_LONG).show();
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
}
insert.php
<?php
require "connect.php";
$id= $_POST["id"];
$phoneNo= $_POST["phoneNo"];
$height= $_POST ["height"];
$weight= $_POST["weight"];
$bloodType= $_POST["bloodType"];
$country= $_POST["country"];
$gender= $_POST["gender"];
$sql = "INSERT into patient (`id`, `phoneNo`) VALUES (`$id`, `$phoneNo`);";
if ($conn->query($sql) === TRUE) {
echo "data added successfully";
} else {
echo "Error adding data: " . $conn->error;
}
$conn->close();
?>

Go to full image screen

I have made an android app to display image from firebase into recycler view and when user click a image it has to go to its full screen page and have tried a several times but it just shows the blank activity
You can use PhotoView library (com.github.chrisbanes.photoview) to show full screen picture as below:
Piccaso is used here to show images, but you can use other image libraries such as Fresco, Glide .
ActivityLargeImageView
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.View;
import android.view.Window;
import android.widget.ProgressBar;
import android.widget.Toast;
import com.github.chrisbanes.photoview.PhotoView;
import com.github.chrisbanes.photoview.PhotoViewAttacher;
import com.squareup.picasso.Callback;
import com.squareup.picasso.Picasso;
import java.io.File;
import butterknife.BindView;
import butterknife.ButterKnife;
public class ActivityLargeImageView extends FragmentActivity {
#BindView(R.id.photoview_image)
PhotoView photoviewImage;
#BindView(R.id.progressbar)
ProgressBar progressBar;
File mFile;
PhotoViewAttacher mAttacher;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_large_image_view);
ButterKnife.bind(this);
progressBar.setVisibility(View.VISIBLE);
String img_url = getIntent().getExtras().getString("image_url");
try {
mFile = new File(img_url);
} catch (Exception ex) {
}
if (mFile.exists()) {
Picasso.with(getApplicationContext()).load(mFile).into(photoviewImage, imageLoadedCallback);
} else {
Picasso.with(getApplicationContext()).load(img_url).into(photoviewImage, imageLoadedCallback);
}
}
Callback imageLoadedCallback = new Callback() {
#Override
public void onSuccess() {
if (mAttacher != null) {
mAttacher.update();
} else {
mAttacher = new PhotoViewAttacher(photoviewImage);
}
progressBar.setVisibility(View.GONE);
}
#Override
public void onError() {
Toast.makeText(getApplicationContext(), getResources().getString(R.string.error_message_connection_to_server), Toast.LENGTH_LONG).show();
}
};
}
XML File
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_vertical"
android:background="#000000"
android:orientation="vertical" >
<com.github.chrisbanes.photoview.PhotoView
android:id="#+id/photoview_image"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<ProgressBar
android:id="#+id/progressbar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center" />
</FrameLayout>

Keep API data in an array

I am developing a basic quiz app but stuck in API part. In the API, we have a "question", "choices", "choice" and "correct" keywords. I want to keep "question" and "choice" keywords' values in an array or different arrays, add fragment as long as question number, also add these questions and choices to fragment activity. I shared a sample screenshot of how it should look like. Layour is not important that much, I need Java code only.If you can help me, I would be grateful. Thank you.
Click for screenshot
This is my MainActivity.java
package myusarisoy.quizmasters;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
Frag frag = new Frag();
ViewPager vp;
RequestQueue requestQueue;
String[] abc, cba;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
vp = findViewById(R.id.vp);
requestQueue = Volley.newRequestQueue(this);
FragmentPagerAdapter fpa = new FragmentPagerAdapter(getSupportFragmentManager()) {
#Override
public Fragment getItem(final int position) {
String url = "https://private-anon-a98702efdd-quizmasters.apiary-mock.com/questions";
final JsonArrayRequest request = new JsonArrayRequest(Request.Method.GET, url, null,
new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
try {
for(int i = 0; i < response.length(); i++) {
JSONObject jrResponse = response.getJSONObject(i);
String question = jrResponse.getString("question");
abc = new String[question.length()];
JSONArray choiceArray = jrResponse.getJSONArray("choices");
for(int j = 0; j < choiceArray.length(); j++) {
JSONObject currentChoice = choiceArray.getJSONObject(j);
String choice = currentChoice.getString("choice");
cba = new String[choice.length()];
String q = abc[i];
String c = cba[j];
Bundle b = new Bundle() ;
b.putString("tvQ", q);
b.putString("tvC", c);
frag.setArguments(b);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.e("myusarisoy", "Error...");
}
});
requestQueue.add(request);
return frag;
}
#Override
public int getCount() {
return abc.length;
}
};
// Set PagerAdapter to ViewPager
vp.setAdapter(fpa);
}
public void importantTask() {
Log.e("myusarisoy", "Important Task...");
}
}
This my activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<android.support.v4.view.ViewPager
android:id="#+id/vp"
android:layout_width="match_parent"
android:layout_height="match_parent">
</android.support.v4.view.ViewPager>
</LinearLayout>
This my Frag.java
package myusarisoy.quizmasters;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class Frag extends Fragment {
View root;
TextView tvQuestion, tvChoices;
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
root = inflater.inflate(R.layout.activity_frag, container, false);
tvQuestion = root.findViewById(R.id.tvq);
tvChoices = root.findViewById(R.id.tvc);
String tvQ = getArguments().getString("tvQ");
String tvC = getArguments().getString("tvC");
tvQuestion.setText(tvQ);
tvChoices.setText(tvC);
MainActivity ma = (MainActivity) getActivity();
ma.importantTask();
return root;
}
}
This is my activity_frag.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".Frag">
<TextView
android:layout_marginTop="200sp"
android:id="#+id/tvq"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:textSize="20sp"
android:textColor="#000000"
android:textStyle="bold"
android:text="Question"
android:gravity="center"/>
<TextView
android:layout_marginTop="50sp"
android:id="#+id/tvc"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:textSize="17sp"
android:textColor="#000000"
android:textStyle="bold"
android:text="Answers"
android:gravity="center"/>
</LinearLayout>
I think you got this a bit backwards.
You'll need to get the questions, then build a list of Fragments, then build an adapter.
That would look like this
// directly in onCreate
final List<Frag> frags = new ArrayList<>();
String url = "https://private-anon-a98702efdd-quizmasters.apiary-mock.com/questions";
final JsonArrayRequest request = new JsonArrayRequest(Request.Method.GET, url, null, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
frags.clear();
try {
for(int i = 0; i < response.length(); i++) {
JSONObject jrResponse = response.getJSONObject(i);
String question = jrResponse.getString("question");
abc = new String[question.length()];
JSONArray choiceArray = jrResponse.getJSONArray("choices");
// TODO: parse the JSON to get arguments
Frag f = new Frag();
f.setArguments(...); // set the arguments
frags.add(f); // store for the adapter
} catch (JSONException e) {
e.printStackTrace();
}
// Create a PagerAdapter here using list of Fragments
// set adapter to viewpager here
} // end of onResponse
Then, for example, getItem, you would return frags.get(position)

Categories

Resources